0

I'm not big guru of JPA, but this behaviour looks strange to me, please comment!

I'm trying to persist nested Objects: each Employee contains Set of Departments

if Department @Id is declared as @Generated int everything works fine. But it is inconvenient and I try to declare as @Id two fields (employee id + department id). But I get

EJBTransactionRolledbackException: A different object with the same identifier value was already associated with the session

on both merge and persist. Is it OK?

Some details:

Departments are declared this way

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

the relation is unidirectional and Persons are not declared in Departments

I populate departments this way:

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

Person is created this way:

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

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

record.setSnils(snils);
record.setFullname(fullname);
record.resetLastActive();

on em.persist(record) or em.merge(record) I get an Exception. Wrapping it to try catch block doesn't help

Transaction cannot proceed: STATUS_MARKED_ROLLBACK

What I need - is just update Person and Departments. Is it possible without boilerplate code (removing cascade, doing separate departments search et c )???

My environment: CentOS7, java8, Wildfly 10.2

Persons table is :

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)

Department table is :

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)

Entity Person (actually 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 Department:

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

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

@Temporal(TemporalType.DATE)
private Date lastActive;
Oleg Gritsak
  • 548
  • 7
  • 26

0 Answers0