How to create a foreign key constraint using sleep mode annotations?

I am trying to use hibernate annotation to write a model class for my database tables.

I have two tables, each of which has a primary user key and a 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 } 

Table of questions.

 @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 } 

And I have another UserAnswer table that has userId and questionId as foreign keys from the two above tables.

But I cannot find how I can refer to these restrictions in the UserAnswer table.

 @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 } 

Please help me achieve this? Thanks in advance.

+52
java hibernate hibernate-mapping hibernate-annotations
Mar 15 '13 at 7:14
source share
2 answers

@Column not a relevant annotation. You do not want to store a complete User or Question in a column. You want to create a relationship between entities. Start by renaming Questions to Question , as the instance represents one question, not several. Then create an association:

 @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 } 

Hibernate documentation explains this. Read. And also read javadoc annotations.

+48
Mar 15 '13 at 7:31
source share

The @Join column(name="reference_column_name") can be used above this property or field of the class that any other object refers to.

+1
Feb 05 '16 at 12:06 on
source share



All Articles