JPA 中使用@Where

来源:互联网 发布:懒蛋蛋布丁玩具淘宝 编辑:程序博客网 时间:2024/05/16 13:57

说明:

customer和表res_prop是一对多的关系,
映射关系是res_propres_id对应customerid,res_proprescode对应‘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