I would like some advice on how to best layout my JPA entity classes. Suppose I have 2 tables I would like to model as entities, user and role.
Create Table users(user_id primary key,
role_id integer not null )
Create table role(role_id primary key,
description text,
)
I create the following two JPA Entities:
@Entity
@Table(name="users")
@Access(AccessType.PROPERTY)
public class User implements Serializable {
private Long userId;
private Long roleId;
private Role role;
@Column(name = "user_id")
@Id
public Long getUserId() {}
@Column(name = "role_id")
public Long getRoleId() {}
@ManyToOne()
JoinColumn(name="role_id")
public Role getRole() {}
}
Role Entity:
@Entity
@Table(name="Role")
@Access(AccessType.PROPERTY)
public class Role implements Serializable {
private String description;
private Long roleId;
@Column(name = "role_id")
@Id
public Long getRoleId() {}
@Column(name = "description")
public Long getDescrition(){}
@ManyToOne()
@JoinColumn(name="role_id")
public Role getRole() {}
}
Would the correct way to model this relationship be as above, or would I drop the private Long roleId; in Users? Any advice welcomed.
When I map it this way, I receive the following error:
org.hibernate.MappingException: Repeated column in mapping for entity:
Yes, you would drop the
private Long roleIdmapping when you have a@ManyToOneon the same column.As the error implies, you can only map each column in an @Entity once. Since
role_idis the@JoinColumnfor the@ManyToOnereference, you cannot also map it as a property.You can, however, add a convenience method to return the role ID, like