问题描述
这个问题非常简单,您可能只需阅读代码
这是一个非常简单的性能问题。在下面的代码示例中,我希望在我的 Cat
对象上设置 Owner
。我有 ownerId
,但cats方法需要一个所有者
对象,而不是 Long
。例如: setOwner(所有者所有者)
@Autowired OwnerRepository ownerRepository;
@Autowired CatRepository catRepository;
Long ownerId = 21;
猫猫=新猫(杰克);
cat.setOwner(ownerRepository.findById(ownerId)); //什么是浪费时间
catRepository.save(cat)
我正在使用 ownerId
加载一个所有者
对象,所以我可以调用 Cat
,它将取出 id
,并将 Cat
记录保存为 owner_id
。所以基本上我没有任何东西加载一个所有者。
这是什么正确的模式?
如果您使用Hibernate Session
:
//将返回持久化实例,并且永远不会返回未初始化的实例
session.get(Owner.class,id);
//可能会返回按需初始化的代理实例
session.load(Owner.class,id);
如果您使用 EntityManager
:
//将返回持久化实例并永不返回未初始化的实例
em.find(Owner.class,id) ;
//可能会返回按需初始化的代理实例
em.getReference(Owner.class,id);
因此,您应该延迟加载Owner实体以避免对缓存或数据库造成一些冲击。 / p>
顺便提一下,我建议将所有者
和 Cat
。
例如:
业主= ownerRepository.load(Owner.class,id);
owner.addCat(myCat);
This question is so simple, you can probably just read the code
This is a very simple performance question. In the code example below, I wish to set the Owner
on my Cat
object. I have the ownerId
, but the cats method for requires an Owner
object, not a Long
. Eg: 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)
I'm using the ownerId
to load an Owner
object, so I can call the setter on the Cat
which is simply going to pull out the id
, and save the Cat
record with an owner_id
. So essentially I'm loading an owner for nothing.
What is the correct pattern for this?
First of all, you should pay attention to your method to load an Owner entity.
If you're using an 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);
If you're using 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);
So, you should lazy load the Owner entity to avoid some hits to the cache nor the database.
By the way, I would suggest to inverse your relation between Owner
and Cat
.
For example :
Owner owner = ownerRepository.load(Owner.class, id);
owner.addCat(myCat);
这篇关于JPA:我如何避免加载对象,以便我可以将其ID存储在数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!