我有一個家長和孩子實體如下主要Hibernate的Session自動關閉
@Entity
@Table(name = "PARENT")
public class Parent implements Comparable<Parent>, Serializable, Cloneable {
private static final long serialVersionUID = 1584115734363172986L;
public static final int NAME_LENGTH = 300;
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "gen-seq")
@GenericGenerator(name = "gen-seq", strategy = "native",
parameters = {@Parameter(name = "sequence_name", value = "parent_id_seq")})
private Long id;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
@BatchSize(size = 50)
@SortNatural
private SortedSet<Child> child = new TreeSet<>();
}
兒童實體如下
@Entity
@Table(name = "Child")
@Inheritance(strategy= InheritanceType.JOINED)
public class Child implements Comparable<Object>, Serializable, Cloneable, Step<Child> {
private static final long serialVersionUID = -9091312680432977997L;
public static final int NAME_LENGTH = 255;
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "gen-seq")
@GenericGenerator(name = "gen-seq", strategy = "native",
parameters = {@Parameter(name = "sequence_name", value = "child_id_seq")})
private Long id;
@ManyToOne()
@JoinColumn(name = "parentId", nullable = false)
private Parent parent;
}
我已經配置Spring和Hibernate來處理數據庫操作,以及處理父我在serviceimpl類中添加了以下方法。
public void processParent(final Long parentId, String userEmail) throws Exception {
getHibernateTemplate().execute(new HibernateCallback<Set<Void>>() {
public void doInHibernate(Session session) throws HibernateException {
Parent parent = (Parent) session.get(Parent.class, parentId);
if (parent!=null && parent.getChild()!=null) {
for (Child child: parent.getChild()) {
// here the session is still Open when I call
child.getParent();
//But when I call this
Parent p = getParent(child.getParent().getId());
//now here the session got closed automatically, and now I cannot process the parent object
}
}
}
}
}}
在上述方法中,我有會話被打開,直到我打電話child.getParent(),但如果我叫具有另一個會話本身,其不爲空,返回下面的方法後,則該方法在下面上述方法中的會話自動變爲null。
public Parent getParent(final Long id) throws Exception {
Parent actionPoint = (Parent) getHibernateTemplate().execute(new HibernateCallback<Parent>() {
/* (non-Javadoc)
* @see org.springframework.orm.hibernate5.HibernateCallback#doInHibernate(org.hibernate.Session)
*/
public Parent doInHibernate(Session session) throws HibernateException {
Parent parent = (ActionPoint) session.get(Parent.class, id);
//here also session is still open
return parent;
}
}}
誰能幫助我如何解決不應該被關閉或成爲空的主要會議。我知道這是一個配置問題,但我不知道應該配置什麼。
在此先感謝,因爲我試圖找出過去2周的這個問題。
剛剛推出春季事務管理和註釋與'@ Transactional'避免手動會話/事務處理您的服務方法。如果您將傳播設置爲REQUIRED,則將使用相同的事務。 – StanislavL
如果你正在使用JTA--將Hibernate.cfg「current_session_context_class」中的屬性更改爲「managed」 –
@PRATHAPS,問題已在某種程度上得到解決,現在我沒有得到會話異常,即會話已打開。但是當我調用其他方法\t'父親=(父)getHibernateTemplate()。get(Parent.class,parentId); (parent!= null){ \t \t if(parent!= null)Hibernate.initialize(parent.getChildren());我在Hibernate.initialize(parent.getChildren())沒有得到會話錯誤; – user503285