a different object with the same identifier value was already associated with the session when trying to persist entity

只谈情不闲聊 提交于 2019-12-05 10:58:25

The problem was how hibernate generates your id's, it starts from 1. When it assigns 1 to an object before saving it into database, it sees a row with same id already exists in the database and causes the exception. The simple and natural solution of this problem is simply to restrict hibernate, so that it can not assign 1 as an id to any object of the concerning class (in your case).

Solution for mySql:

If you are using mySql, you can create table manually and set the auto increment like:

  CREATE TABLE IF NOT EXISTS `testTable` (
      `id` number(11) NOT NULL AUTO_INCREMENT,
       ...,
       ...,
       ...,
       PRIMARY KEY (`id`)
 ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2; //assigning id by hibernate, will start from 2.

And in your domain class you can have id annotated like bellow:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
public long getId() {
   ....
}

GenerationType.AUTO by default uses auto increment in mySql. and after setting AUTO_INCREMENT=2 hibernate will start assigning id's from 2 (hence 1 is skipped).

Solution for Oracle:

The same thing for oracle can be done if you restrict hibernate use a "sequence" and you set the initial point of the sequence as your wish. You can create a sequence to be start from 2 and increment by 1 like bellow:

 create sequence idSequence
        start with 2
        increment by 1
        maxvalue 9999999999999;

And you can specify your sequence to be used to generate id's of your domain class's object like bellow:

@Id
@SequenceGenerator(name = "idGeneratorSeq", sequenceName = "idSequence")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "idGeneratorSeq")
@Column(name = "ID")
public long getId() {
   ....
}

And your problem is sovled.

Do the following steps before calling persist() method.

First detach your current instance

getEntityManager().detach(getInstance());

Now set its Id to null

getInstance().setId(null);

Now persist

String outcome = persist();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!