1
我有兩個實體,它們之間有一個關係ManyToMany。出於某種原因,當我嘗試從數據庫中獲取所有實體時,我得到一個"statement closed"
異常。獲取ManyToMany相關元素時語句關閉異常
下面是一些代碼:
public class Famille {
[...]
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "famille_personne",
[email protected](name="famille_id"), [email protected](name="personne_id"))
private Set<Personne> listPersonne;
[...]
@Override
public boolean equals(Object object){
if(object instanceof Famille){
Famille famille = (Famille) object;
return (nom.equals(famille.getNom())
&& ((listPersonne == null && famille.getListPersonne() == null)
|| (listPersonne != null && new HashSet(listPersonne).equals(new HashSet(famille.getListPersonne())))
)
);
}
return false;
}
}
public class Personne {
[...]
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "famille_personne",
[email protected](name="personne_id"), [email protected](name="famille_id"))
private Set<Famille> listFamille;
[...]
@Override
public boolean equals(Object object){
if(object instanceof Personne){
Personne personne = (Personne) object;
return (matricule.equals(personne.getMatricule()) && nom.equals(personne.getNom()));
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(matricule, nom);
}
}
這裏是與這兩個查詢的方法,我不能在同一時間執行:
public ArrayList<Famille> getListFamille(){
entityManager = entityManagerFactory.createEntityManager();
ArrayList<Famille> listFamille = new ArrayList<Famille>();
listFamille.addAll(entityManager.createQuery("from Famille", Famille.class).getResultList());
entityManager.close();
return listFamille;
}
public ArrayList<Personne> getListPersonne(){
entityManager = entityManagerFactory.createEntityManager();
ArrayList<Personne> listPersonne = new ArrayList<Personne>();
listPersonne.addAll(entityManager.createQuery("from Personne", Personne.class).getResultList());
entityManager.close();
return listPersonne;
}
這是我得到的異常:
org.postgresql.util.PSQLException: This statement has been closed.
有人可以解釋我是如何工作的,爲什麼我得到這個異常?
我已經改變了我的兩個方法,如你所說,它仍然不工作的一側提取。我爲什麼要開始/提交交易?從來沒有這樣做過,當我得到一些價值,它始終工作 –
我認爲這可能是與雙方渴望提取的問題..請檢查我更新的答案 –
對不起,很長時間的迴應。我已經按照你的說法試過了,並且我得到了一個「未能懶惰地初始化一個角色集合」的例外。有時我想獲取Personne.listFamille,有時候還需要Famille.listPersonne,因此無法工作... –