JPA 中使用@Where

说明:

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
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值