JPA 中使用@Where
来源:互联网 发布:懒蛋蛋布丁玩具淘宝 编辑:程序博客网 时间:2024/05/16 13:57
说明:
表customer
和表res_prop
是一对多的关系,
映射关系是res_prop
的res_id
对应customer
的id,res_prop
的rescode
对应‘Customer’
问题:
对customer
分页查询,每页20条,但是每页查询出来只显示5条,但是total却是对的。
修改之前的代码:
customer对应的实体Customer
import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.JoinColumn;import javax.persistence.OneToMany;import javax.persistence.Table;import org.hibernate.annotations.Fetch;import org.hibernate.annotations.FetchMode;import org.hibernate.annotations.Where;@Entity@Table(schema="customer",name="customer")public class Customer extends BaseEntity implements UndeleteableEntity{ // 其他字段忽略 private List<ResProp> resProps; @OneToMany(targetEntity=ResProp.class,fetch=FetchType.EAGER) @JoinColumn(name="res_id",insertable=false,updatable=false,referencedColumnName="id") @Where(clause="status = 1 AND rescode = 'Customer'") public List<ResProp> getResProps() { return resProps; } public void setResProps(List<ResProp> resProps) { this.resProps = resProps; }}
思考:
customer和res_prop是一对多的关系,@OneToMany默认的Fetch模式是join,每页查询出来是20条,但是这20条数据是多个customer对应res_prop,所以customer是重复的,经过hibernate处理,最终查询出来的customer自然少于20条。
解决方法:
将Fetch模式改为select模式,即每次查询完customer,单独select下res_prop,这样就不会影响customer的分页。
- 修改后的代码
@Entity@Table(schema="customer",name="customer")public class Customer extends BaseEntity implements UndeleteableEntity{ // 其他字段忽略 private List<ResProp> resProps; @OneToMany(targetEntity=ResProp.class,fetch=FetchType.EAGER) @JoinColumn(name="res_id",insertable=false,updatable=false,referencedColumnName="id") @Fetch(FetchMode.SELECT) @Where(clause="status = 1 AND rescode = 'Customer'") public List<ResProp> getResProps() { return resProps; } public void setResProps(List<ResProp> resProps) { this.resProps = resProps; }}
总结:
- @OneToMany分页查询时候,使用Fetch采用select模式
- 如果关联多个字段,且有些字段为确定常量,可以使用@Where
0 0
- JPA 中使用@Where
- Yii中where方法使用
- eclipse中JPA的使用
- spring boot 中使用 jpa以及jpa介绍
- ThinkPHP Where 条件中使用表达式
- 在where中使用decode函数
- ThinkPHP Where 条件中使用表达式
- PL/SQL where 条件中使用case
- ThinkPHP Where 条件中使用表达式
- ThinkPHP Where 条件中使用表达式
- 使用where子句过滤表中数据
- ThinkPHP中CURD where的使用注意事项
- 在where子句中使用子查询
- ThinkPHP Where 条件中使用表达式
- ThinkPHP Where 条件中使用表达式
- ThinkPHP Where 条件中使用表达式
- ThinkPHP Where 条件中使用表达式---$map
- ThinkPHP Where 条件中使用表达式
- spark和hadoop的区别
- scala-43:Scala中类型变量Bounds代码实战及其在Spark中的应用源码解析
- Oozie中Sqoop的配置及应用
- python 循环
- 国产厂商的低价产品虽然利润很低
- JPA 中使用@Where
- Oozie中Shell action的配置及应用
- Linux系统apache2.4环境下php7.0.0的源码安装
- Android BackgroundViewPager:类似桌面背景壁纸随手指滑动
- 蓝桥杯 方格取数 (多线程DP)
- project euler 91
- SpannableString的一些api
- bootstrap中的网格系统
- ScrollView 滑动监听