我試圖觀察JPA2/Hibernate4代理下面的行爲,JPA和Hibernate的代理行爲
//圓形,延遲加載實體:
@Entity
public class Employee {
@[email protected]
int id;
String name;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
Employee boss;
public String toString() {
return id + "|" + name + "|" + boss;
}
//getters and setters ...
}
//堅持實體:
// Outer entity:
Employee employee = new Employee();
employee.setName("engineer");
// Inner entity:
Employee boss = new Employee();
boss.setName("manager");
employee.setBoss(boss);
entityTransaction.begin();
entityManager.persist(employee);
entityTransaction.commit();
System.out.println(employee);
//輸出:
Hibernate: insert into Employee (id, boss_id, name) values (default, ?, ?)
Hibernate: insert into Employee (id, boss_id, name) values (default, ?, ?)
2|engineer|1|manager|null
//加載外實體:
String queryString = "select e from Employee e where e.id=" + employee.getId();
Query query = entityManager.createQuery(queryString);
Object loadedEmployee = query.getSingleResult();
System.out.println(loadedEmployee.getClass().getSimpleName());
//輸出:
Hibernate: select employee0_.id as id2_, employee0_.boss_id as boss3_2_, employee0_.name as name2_ from Employee employee0_ where employee0_.id=2 limit ?
Employee
令我驚訝的上方的裝載外實體仍然是普通的,但我希望它是Hibernate proxy
所得從lazy loading
。我可能在這裏錯過了一些東西,那麼怎樣才能把它做好?非常感謝一個簡單但具體的例子!
@EDIT
據@kostja
答案我適應的代碼,並且在下面SE模式調試它,既不能LazyInitializationException
來生產,也不是boss property
代理。還有什麼提示?
@EDIT 2
最後,我想確認從@kostja
答案是undoubtly很大。
我在EE模式下測試,所以proxied boss property
在低於觀察到的,
// LazyInitializationException
拋出:
public Employee retrieve(int id) {
Employee employee = entityManager.find(Employee.class, id);
// access to the proxied boss property outside of persistence/transaction ctx
Employee boss = employee.getBoss();
System.out.println(boss instanceof HibernateProxy);
System.out.println(boss.getClass().getSimpleName());
return boss;
}
//綠色光放Spring Tx
到位後:
@Transactional
public Employee retrieve(int id) ...
//輸出:
true
Employee_$$_javassist_0
另外,可以參考Hibernate文檔中的20.1.4. Initializing collections and proxies。
謝謝。你能否根據你的提示檢查我的修改版本? – sof
@sof - 已經做了一些測試 - 也許你可以重現它 – kostja
非常感謝。我在EE模式下成功進行了另一項測試。 – sof