JPA:如何避免加载对象,以便将其ID存储在数据库中?

Spi*_*der 7 java orm hibernate jpa spring-boot

这个问题很简单,你可能只是阅读代码

这是一个非常简单的性能问题.在下面的代码示例中,我希望设置Owner我的Cat对象.我有ownerId,但猫的方法需要一个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)
Run Code Online (Sandbox Code Playgroud)

我正在使用它ownerId来加载一个Owner对象,所以我可以调用setter就Cat可以将其拉出来id,并Cat用一个保存记录owner_id.所以基本上我只是在装载一个所有者.

这是什么样的正确模式?

vic*_*let 9

首先,您应该注意加载所有者实体的方法.

如果您正在使用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);
Run Code Online (Sandbox Code Playgroud)

如果您正在使用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);
Run Code Online (Sandbox Code Playgroud)

因此,您应该延迟加载所有者实体以避免对缓存或数据库的某些命中.

顺便说一下,我建议改变你Owner和之间的关系Cat.

例如 :

Owner owner = ownerRepository.load(Owner.class, id);
owner.addCat(myCat);
Run Code Online (Sandbox Code Playgroud)