这个问题很简单,您可能只需阅读代码即可
这是一个非常简单的性能问题。在下面的代码示例中,我希望Owner
在Cat
对象上设置on 。我有ownerId
,但cats方法需要一个Owner
对象,而不是Long
。例如:setOwner(Owner owner)
@Autowired OwnerRepository ownerRepository;
@Autowired CatRepository catRepository;
Long ownerId = 21;
Cat cat = new Cat("Jake");
cat.setOwner(ownerRepository.findById(ownerId)); // What a waste of time
catRepository.save(cat)
我正在使用ownerId
加载Owner
对象,因此可以在上调用setter,Cat
只需将拔出id
,然后用保存Cat
记录owner_id
。因此,本质上来说,我一无所获。
正确的模式是什么?
首先,您应注意加载Owner实体的方法。
如果您使用的是Hibernate Session
:
// will return the persistent instance and never returns an uninitialized instance
session.get(Owner.class, id);
// might return a proxied instance that is initialized on-demand
session.load(Owner.class, id);
如果您使用的是EntityManager
:
// will return the persistent instance and never returns an uninitialized instance
em.find(Owner.class, id);
// might return a proxied instance that is initialized on-demand
em.getReference(Owner.class, id);
因此,您应该延迟加载Owner实体,以避免对高速缓存或数据库造成某些损失。
顺便说一句,我建议您反转Owner
和之间的关系Cat
。
例如 :
Owner owner = ownerRepository.load(Owner.class, id);
owner.addCat(myCat);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句