jpa 使用HQL查询视图的结果与数据库用sql查询的结果不一致的问题让我碰到了,以前从来没遇到过,第一次遇到搞得我郁闷了一天,终于找到问题的所在:
原因:
因为用jpa的HQL语句写自定义查询sql,所以直接是用Entiy实体类接收结果(也就是说查出什么字段实体属性就有什么字段),由于查出来的字段没有一个是唯一的,然而看了jpa文档了解到jpa要求有唯一的字段,因此查询出来的结果不一致。
解决方法:
(1)给视图或者表提供一个唯一的字段即可,比如oracle或者mysql的rownum函数,不同数据库可用row_num、row_id等,比如我用的PostgreSQL ,则是需要加row_number() OVER () AS row_num ,并在实体类加上row_num变量来接收查询结果
(2)如果是视图查询那就在视图sql的实际表中返回一个表里唯一的字段作为视图的唯一字段,然后在实体类上定义唯一字段,本人是第二种情况,所以直接用表里的BID返回。
本人的实际代码如下:
实体类:IpoBillDetailEntity,view_ele_ipo_billdetail是对应的数据库视图
@Entity
@Table(name = "view_ele_ipo_billdetail", schema = "ADAPTER")
public class IpoBillDetailEntity {
@Column(name = "order_sn")
private String orderSn;
@Column(name = "exec_sn")
private String execSn;
@Column(name = "bill_code")
private String billCode;
@Column(name = "bill_name")
private String billName;
@Column(name = "fee_code")
private String feeCode;
@Column(name = "unit_price")
private BigDecimal unitPrice;
@Column(name = "fee_unit")
private String feeUnit;
@Column(name = "fee_qty")
private BigDecimal feeQty;
@Column(name = "tot_cost")
private BigDecimal totCost;
@Column(name = "inpatient_sn")
private String inpatientSn;
@Column(name = "HOSPITAL_ID")
private String hospitalId;
@Column(name = "compound_id")
private String compoundId;
@Column(name = "trans_class")
private String transClass;
@Column(name = "relation_positive_id")
private String relationPositiveId;
/**
* 视图主键ID,注意这里要加主键@ID,此字段唯一,也是解决上述问题的关键
*/
@Id
@Column(name = "bid")
private String bid;
/**
* 下面set,get方法省略。。。。
*/
jpa的JpaRepository类:
public interface IpoBillDetailRepository extends JpaRepository<IpoBillDetailEntity, String> {
@Query("select t from IpoBillDetailEntity t where t.hospitalId = ?2 and t.compoundId = ?3 and t.inpatientSn = ?1")
List<IpoBillDetailEntity> queryIpoBillDetailEntitiesByInpatientSn(String inpatientSn, String hospitalId, String compoundId);
}