How to use MyBatis Optional Mapper with a One/Many relationship

24 views
Skip to first unread message

barkeldiho

unread,
Jul 18, 2019, 3:29:33 PM7/18/19
to mybatis-user

Iam trying to access data in a database via MyBatis in a Java/Spring Boot project. I recognized that when there is no data found in the database, MyBatis will return null, hence as a return type I'd like to use an Optional<CustomType>.

This feature got introduced in version 3.5.0 of mybatis. But unfortunately it does not seem to work with an additionally supplied @Results {@Result} annotation, which I am required to use to resolve a one-to-many etc. relationship for some object attributes with another method call.

Does anyone know a solution for this dilemma?

For simple objects the returntype Optional<CustomObject> works fine if one omits the @Result{@Result} annotation completely.


What works:

CustomObject:

public class CustomObject {

    private Long attribute1;

    private String attribute2;
}

MyBatis DAO:

@Select("some SQL statement with columnnames matching the object attributes")
public Optional<CustomObject> methodName(@Param("input") final String input);

What does not work:

CustomObject:

public class CustomObject {

    private Long attribute1;

    private String attribute2;

    private List<String> attribute3 = new ArrayList<>();
}

with a similar DAO method.

It works though without the Optional in this manner:

@Select("some SQL statement with columnnames matching the object attributes")
@Results(value={
        @Result(property = "attribute1", column = "attribute1"),
        @Result(property = "attribute2", column = "attribute2"),
        @Result(property = "attribute3", column = "attribute3", javaType = List.class, many=@Many(select = "getattribute3Content"))
})
public CustomType methodName(@Param("input") final String input)

Does anyone know how I can possibly set the relationship for the attribute and at the same time return an Optional of the CustomObject?

Guy Rouillier

unread,
Jul 18, 2019, 9:43:29 PM7/18/19
to mybati...@googlegroups.com
On 7/18/2019 3:29:33 PM, "'barkeldiho' via mybatis-user" <mybati...@googlegroups.com> wrote:

Iam trying to access data in a database via MyBatis in a Java/Spring Boot project. I recognized that when there is no data found in the database, MyBatis will return null, hence as a return type I'd like to use an Optional<CustomType>.


This is not always the case.  MyBatis provides an property - returnInstanceForEmptyRow - you can specify if you want an object instance to be created for an empty row.  Not exactly what you were asking, but may suffice for your needs.

--
Guy Rouillier
Reply all
Reply to author
Forward
0 new messages