SpringData JPA 使用UNION 查询,自定义对象返回

  场景:要模糊匹配两张表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...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值