sql相关代码
首先这是sql,主要问题在于 realPrice 字段,是由三个表查询得出的结果,根据表A的一个字段 判断 realPrice 是取表B的值 还是表C的值。
@Query(value = "select *,case when db.order_type_code = 'Db2bOrder' then d.RealTotal else df.TotalMoney end realPrice from db2border_bill_detail db " +
"left join db2border d on d.fID =db.source_id " +
"left join db2brefund df on df.OrderID = db.source_id where db.group_id = ?1 and db.db2border_bill_id = ?2", nativeQuery = true)
List<Db2BorderBillDetail> findAllByGroupIdAndDb2BorderBillId(String groupId,Long Id);
首次尝试
由于表A没有realPrice 字段,所以用@Transient注释。虽然这样查询正常 ,返回的realPrice的字段有值 ,但是发现保存时会报错 提示“Unknown column ‘db2borderb0_.realPrice’ in ‘field list’”,这样明显不行
@Transient
private BigDecimal realPrice;
public BigDecimal getRealPrice() {
return realPrice;
}
public void setRealPrice(BigDecimal realPrice) {
this.realPrice = realPrice;
}
再次尝试
然后在某度搜索了一下解决方案,改为如下那样,还是不好使,这次虽然保存不会报错,但是 查询时 realPrice字段返回为null
private BigDecimal realPrice;
@Transient()
public BigDecimal getRealPrice() {
return realPrice;
}
public void setRealPrice(BigDecimal realPrice) {
this.realPrice = realPrice;
}
然后在csdn里也找了下资料,csdn里有同学提议
字段用@TableField(exist=false)注解,即:@Transient()改成@TableField(exist=false)试试,
不过由于@TableField注释是Mybatis-plus的注释,我这边没有用到,也没法证实能否成功。以后有用到Mybatis-plus时会尝试下。
还有同学,提议在实体类getRealPrice() 方法里做处理。但是应该不适合我这情景,realPrice 是根据表A的一个字段 判断 realPrice 是取表B的值 还是表C的值。表A别名都显示不出来,应该也不能正常读取到表B的值和表C的值,所以应该不能处理。
最后
最后还是弄多了一步操作,查询sql时先返回List<Object[]>,再把List<Object[]> 用反射转为List 了。
public static Object getValueByKey(Object obj, String key) {
// 得到类对象
Class userCla = (Class) obj.getClass();
/* 得到类中的所有属性集合 */
Field[] fs = userCla.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
f.setAccessible(true); // 设置些属性是可以访问的
try {
if (f.getName().endsWith(key)) {
System.out.println("单个对象的某个键的值==反射==" + f.get(obj));
return f.get(obj);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
// 没有查到时返回空字符串
return "";
}
@Query(value = "select db.id, db2border_bill_id db2bOrderBillId, db.source_id sourceId, db.source_no sourceNo, db.order_type_code orderTypeCode, " +
"db.order_type_name orderTypeName, db.total_money totalMoney, db.pay_money payMoney, db.remark remark, db.group_id groupId, db.create_id createId, db.create_name createName," +
" db.create_date createDate, db.posting_date postingDate, db.company_id companyId, db.company_code companyCode, db.company_name compayName,case when db.order_type_code = 'Db2bOrder' then d.RealTotal else df.TotalMoney end realPrice from db2border_bill_detail db " +
"left join db2border d on d.fID =db.source_id " +
"left join db2brefund df on df.OrderID = db.source_id where db.group_id = ?1 and db.db2border_bill_id = ?2", nativeQuery = true)
List<Object[]> findAllByGroupIdAndDb2BorderBillId(String groupId, Long Id);