Skip to content

SimpleFlatMapper JdbcMapper 1 N relationship

kevinlexus edited this page Aug 18, 2022 · 11 revisions

Since version 1.6.0 it is possible to map 1-N relationship and aggregating the N into a list in the 1.

ie.

select p.id as id, p.name as name, s.id as students_id, s.name as students_name
from professor p, students s
where p.id = s.professor_id (+)
order by p.id

for the following rows

id name students_id students_name
1 professor1 10 student1
1 professor1 20 student2

the JdbcMapper will return 2 professors with 1 students each.

0 : Professor1 { Students[ Student1 ] }
1 : Professor1 { Students[ Student2 ] }

But from 1.6.0 if you define the column "id" as a key.

JdbcMapper<Professor> mapper 
   = JdbcMapperFactory
        .newInstance()
        .addKeys("id", "students_id")
        .newMapper(Professor.class);

then the mapper will return 1 professor with 2 students.

0 : Professor1 { Students[ Student1, Student2 ] }

we are also able to identify null object on outer join. ie For the following row

id name students_id students_name
1 professor1 null null

The mapper will now return a professor with an empty list of students instead of a student with null values.

0 : Professor1 { Students[ Student1 { id:null, name :null} ] }

vs

0 : Professor1 { Students[] }

Note that the simple flat mapper can handle any number of join that way. It also possible to specify multiple field as key and to use a tuple as a root if the Professor object does not have a students list.

select p.id as p_id, p.name as p_name, s.id as s_id, s.name as s_name
from professor p, students s
where p.id = s.professor_id (+)
order by p.id
JdbcMapper<Tuple2<Professor, List<Student>>> mapper 
   = JdbcMapperFactory
        .newInstance()
        .addKeys("p_id", "s_id")
        .newMapper(new TypeReference<Tuple2<Professor, List<Student>>>(){});
Clone this wiki locally