给定这两个具有 OneToOne 关系的实体(A 作为拥有方,持有 B 实体 id):
@Entity
@Table(name="A")
public class AEntity{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
...
@OneToOne(optional = true, cascade = CascadeType.ALL)
@JoinColumn(name = "bId")
private BEntity b;
}
@Entity
@Table(name="B")
public class BEntity{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@OneToOne(mappedBy = "b", cascade = CascadeType.ALL, optional = true, fetch = FetchType.LAZY)
private AEntity a;
...
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable = false)
protected Date someDate;
}
我使用条件查询来获取给定日期内的所有 B 实体:
public class BSpecification {
public static Specification<BEntity> filter(BFilter filter) {
return new Specification<BEntity>() {
@Override
public Predicate toPredicate(Root<BEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<Predicate>();
if(filter.getDateFrom() != null){
predicates.add(cb.greaterThanOrEqualTo(cb.function("date", Date.class, root.get(BEntity_.someDate)),
filter.getDateFrom()));
}
if(filter.getDateTo() != null){
predicates.add(cb.lessThanOrEqualTo(cb.function("date", Date.class, root.get(BEntity_.someDate)),
filter.getDateTo()));
}
if(predicates.size()==0){
return null;
}else{
return cb.and(predicates.toArray(new Predicate[0]));
}
}
};
}
}
查询被执行,bRepository.findAll(BSpecification.filter(filter));
我看到在基于日期获取 BEntities 之后......
select
b0_.id as id1_7_,
b0_.some_date as some_date_cr2_7_,
from
b b0_
where
date(b0_.some_date)>=?
and date(b0_.some_date)<=?
...还有另一个获得一对一惰性相关的 AEntity:
select
a0_.id as id1_9_2_,
a0_.b_id as b14_9_2_,
from
a a0_
where
a0_.b_id=?
由于性能原因,我需要阻止加载 AEntities,为什么这个标准会获取它们?
更新:试图简化我刚刚加载了一个 BEntities 的问题bRepository.findOne(bId)
,同样的事情发生了。所以这不是关于标准,而是关于映射。它出什么问题了?