场景:要模糊匹配两张表A,B的多个字段,返回符合条件的结果集。
A表 字段 name id update_time(BigInt) attribute1
B表 字段 name id update_time attribute1 attribute2 attribute3
JPA使用entity做UNION 查询,官网示例是同一张表,JPA对字段和entity的约束性很强,写一些复杂sql,需要花点功夫。但是约束强,另一面就是可移植性高。
官方参考:http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#UNION
这里使用原生SQL,自定义对象接受结果集,如果项目不允许使用原生写法,可以转变思路,用JPA实现。
声明接受结果集对象
public interface ResultDto{
BigInteger getUpdateTime();
Integer getId();
String getName();
String getAttribute1();
String getAttribute2();
String getAttribute3();
}
DAO层自定义SQL
@Query(
value="select A.update_time as updateTime...... ",
nativeQuery=true
)
List<ResultDto> queryResultFromAandB(@Param("queryParam")String queryParam);
DAO上层定义对象接受 返回的代理对象
public class Result implements Serializable{
private BigInteger updateTime;
private Integer id;
private String name;
......
get,set......
}
for(ResultDto resultDto:
resultDtoList){
Result result = new Result();
result.setUpdateTime(resultDto.getUpdateTime)
......
}
注意点:
1.ResultDto 的getUpdateTime对应 原生SQL中的列 updateTime
原本我以为根据驼峰规则,列应该为update_time,返回的代理对象没有值
2.ResultDto数据类型应该和数据库一致
原本ResultDto属性返回值根据一个Entity复制过来的,其中update_time字段数据库为BigInt,Entity用long接收,没有问题。
但是ResultDto用long接收 会异常,改为包装类依然异常。
异常:Null return value from advice does not match primitive return type for:.....
解决:避免AOP期间,进行数据转换(为什么?不知道,如有后续会拓展)
参考博客:
1.https://blog.csdn.net/sinat_34820292/article/details/90380251 JPA自定义原生SQL语句的查询结果如何转化.......
2.https://blog.csdn.net/thewindkee/article/details/99437068 SpringAop时Null return value from...