I write Struts action with some utils class from
http://caveatemptor.hibernate.org/
HibernateUtil and DAO pattern
I use session-per-request session with Hibernate filter as follow
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>jq.com.vn.bean.util.HibernateFilter</filter-class>
</filter>
filter method
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
// There is actually no explicit "opening" of a Session, the
// first call to HibernateUtil.beginTransaction() in control
// logic (e.g. use case controller/event handler) will get
// a fresh Session.
try {
chain.doFilter(request, response);
// Commit any pending database transaction.
HibernateUtil.commitTransaction();
} finally {
// No matter what happens, close the Session.
HibernateUtil.closeSession();
}
}
Hibernate version:2.1.6
Mapping documents:
<class name="Contents" table="T_CONTENTS" proxy="Contents">
<id name="id" column="CONTENTS_ID" unsaved-value="null">
<generator class="uuid.hex"/>
</id>
<property name="title" not-null="true" column="F_TITLE"/>
<property name="brief" column="F_BRIEF"/>
<property name="content" column="F_CONTENT"/>
<property name="createDate"
column="F_CREATED"
type="java.util.Date"
not-null="true"/>
<property name="status" column="F_STATUS"/>
<many-to-one
name="category"
column="CATEGORY_ID"
class="Category"
not-null="true"
/>
<set name="images"
lazy="true"
table="T_IMAGES"
order-by="F_TITLE asc">
<key column="CONTENTS_ID"/>
<composite-element class="Image">
<property name="title" column="F_TITLE"/>
<property name="description" column="F_DESCRIPTION"/>
<property name="path" column="F_PATH"/>
<property name="thumbnail" column="F_THUMBNAIL"/>
<property name="createDate"
column="F_CREATED"
type="java.util.Date"
not-null="true"/>
</composite-element>
</set>
</class>
DAO method
public void makePersistent(Contents contents)
throws InfrastructureException {
try {
contents.setCreateDate(new Date());
HibernateUtil.getSession().saveOrUpdate(contents);
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
}
Struts Action
private ActionForward updateContents(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
ContentsForm contentsForm=(ContentsForm) form;
ContentsDAO contentsDAO=new ContentsDAO();
Contents contents=new Contents().copyFrom(contentsForm);
contentsDAO.makePersistent(contents);
return mapping.findForward(Constant.SUCCESS);
}
when i new instant of object, it's work
but if I delete or update, thrown exception:
net.sf.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session
Anyone give the solution?