Wednesday, September 5, 2018

JPA: OneToOne Lazy Load

Mặc định thì lazy load cho trường hợp là OneToOne sẽ không hoạt động trong jpa hoặc là ta sẽ convert qua OneToMany hoặc là ta xài theo cách bên dười là dùng LazyToOne của Hibernate.

1. use @LazyToOne(LazyToOneOption.NO_PROXY)
@OneToOne(cascade = {CascadeType.PERSIST}, mappedBy = "post", fetch = FetchType.LAZY, optional=false)
@LazyToOne(LazyToOneOption.NO_PROXY) 
private PostDetailEntity detail;
1.1 Must define one more property in persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
 version="2.1">
 <persistence-unit name="mydb" transaction-type="JTA">
  <jta-data-source>java:jboss/datasources/mydb</jta-data-source>
  ...
  <properties>
   ...
   <property name="hibernate.ejb.use_class_enhancer" value="true"/>
   ...
  </properties>
 </persistence-unit>
</persistence>
2. Reference
https://stackoverflow.com/questions/45107084/hibernate-lazy-loading-with-lazytoonelazytooneoption-no-proxy

http://justonjava.blogspot.com/2010/09/lazy-one-to-one-and-one-to-many.html

No comments:

Post a Comment