我有一个实体(联系人),它有一个延迟加载的集合。我不想改变它,但我需要在执行 em.find(Contact.class, myID) 时加载集合,这是否可以在不更改实体且不使用 jpql 语句和 fetch 的情况下完成。 ?
public class Contact implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@Column(name="contactId", nullable=false)
public String contactId;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "contact", orphanRemoval = true, fetch=FetchType.LAZY)
private List<ContactTaskRelation> taskRelations = new ArrayList<ContactTaskRelation>();
}
来 self 的无状态bean
@PersistenceContext(unitName="myContext")
private EntityManager em;
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
private Contact getContact(ContactMapping mappedContact){
//force em to load the collection of taskRelations
return em.find(Contact .class, mappedContact.getContact());
}
最佳答案
Contact entity = em.find(Contact.class, mappedContact.getContact());
entity.getTaskRelations().size(); // this will fetch the TaskRelations
return entity;
缺点是这会对数据库进行两次查询:一次获取联系人,另一次获取任务关系。
另一种选择是进行查询,如下所示:
String queryString = "SELECT model FORM Contact model JOIN FETCH model.taskRelations WHERE model.id = :id";
Query query = em.createQuery(queryString);
query.setParameter("id", mappedContact.getContact());
return query.getSingleResult(); // or getResultList();
此选项只进行一次查询。
关于java - 使用 entitymanager 急切加载集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12216546/