如何使用Hibernate批注标记外键约束? [英] How can I mark a foreign key constraint using Hibernate annotations?

查看:100
本文介绍了如何使用Hibernate批注标记外键约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Hibernate批注为数据库表编写模型类.

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

我有两个表,每个表都有一个主键User和Question.

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
}

问题表.

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

我还有一个表UserAnswer,其中有来自上面两个表的userId和questionId作为外键.

And I have one more table, UserAnswer, which has userId and questionId as foreign keys from the above two tables.

但是我无法在UserAnswer表中找到如何引用这些约束.

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
}

我该如何实现?

推荐答案

@Column不是适当的注释.您不想在列中存储整个用户或问题.您要在实体之间创建关联.首先将Questions重命名为Question,因为一个实例代表一个问题,而不是多个问题.然后创建关联:

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

休眠文档对此进行了解释.阅读.并阅读注释的javadoc.

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

这篇关于如何使用Hibernate批注标记外键约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆