Answer the question
In order to leave comments, you need to log in
How to map an auxiliary table in Hibernate?
Table (Postgres) linking room, user, role entities:
CREATE TABLE room_user_role (
room_id INT REFERENCES room (id) ON DELETE CASCADE,
users_id INT REFERENCES "user" (id) ON DELETE CASCADE,
role_id INT REFERENCES role (id) ON DELETE CASCADE,
CONSTRAINT room_user_role_pk PRIMARY KEY (room_id, users_id, role_id)
);
// lombok
@Getter
@Setter
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
// lombok
@Entity(name = "room_user_role")
@Table(name = "room_user_role", uniqueConstraints = {
@UniqueConstraint(columnNames = {"room_id", "user_id", "role_id"})
})
public class RoomUserRole implements Serializable {
private static final long serialVersionUID = 1102368085498665957L;
@Id
@ManyToOne()
@JoinColumn(name = "room_id", referencedColumnName = "id")
private Room room;
@Id
@ManyToOne()
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
@Id
@ManyToOne()
@JoinColumn(name = "role_id", referencedColumnName = "id")
private Role role;
// ... equals & hashcode
}
Answer the question
In order to leave comments, you need to log in
Good afternoon.
Probably, first of all, I should clarify one question...
- Are you trying to create a java code for an already prepared table? (db first approach)
- Or are you trying to write java code and want it to be like in the specified table? (code first approach).
If the first approach, then you need to describe not entities, but rather work with the JDBC API.
You should provide more data about the interaction of your entities, but I can suggest the following:
First, the User & Role entities. There should most likely be a ManyToMany connection between them. In simple words, a user can have several roles (admin, user, moderator, etc.). Accordingly, you will have 3 tables: users, roles, user_roles
Further, the essence of Room is not very clear. But most likely it is either OneToMany & ManyToOne or ManyToMany.
As for your RoomUserRole entity, you don't need to use @Id
.
@UniqueConstraint
should be enough.
https://www.baeldung.com/jpa-unique-constraints
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question