情况是这样的:
xml文件查询操作,其中(curdate()-a.lend)*b.price是通过天数计算租金:
<select id="findAllNoReturn" parameterType="string" resultType="NoReturnInfo">
select a.name,a.fid,a.lend,(curdate()-a.lend)*b.price from userrentalhistory as a,vacantfile as b where a.username=#{username} and a.back is null and a.fid=b.fid
</select>
这是对应的返回实体类:
public class NoReturnInfo {
private String name;
private long fid;
private java.sql.Date lend;
private double amount;
下面略...
这样查询出来的结果:

发现amount中始终为0,但是我在navicat中使用同样的sql语句明明是对的,于是我想问题肯定出在存到实体类这个环节。其中name,fid,lend都是和数据库中的字段一一对应的,而(curdate()-a.lend)*b.price这个虽然也是double,但它是临时产生的,所以必须要设置一个于实体类属性名相同的名字。到此这个问题就很简单了,直接在后面加上as amount就ok了,下面是改正后的语句:
<select id="findAllNoReturn" parameterType="string" resultType="NoReturnInfo">
select a.name,a.fid,a.lend,(curdate()-a.lend)*b.price as amount from userrentalhistory as a,vacantfile as b where a.username=#{username} and a.back is null and a.fid=b.fid
</select>
查询结果:

总结:mybatis查询时必须要和resultType的内容一一对应,如果查询时用到通过计算临时产生的数据项,那必须取别名使之与实体类中的属性对应。
在使用MyBatis进行查询时,遇到计算字段(如:(curdate()-a.lend)*b.price)无法正确写入到实体类的问题。经过排查,发现原因是计算字段虽然是double类型,但其名称需要与实体类属性名一致。解决方案是在查询语句中为计算字段设置别名,使其与实体类属性对应,从而成功将查询结果存入实体类。
3599

被折叠的 条评论
为什么被折叠?



