To create a JPA entity class for a user that has roles - nicode



To create a JPA entity class for a user that has roles, you can use the @ManyToMany annotation to create a many-to-many relationship between the User entity and the Role entity. Here's an example:

less
@Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) private Set<Role> roles = new HashSet<>(); // constructors, getters, and setters }

In this example, the User entity has a many-to-many relationship with the Role entity. The @ManyToMany annotation specifies the name of the join table (user_roles) and the foreign key columns (user_id and role_id). The fetch attribute specifies the fetch strategy for the roles, which in this case is EAGER to ensure that the roles are always loaded with the user.

Here's an example of a Role entity:

less
@Entity @Table(name = "roles") public class Role { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @ManyToMany(mappedBy = "roles") private Set<User> users = new HashSet<>(); // constructors, getters, and setters }

In this example, the Role entity has a many-to-many relationship with the User entity, which is mapped by the roles field in the User entity. The @ManyToMany annotation specifies the mappedBy attribute to indicate that the relationship is bidirectional.

With these entity classes, you can use JPA to persist users with roles to a database. When you load a User entity from the database, its associated roles will also be loaded due to the EAGER fetch strategy specified in the @ManyToMany annotation.

Comments