Mybatis select with nested objects

2019-08-19 06:38发布

问题:

I am using MyBatis to do a simple select.

Assume we have the following classes:

class Book {
    private String bookName;

    public Book(String bookName){
        this.bookName = bookName;
    }

    public String getBookName(){
        return bookName;
    }
}


class Student {
    private String studentName;
    private Book book;

    public Student(){}

    // getters and setters
}

I have an annotation on a method that returns a Student object.

@Select("Select studentName, book from Students")

My Issue is that book is always null. I was under the assumption MyBatis will call the constructor with that JDBC type (in this case String) to populate book. What am I missing or doing incorrectly?

回答1:

One option is

Use @ConstructorArgs annotations to explicitly call Constructor method.

@Select("Select studentName, book from Students")
@ConstructorArgs(value = { 
@Arg(column = "studentName", javaType=java.lang.String.class),
@Arg(column = "book", javaType = java.lang.String.class)
})

and pass them to Student constructor, which calls Book constructor.



标签: java mybatis