JPA 持久化问题
描述 :使用spring+strust2配置,第一次新增成功,第二次新增抛异常
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: model.Product; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: model.Product
org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:648)
org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:95)
org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:212)
org.springframework.orm.jpa.JpaAccessor.translateIfNecessary(JpaAccessor.java:152)
org.springframework.orm.jpa.JpaTemplate.execute(JpaTemplate.java:189)
org.springframework.orm.jpa.JpaTemplate.persist(JpaTemplate.java:266)
root cause
org.hibernate.PersistentObjectException: detached entity passed to persist: model.Product
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.26 logs.
Apache Tomcat/6.0.26
方案一 (推荐)
设置spring配置文件,使每次请求都重新初始化变量
<bean id="demoAction" class="com.web.action.DemoAction" scope="prototype"></bean>
方案二
在新增的Jsp页面隐藏对应的ID字段,使其值为零
<input type="hidden" name="bean.id" value="0" />
方案三
在执行方法体内,对刚刚持久化的实体手工初始化
public String execute throw Exception {
demoService.addBean(bean);
DemoBean = new DemoBean ();
}
另 如果 action在单实例时,只要程序异常,是无法再次执行,推荐Action使用 scope="prototype"
type Status report
message No result defined for action com.web.action.DemoAction and result input
description The requested resource (No result defined for action com.web.action.DemoAction and result input) is not available.