Being new to hibernate/jpa i am facing difficulty on how to model the nested entities correctly, my requirment, user -> have many roles -> each role have many permissions
Each permission for a role needs to be persisted as separate row in table. And, need to have separate tables for users and theirs roles; again each role of a user need to be persisted as a separate row in table. I wrote the below; but this is not allowing me to create new users with already defined roles...
@Entity
@Table(name = "users")
public class User implements Serializable {
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID",strategy = "org.hibernate.id.UUIDGenerator")
public UUID id;
@Column(name = "username")
public String name;
@Column(name = "password")
public String password;
@OneToMany(cascade = CascadeType.ALL, mappedBy="user")
@LazyCollection(LazyCollectionOption.FALSE)
public List<UserRole> roles;
}
@Entity
@Table(name = "user_roles")
public class UserRole implements Serializable {
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID",strategy = "org.hibernate.id.UUIDGenerator" )
public UUID id;
@ManyToOne
@JoinColumn(name="username", nullable=false, referencedColumnName = "username")
public User user;
@Column(name = "role_name")
public String roleName;
@OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumn(name = "role_name", referencedColumnName = "role_name")
public List<RolePermission> permissions;
}
@Entity
@Table(name = "roles_permissions")
public class RolePermission implements Serializable {
@Id
@Column(name = "role_name")
public String roleName;
@Id
@Column(name = "permission")
public String permission;
}
Get the below error,
2019-03-06 21:25:22.643 ERROR 48896 --- [nio-8090-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: duplicate key value violates unique constraint "uk_40fvvy071dnqy9tywk6ei7f5r" Detail: Key (role_name)=(owner) already exists.