我的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为什么只能保存一次,保存第二次就失败了,求高手帮忙。

解决方案 »

  1.   

    换成下面的试试:public void save(Person person) { 
      sessionFactory.getCurrentSession().save(person); 

      

  2.   

    <hibernate-mapping package="cn.itcast.bean"> 
      <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> 
      

  3.   

    由 sessionFactory.getCurrentSession().persist(person); 
    换成
    sessionFactory.getCurrentSession().save(person); 
    问题就解决了,但我不知道,persist和save两个有什么区别?
      

  4.   

    看看hibernate推荐的例子吧,用楼上的save()方法。persist()可能意味着: 让一个对象和一条数据库数据关联
    如果你让2个对象和数据库的同一条记录关联的话,detached entity passed to persist ,已经关联了。
      

  5.   

    public void save(Person person) { 
      Session session= SessionFactory().getCurrentSession().beginTransaction();
      session.save(person);
      session.close();
    }
    保存时是要开始一个事务的吧,
      

  6.   

    刚写掉了,,,改下
    public void save(Person person) { 
      Session session= SessionFactory().getCurrentSession();
      Transaction tran=session.beginTransaction(); 
      session.save(person); 
      tran.commit();
      session.close(); 

    保存时是要开始一个事务的吧,
      

  7.   

    public String add(){ 
      this.personService.save(this.person); 
      this.message="添加成功"; 
      this.person = null;
      return "message"; 

    修成成这样就可以,
    第一次保存后person中已经有id值了,第二次保存的时候,因为在数据库中已经存在
    该记录,所有报错。应该保存后把person给清空就好了
      

  8.   

    你返回的的那个MESSAGE怎么用引号引住?
    那样他会直接吧MESSAGE这几个字符返回回去吧