微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

这是一个非常简单的性能问题.在下面的代码示例中,我希望在我的Cat对象上设置所有者.我有ownerId,但是cat方法需要一个Owner对象,而不是Long.例如:setowner(所有者所有者)

@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对象,所以我可以调用Cat上的setter,它只是取出id,并用owner_id保存Cat记录.所以基本上我只是在装载一个所有者.

这是什么样的正确模式?

解决方法

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

如果您正在使用Hibernate会话:

// 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 = ownerRepository.load(Owner.class,id);
owner.addCat(myCat);

原文地址:https://www.jb51.cc/java/128173.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐