我的hibernate为什么只能保存一次,保存第二次就失败了,求高手帮忙。错误提示:detached entity passed to persist========Person.hbm.xml===========
<hibernate-mapping package="cn.itcast.bean">
<class name="Person" table="person">
<id name="id">
<generator class="native"/>
</id>
<property name="name" length="10" not-null="true"/>
</class>
</hibernate-mapping>========== hibernate保存 ==========
@Resource// 用注释的方法得到SessionFactory
private SessionFactory sessionFactory;public void save(Person person) {
sessionFactory.getCurrentSession().persist(person);
}========struts2的行为===========
public String add(){
this.personService.save(this.person);
this.message="添加成功";
return "message";
}我的hibernate为什么只能保存一次,保存第二次就失败了,求高手帮忙。
<hibernate-mapping package="cn.itcast.bean">
<class name="Person" table="person">
<id name="id">
<generator class="native"/>
</id>
<property name="name" length="10" not-null="true"/>
</class>
</hibernate-mapping>========== hibernate保存 ==========
@Resource// 用注释的方法得到SessionFactory
private SessionFactory sessionFactory;public void save(Person person) {
sessionFactory.getCurrentSession().persist(person);
}========struts2的行为===========
public String add(){
this.personService.save(this.person);
this.message="添加成功";
return "message";
}我的hibernate为什么只能保存一次,保存第二次就失败了,求高手帮忙。
解决方案 »
- jsp门户例子~
- 多线程 发短信 帮助
- 服务器文件下载
- 在Tomcat作为服务器,为什么用不了fso = new ActiveXObject("Scripting.FileSystemObject");
- ajax问题:为什么取到值没办法比较?
- webwork 无法获取参数
- 大家研究研究这个问题,google上没有的
- 求jsp+oracle+struts分页
- 100分求——jfreechart0.9.21的中文文档或者项目原码
- 一个关闭数据库连接的问题?
- 典型的分页问题
- JSF,提示"The server has not found anything matching the Request-URI"
sessionFactory.getCurrentSession().save(person);
}
<class name="Person" table="person">
<id name="id" type="long">
<generator class="native"/>
</id>
<property name="name" length="10" type="string" not-null="true"/>
</class>
</hibernate-mapping>
换成
sessionFactory.getCurrentSession().save(person);
问题就解决了,但我不知道,persist和save两个有什么区别?
如果你让2个对象和数据库的同一条记录关联的话,detached entity passed to persist ,已经关联了。
Session session= SessionFactory().getCurrentSession().beginTransaction();
session.save(person);
session.close();
}
保存时是要开始一个事务的吧,
public void save(Person person) {
Session session= SessionFactory().getCurrentSession();
Transaction tran=session.beginTransaction();
session.save(person);
tran.commit();
session.close();
}
保存时是要开始一个事务的吧,
this.personService.save(this.person);
this.message="添加成功";
this.person = null;
return "message";
}
修成成这样就可以,
第一次保存后person中已经有id值了,第二次保存的时候,因为在数据库中已经存在
该记录,所有报错。应该保存后把person给清空就好了
那样他会直接吧MESSAGE这几个字符返回回去吧