简体   繁体   中英

MyBatis dynamic ResultMap. How to return list of different POJO objects?

MyBatis mapping issue.

Suppose we have a table USERS

CREATE TABLE USERS(
   USER_ID int(10) NOT NULL AUTO_INCREMENT,
   LOGIN varchar(100) NOT NULL,
   EMAIL varchar(255),
   SALARY int(10),
   AVG_SCORE int(10),
   PRIMARY KEY ( USER_ID )
);

And there are 3 POJO classes -

public class User {
    private Long id;
    private String login;
    private String email;

...getters/setters
}

and two more classes extending User

public class Student extends User {
    private Integer score;
...getters/setters
}

public class Teacher extends User {
    private Integer salary;
...getters/setters
}

and a mapper (I use XML but actually it does not matter).

<select id="selectAll" resultMap="<dynamicResultMapHere>">
    SELECT * FROM USERS
    <some conditions here>
</select>

I would like to get List<Teacher> or List<Student> instances depending on whether SALARY column is empty or not.

How to add the dynamic results filling?

Actually the case is more complicated. I somehow need to return different results depending on query parameters.

Check documentation about discriminator . It will require a resultMap for specific fields of Student and Teacher referenced by a resultMap for User (for common fields) and a <discriminator> part.

A pseudo column will likely be required:

SELECT (CASE WHERE salary IS NULL THEN 1 ELSE 2 END) AS userType

and then

<discriminator javaType="int" column="userType">
    <case value="1" resultMap="studentResultMap" />
    <case value="2" resultMap="teacherResultMap" />
</discriminator>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM