I have 3 tables:
Principals: PK -> PrincipalID
Roles_type: PK -> roles_type
Roles: PK -> PrincipalID (Foreign Key), PK -> Role (Foreign Key).
My Entity are:
PRINCIPALS
@Entity
@Table(name = "principals")
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class Principals implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@javax.persistence.GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "PrincipalID", nullable = false)
private String principalID;
@OneToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL, mappedBy = "principals")
private Collection<Roles> rolesCollection;
}
ROLES
@Entity
@Table(name = "roles")
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class Roles implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected RolesPK rolesPK;
@Column(name = "RoleGroup")
private String roleGroup;
@JoinColumn(name = "Role", referencedColumnName = "roles_type", insertable = false, updatable = false)
@ManyToOne(optional = false)
private RolesType rolesType;
@JoinColumn(name = "PrincipalID", referencedColumnName = "PrincipalID", insertable = false, updatable = false)
@ManyToOne(fetch = FetchType.EAGER)
private Principals principals;
}
ROLESPK
@Embeddable
public class RolesPK implements Serializable {
@Column(name = "PrincipalID", nullable = false)
private String principalID;
@Column(name = "Role", nullable = false)
private String role;
}
ROLES_TYPE
@Entity
@Table(name = "roles_type")
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class RolesType implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "roles_type")
private String rolesType;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "rolesType")
private Collection<Roles> rolesCollection;
}
My code for persist a new principals:
Principals principals = new Principals();
principals.setPrincipalID("PRINCIPAL");
RolesType rolesType = em.find(RolesType.class, "TYPE_1");
RolesPK rolesPk = new RolesPK();
rolesPk.setPrincipalID(principals.getPrincipalID());
rolesPk.setRole(rolesType.getRolesType());
Collection<Roles> collRoles = new ArrayList<Roles>();
Roles roles = new Roles();
roles.setRolesType(rolesType);
roles.setRolesPK(rolesPk);
roles.setPrincipals(principals);
collRoles.add(roles);
principals.setRolesCollection(collRoles);
rolesType.setRolesCollection(collRoles);
em.persist(principals);
So I get: javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: package.entity.Principals
I tried many combinations (persist roles, change CascadeType etc...)
Please help me :-)