我正在尝试使用条件API获取实体。
这是标头实体的样子
public class Header{
@OneToMany(mappedBy = "header", cascade = CascadeType.ALL)
@LazyCollection(LazyCollectionOption.FALSE)
@JsonManagedReference
private List<Item> items;
}
我可以限制不加载物品吗?我试过这个。请帮忙
Criteria criteria = session.createCriteria(Header.class);
criteria.add(Restrictions.eq("id", id));
criteria.setFetchMode("header.items",FetchMode.LAZY);
return (Header) criteria.uniqueResult();
记录了它看起来像
的mysql查询/* MyService Health Check */ SELECT 1
3 Query /* criteria query */ select this_.id as id1_0_0_, this_.created_at as created_2_0_0_, this_.updated_at as updated_3_0_0_, this_.created_by as created_4_0_0_, this_.description as descript5_0_0_, this_.due_date as due_date6_0_0_, this_.party_id_from as party_id7_0_0_, this_.party_id_to as party_id8_0_0_, this_.reference_id as referenc9_0_0_, this_.sub_type as sub_typ10_0_0_, this_.total_amount_with_tax as total_a11_0_0_, this_.total_amount_without_tax as total_a12_0_0_, this_.type as type13_0_0_ from headers this_ where this_.id=1
3 Query SHOW WARNINGS
3 Query select items0_.header_id as header_i7_0_0_, items0_.id as id1_2_0_, items0_.id as id1_2_1_, items0_.created_at as created_2_2_1_, items0_.updated_at as updated_3_2_1_, items0_.amount as amount4_2_1_, items0_.header_id as header_i7_2_1_, items0_.ignore_reco as ignore_r5_2_1_, items0_.type as type6_2_1_ from items items0_ where items0_.header_id=1
答案 0 :(得分:0)
您可以在声明与实体的关系时定义初始化。您的代码看起来像
public class Header{
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name="items")
private List<Item> items;
}
,您的提取代码看起来像
Criteria criteria = session.createCriteria(Header.class);
criteria.add(Restrictions.eq("id", id));
return (Header) criteria.uniqueResult();
获取类型lazy初始化代理,以便在请求实体时立即加载实体。因此,当您尝试访问会话生命周期内的项目时,您将能够获取项目。
但是如果你试图在会话生命周期之外访问,你将得到LazyInitializationException。