说明:
表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