Hibernate中的错误或我对复合ID的误解?

时间:2017-01-13 07:46:23

标签: java hibernate jpa orm

我不是JPA的大师,但这种行为对我来说很奇怪,请发表评论!

我试图保留嵌套对象: 每个员工都包含一组部门

如果部门@Id被声明为@Generated int,一切正常。但这很不方便,我尝试将@Id两个字段(员工ID +部门ID)声明为。但是我得到了

EJBTransactionRolledbackException: A different object with the same identifier value was already associated with the session
两者合并并保留。可以吗?

一些细节:

部门以这种方式宣布

@OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, cascade = CascadeType.ALL)
@JoinColumn(name = "snils")
private Set<DepartmentRecord> departments = new HashSet<>();

该关系是单向的,而且未在Departments中声明人员

我用这种方式填充部门:

record.getDepartments().add(new DepartmentRecord(snils, department));

以这种方式创建人:

Person record = em.find(Person.class, snils);

if (record == null)
        record = new Person();

record.setSnils(snils);
record.setFullname(fullname);
record.resetLastActive();
在em.persist(记录)或em.merge(记录)上我得到一个例外。 包装它以尝试捕获阻止没有帮助

Transaction cannot proceed: STATUS_MARKED_ROLLBACK

我需要的 - 只是更新人员和部门。是否有可能没有样板代码(删除级联,执行单独的部门搜索等)

我的环境:CentOS7,java8,Wildfly 10.2

人员表是:

snils      | character varying(255) | not null
blocked    | integer                | not null
fullname   | character varying(255) | 
lastactive | date                   | 
    Indexes:
"hr_workers_pkey" PRIMARY KEY, btree (snils)
Referenced by:
    TABLE "hr_departments" CONSTRAINT "fk49rcpg7j54eq6fpf9x2nphnpu"     FOREIGN KEY (snils) REFERENCES hr_workers(snils)

部门表是:

snils      | character varying(255) | not null
department | character varying(255) | not null
lastactive | date                   | 
     Indexes:
"hr_departments_pkey" PRIMARY KEY, btree (snils, department)
     Foreign-key constraints:
"fk49rcpg7j54eq6fpf9x2nphnpu" FOREIGN KEY (snils) REFERENCES hr_workers(snils)

实体人(实际上是SNILSRecord):

@Entity
@Table(name = "hr_workers")
public class SNILSRecord implements Serializable {

@Id
private String snils;
private String fullname;

@OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, cascade = CascadeType.ALL)
@JoinColumn(name = "snils")
private Set<DepartmentRecord> departments = new HashSet<>();

@Temporal(TemporalType.DATE)
private Date lastActive;
private int blocked;

// getters and setters

}

实体部门:

@Entity
@Table(name = "hr_departments")
public class DepartmentRecord implements Serializable {

@Id
private String snils;
@Id
private String department;

@Temporal(TemporalType.DATE)
private Date lastActive;

0 个答案:

没有答案