版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/amoscn/article/details/84799736
背景
mapper文件添加一个根据条件随机取值的select方法,返回的记录的id是对的,但是有几个字段打印的结果是null,可是数据库里面明明是有值的呀!
测试代码
public static void main(String[] args) {
Name name = new Name();
name.setNameLength(1);
NameMapper mapper = MbSqlSessionFactory.getSession().getMapper(NameMapper.class);
System.out.println(mapper.random(name));
}
打印结果:
Name [Hash = 1860944798, id=347, nameLength=null, serialVersionUID=1]
xml文件配置
<select id="random" resultType="com.ppmoney.qa.source.model.Name">
select
<include refid="Base_Column_List" />
from name
<trim prefix="where " suffix="" suffixOverrides="and">
<if test="id != null">
id=#{id,jdbcType=INTEGER} and
</if>
<if test="nameLength != null">
name_length=#{nameLength,jdbcType=INTEGER} and
</if>
<!-- 部分字段省略 -->
</trim>
order by random() limit 1
</select>
原因
数据库表结构某几个字段是下划线格式,比如
name_length
而model类属性是nameLength
class Name{
public String nameLength;
// 其他省略
}
显然,mybatis会将数据库查出来的结果与Name这个model类做比对,如果一致则认为是同一个字段,如果不一致则认为不是同一个字段。
假如刚好查出的记录是name_length=1(其他字段省略),很显然Name这个类里面是没有name_length这个属性的。所以数据库记录映射成 Name实例后 ,nameLength=null.
正确写法:
BaseResultMap - mybatis文件开头定义的数据库字段与类属性映射…
<select id="random" resultMap="BaseResultMap">
// 其他省略
</select>
问题解决。