vikiiii vikiiii - 6 days ago 7
Java Question

How can I create a foreign key constraint using hibernate annotations?

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

I have two tables each having a primary key User and 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
}


Question Table.

@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 one more table, UserAnswer, which has userId and questionId as foreign keys from the above two tables.

But I am unable to find how I can reference these constraints 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.

Answer

@Column is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming Questions to Question, since an instance represents a single question, and not several ones. Then create the 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 
}

The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.

Comments