Hibernate 주석을 사용하여 외래 키 제약을 어떻게 표시 할 수 있습니까?
데이터베이스 테이블에 대한 모델 클래스를 작성하기 위해 Hibernate 주석을 사용하려고합니다.
각각 기본 키 User와 Question이있는 두 개의 테이블이 있습니다.
@Entity
@Table(name="USER")
public class User
{
@Id
@Column(name="user_id")
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(name="username")
private String username;
// Getter and setter
}
질문 표.
@Entity
@Table(name="QUESTION")
public class Questions extends BaseEntity{
@Id
@Column(name="question_id")
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@Column(name="question_text")
private String question_text;
// Getter and setter
}
그리고 위의 두 테이블의 외래 키로 userId와 questionId가있는 UserAnswer 테이블이 하나 더 있습니다.
그러나 UserAnswer 테이블에서 이러한 제약 조건을 참조 할 수있는 방법을 찾을 수 없습니다.
@Entity
@Table(name="UserAnswer ")
public class UserAnswer
{
@Column(name="user_id")
private User user;
//@ManyToMany
@Column(name="question_id")
private Questions questions ;
@Column(name="response")
private String response;
// Getter and setter
}
이것을 어떻게 달성 할 수 있습니까?
@Column적절한 주석이 아닙니다. 전체 사용자 또는 질문을 열에 저장하고 싶지 않습니다. 엔티티 간의 연관을 작성하려고합니다. 인스턴스는 여러 질문이 아닌 단일 질문을 나타내므로 로 이름 Questions을 변경 하여 시작 Question합니다. 그런 다음 연결을 만듭니다.
@Entity
@Table(name = "UserAnswer")
public class UserAnswer {
// this entity needs an ID:
@Id
@Column(name="useranswer_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "question_id")
private Question question;
@Column(name = "response")
private String response;
//getter and setter
}
The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.
There are many answers and all are correct as well. But unfortunately none of them have a clear explanation.
The following works for a non-primary key mapping as well.
Let's say we have parent table A with column 1 and another table, B, with column 2 which references column 1:
@ManyToOne
@JoinColumn(name = "TableBColumn", referencedColumnName = "TableAColumn")
private TableA session_UserName;
@ManyToOne
@JoinColumn(name = "bok_aut_id", referencedColumnName = "aut_id")
private Author bok_aut_id;
@JoinColumn(name="reference_column_name") annotation can be used above that property or field of class that is being referenced from some other entity.
'IT TIP' 카테고리의 다른 글
| Vim에서 부드럽게 스크롤하는 가장 좋은 방법은 무엇입니까? (0) | 2020.11.05 |
|---|---|
| WebSocket 요청-응답 서브 프로토콜 (0) | 2020.11.05 |
| JSON 웹 서비스는 CSRF 공격에 취약합니까? (0) | 2020.11.05 |
| WordPress 단축 코드에서 AJAX를 사용하는 방법? (0) | 2020.11.05 |
| [사실] 속성은 무엇입니까? (0) | 2020.11.05 |
