java – JPA:如何避免加载对象,以便将其ID存储在数据库中?
发布时间:2020-05-29 00:46:59 所属栏目:Java 来源:互联网
导读:这个问题很简单,你可能只是阅读代码 这是一个非常简单的性能问题.在下面的代码示例中,我希望在我的Cat对象上设置所有者.我有ownerId,但是cat方法需要一个Owner对象,而不是Long.例如:setOwner(所有者所有者) @Autowired OwnerRepository ownerRepository;@Aut
|
这个问题很简单,你可能只是阅读代码 这是一个非常简单的性能问题.在下面的代码示例中,我希望在我的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); (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- java – 访问非重写的超类方法时使用’super’关键字
- javax.inject.Inject和com.google.inject.Inject有什么区别
- Java 程序员容易犯的10个SQL错误
- 这个简单工厂是否违反了开放封闭原则?
- 是否有任何免费的Java开源应用程序可以监视网站状态?
- Spring Boot Thymeleaf实现国际化的方法详解
- java – 在JDK 1.5中使用的Collections.newSetFromMap的替代
- mybatis实现增删改查_动力节点Java学院整理
- java – 二元运算符’^’的坏操作数类型
- java.lang.IllegalStateException:AssetManager已完成
