用于集合的Java MyBatis映射器

时间:2017-12-02 04:13:50

标签: java jdbc orm mybatis builder-pattern

我正在尝试为以下java对象编写MyBatis Mapper,并且mapper的输出需要List作为返回类型。

class Blog{
private final String name;
private final String author;
private final List<Posts> posts;

// I follow builder pattern, so the below private constructor is intended for MyBatis alone
private Blog(String name, String author, List<Posts> posts){
this.name = name;
this.author= author;
this.posts= posts;

...... excluding getters and builder class as it it not relevant in this case
}

帖子对象如下所示

class Post{
private final String postName;
private final String postSummary;

// Same here as well. Private constructor only to satisfy MyBatis.
private Post(String postName, String postSummary) {
this.postName = postname;
this.postSummary = postSummary;
}

BlogRepoMapper如下:

public List<Blog> getAllBlogPosts();

BlogMapper.xml

<select id="getAllBlogPosts" resultMap = "blogResultMapper"
BLOGNAME, AUTHOR, POSTNAME, POSTSUMMARY from BLOGDETAILS>
</select>
<resultMap id="blogResultMapper" type="Blog">
 <constructor>
  <arg column="BLOGNAME" javaType="String" />
  <arg column="AUTHOR" javaType="String" />
 </constructor>
<collection property="posts" ofType="posts" resultMap="postsMapper" />
</resultMap>
<resultMap id="postsMapper" type="Posts">
 <constructor>
  <arg column="POSTNAME" javaType="String" />
  <arg column="POSTSUMMARY" javaType="String" />
 </constructor>
</resultMap>

我不确定如何编写select查询的resultmap,因为它涉及Post对象的集合。我尝试了几次但得到了以下异常

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: Error instantiating class Blog with invalid types (String,String) or values (JavaBlog, JavaAuthor). Cause: java.lang.NoSuchMethodException: Blog.<init>(java.lang.String, java.lang.String)
    at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:77) ~[mybatis-spring-1.3.1.jar:1.3.1]
    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446) ~[mybatis-spring-1.3.1.jar:1.3.1]
    at com.sun.proxy.$Proxy78.selectList(Unknown Source) ~[na:na]
    at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:230) ~[mybatis-spring-1.3.1.jar:1.3.1]
    at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137) ~[mybatis-3.4.3.jar:3.4.3]
    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75) ~[mybatis-3.4.3.jar:3.4.3]
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59) ~[mybatis-3.4.3.jar:3.4.3]

非常感谢为上述映射器提供解决方案的任何帮助。

0 个答案:

没有答案