Mybatis Nested Select for Association/Collection doesn't work

和自甴很熟 提交于 2019-12-02 11:21:01

问题


I am trying to test out Mybatis's user manual with the result map section. Mybatis version : mybatis-3.1.0

<setting name="lazyLoadingEnabled" value="false" />


<resultMap id="blogMap" type="blog">
<constructor>
    <idArg column="id" javaType="_long" />
    <arg column="title" javaType="String" />
</constructor>
<association property="author" javaType="author" column = "author_id"           select = "getAuthor"/>
</resultMap>

<select id="getBlog" parameterType="Long" resultMap="blogMap">
    select
    b.id,
    b.title
    from
    blog b
    where b.id = #{id} 
</select>

<select id="getAuthor" parameterType="Long" resultType="author">
    select
    a.id ,
    a.username,
    a.password
    from author a
where a.id = #{id} 
</select>

My Java classes :

public class Blog {
private long id;
private String title;

private Author author;
private List<Post> posts;
      //getter, setters and the constructor

public class Author {
private long id;
private String username;
private String password;
private String email;
private String bio;
private String favouriteSection;

Finally, my test Module

   BlogMapperInterface bm = context.getBean("blogMapper",BlogMapperInterface.class);
   Blog b = bm.getBlog(1);

Debug Stack Trace

[10/05/12 06:45:19:019 SGT] DEBUG datasource.DataSourceUtils: Fetching JDBC Connection from DataSource
[10/05/12 06:45:19:019 SGT] DEBUG BlogMapperInterface.getBlog: ooo Using Connection        [jdbc:oracle:thin:@*, UserName=*, Oracle JDBC driver]
[10/05/12 06:45:19:019 SGT] DEBUG BlogMapperInterface.getBlog: ==>  Preparing: select b.id, b.title from blog b where b.id = ? 
[10/05/12 06:45:19:019 SGT] DEBUG BlogMapperInterface.getBlog: ==> Parameters: 1(Long)
[10/05/12 06:45:19:019 SGT] DEBUG BlogMapperInterface.getBlog: <==    Columns: ID, TITLE
[10/05/12 06:45:19:019 SGT] DEBUG BlogMapperInterface.getBlog: <==        Row: 1, first blog
[10/05/12 06:45:19:019 SGT] DEBUG datasource.DataSourceUtils: Returning JDBC Connection to DataSource

Why the getAuthor is not invoked? Shouldn't it be invoked whenever I call getBlog()?


回答1:


Because there is not an author_id column in the result got from getBlog.

Try:

 select
    b.id,
    b.title,
    b.author_id
    from
    blog b
    where b.id = #{id} 


来源:https://stackoverflow.com/questions/10545232/mybatis-nested-select-for-association-collection-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!