MyBatis error converting result into Java records with an association

106 Views Asked by At

We are moving from using Java Pojo's as DTO's to records with the MyBatis framework.

The following two record types are used:

public record User(Integer cprid, String inlognaam, String upn, Boolean actief, String email, Locatie locatie, Collection<RoleExtra> rolesExtra) {}

public record RoleExtra(Role role) { }

The identifier of a user is the cprid. Location and Role are simple enums.

Having the following query in myBatis:

<select id="getAllUsers" resultMap="suezUserResult">
    SELECT g.inlognaam, g.cprid, g.upn, g.actief, g.email, g.locatie, grl.rol
    FROM suez.gebruikers g
    LEFT JOIN suez.gebruikers_rollen_link grl USING (cprid)
    WHERE cprid = 107884
    ORDER BY g.naam
</select>

results in the tuples:

 inlognaam | cprid  |             upn             | actief |            email            | locatie |   rol
-----------+--------+-----------------------------+--------+-----------------------------+---------+---------
 msmith    | 107884 | [email protected]     | t      | [email protected]     | AMC     | ROLE_PI
 msmith    | 107884 | [email protected]     | t      | [email protected]     | AMC     | ROLE_PL

The resultmaps used:

<resultMap id="suezUserResult" type="amr.bi.elsalvador.domain.suez.User">
     <constructor>
        <arg column="cprid" javaType="java.lang.Integer"/>
        <arg column="inlognaam" javaType="java.lang.String"/>
        <arg column="upn" javaType="java.lang.String"/>
        <arg column="actief" javaType="java.lang.Boolean"/>
        <arg column="email" javaType="java.lang.String"/>
        <arg column="locatie" javaType="amr.bi.elsalvador.enums.Locatie"/>
        <arg javaType="java.util.Collection" resultMap="roleExtraResult" />
    </constructor>
    <id column="cprid"/>
  </resultMap>

<resultMap type="amr.bi.elsalvador.domain.suez.RoleExtra" id="roleExtraResult">
    <constructor>
        <arg column="rol" javaType="amr.bi.elsalvador.enums.Role" />
    </constructor>
</resultMap>

When invoking getAllUsers I get an exception:

Error instantiating class amr.bi.elsalvador.domain.suez.User with invalid types
(Integer,String,String,Boolean,String,Locatie,Collection) or values 
(107884,msmith,[email protected],true,[email protected],AMC,**RoleExtra[role=Principal Investigator]**).
Cause: java.lang.IllegalArgumentException: argument type mismatch

It seems that MyBatis is trying to make two instances of User for each role ROLE_PI and ROLE_PL (hence the argument type mismatch) instead of one instance using the set of roles. What am I doing wrong?

0

There are 0 best solutions below