(超详细)在使用mybatis时遇到查询结果返回为空(NULL)的情况,但是查数据库能查到

这个问题困扰了我一个下午,看了很多博客都没有我中情况,所有写给和我有一样错误的

由于我的实体类里声明了其它实体类,所以在mapper.xml文件里要使用resultMap,在resultMap里要使用association引入,否则会报错

下面贴出我的实体类:

public class Subject {
    private Integer subid;
    private String subname;
    private Teacher tutor;
    private Teacher othertutor;

    //省略get和set方法
}

注意:声明了 Teacher 类

sql 语句:

<select id="getSubjectSim"  resultMap="SubjectMap">
   SELECT  tutorid,subname FROM tb_subject
</select>

resultMap:

<resultMap id="SubjectMap" type="com.learn.mydos.entity.Subject">
    <id column="subid" property="subid"/>
    <result column="subname" property="subname"/>
    <association property="tutor" javaType="com.learn.mydos.entity.Teacher" column="tutorid" >
    </association>
    <association property="othertutor" javaType="com.learn.mydos.entity.Teacher"              column="othertid">
    </association>
</resultMap>

   

这里用到了 association,property为实体类里定义的名称,javaType 为实体类,column 为数据库字段名

问题来了

我想取 Teacher 类里的 tid

 但是返回的是null,我到数据库里使用sql语句查询,能查到tid,我纠结了一会,重新去看mybaties里的association

下面我贴出教程里介绍的

关联:

<association property="author" column="blog_author_id" javaType="Author">
  <id property="id" column="author_id"/>
  <result property="username" column="author_username"/>
</association>

关联元素处理“有一个”类型的关系。比如,在我们的示例中,一个博客有一个用户。 关联映射就工作于这种结果之上。你指定了目标属性,来获取值的列,属性的 java 类型(很 多情况下 MyBatis 可以自己算出来) ,如果需要的话还有 jdbc 类型,如果你想覆盖或获取的 结果值还需要类型控制器。

关联中不同的是你需要告诉 MyBatis 如何加载关联。MyBatis 在这方面会有两种不同的 方式:

  • 嵌套查询:通过执行另外一个 SQL 映射语句来返回预期的复杂类型。
  • 嵌套结果:使用嵌套结果映射来处理重复的联合结果的子集。首先,然让我们来查看这个元素的属性。所有的你都会看到,它和普通的只由 select 和

resultMap 属性的结果映射不同。

看完之后,就按按照着教程在 association 里添加 id 和 result

<resultMap id="SubjectMap" type="com.learn.mydos.entity.Subject">
        <id column="subid" property="subid"/>
        <result column="subname" property="subname"/>
        <association property="tutor" javaType="com.learn.mydos.entity.Teacher" column="tutorid" >
            <id column="tutorid" property="tid"/>
            <result column="tname" property="tname"/>
        </association>
        <association property="othertutor" javaType="com.learn.mydos.entity.Teacher" column="othertid">
            <id column="othertid" property="tid"/>
            <result column="tname" property="tname"/>
        </association>

果然,再测试一下就有值了

猜你喜欢

转载自blog.csdn.net/weixin_39637376/article/details/83994112