我有3张桌子:
校长:PK - > PrincipalID
Roles_type :PK - > roles_type
角色:PK - > PrincipalID(外键),PK - >角色(外键)。
我的实体是:
主体
@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;
}
角色
@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;
}
我的代码是为了坚持新的校长:
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);
所以我得到: javax.persistence.PersistenceException:org.hibernate.PersistentObjectException:传递给persist的分离实体:package.entity.Principals
我尝试了很多组合(持久化角色,更改CascadeType等......)
请帮帮我: - )
答案 0 :(得分:0)
解决: 我从
更改了Principals.java @Id
@javax.persistence.GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "PrincipalID", nullable = false)
到
@Id
@Basic(optional = false)
@Column(name = "PrincipalID")