An issue has arisen in the RoomUser during the development of the project. Before explaining it, let me provide some context.
Context
In this project, there are three main tables:
- User: This table is necessary for using the online study service. It is required when creating and utilizing the functionality to join study rooms.
- StudyRoom: This table represents the study rooms.
- RoomUser: This table stores the users registered in study rooms.
Since RoomUser manages the users in study rooms, it has foreign keys (FK) referencing User and StudyRoom. Initially, I attempted to create a composite primary key using IdClass. The purpose was to prevent duplicates since additional registrations were required if a user was added to the StudyRoom.
However, this approach leads to several issues:
- For video chat purposes, we need to send unique data that can identify the user to Openvidu.
- Due to security concerns, we cannot send the UserID, which would allow user identification.
- If we generate an artificial key in RoomUser and use it as the primary key, duplicates may occur with User and StudyRoom.
UniqueConstraint
Considering these conditions, a suitable solution is to use UniqueConstraint. UniqueConstraint allows setting multiple unique keys. We generate a separate artificial key and set User and StudyRoom as composite unique constraints.
@Entity
@Table(name = "room_users",
uniqueConstraints = {@UniqueConstraint(
name = "UniqueUserAndStudyRoom",
columnNames = {"users_id","study_rooms_id"})})
public class RoomUser extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long roomUserId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "users_id",nullable = false)
private User user;
@Column(nullable = false)
private String roomUserName;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="study_rooms_id",nullable = false)
private StudyRoom studyRoom;
}
To be honest, when I first learned about it, I thought, "Why bother using it when we can simply set up a composite primary key?" But as it turns out, I needed it right away. If you ever come across a similar situation, I hope you take a moment to consider it.
'Project' 카테고리의 다른 글
Project_온라인스터디_Chpater0?_Persistence Context(N+1 Test) (0) | 2023.06.30 |
---|---|
Project_화상스터디_Chapter03_Spring으로만 화상채팅 만들기 (0) | 2023.05.01 |
Project_화상스터디_Chapter02_WebSocket (0) | 2023.04.01 |
Project_화상스터디_Chapter01_WebRTC (0) | 2023.03.25 |
Project_화상스터디_Chapter00_개요 & WebRTC (0) | 2023.03.24 |