如何在JPA2中强制设置@ManyToOne字段? [英] How to make a @ManyToOne field mandatory in JPA2?

查看:321
本文介绍了如何在JPA2中强制设置@ManyToOne字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为应用程序设计持久性存储库.

我是 Hibernate + JPA2 的新手,并且在创建更复杂的关系时遇到了麻烦,在这种情况下,我是外来强制性密钥.

一个例子(只是写在记事本上,所以不完全是这样.)

我有一个称为Person的顶级人才,可以担任多篇文章(另一类).

如果我这样映射我的顶级班级

@Entity
@Table(name="tb_people")
public class Person{
    @Id
    @GeneratedValue
    public long         id;

    @OneToMany(mappedBy="person")
    List<Post>          listOfPosts;

    .
    . more code
    .

}

@Entity
@Table(name="tb_posts")
public class Post{

    @Id
    @GeneratedValue
    public long         id;

    @ManyToOne
    @JoinColumn(name = "person_id")
    Person              person;

    .
    .more code
    .

}

如何使用注释使Post中的人员字段成为必填字段?

我尝试使用@Column(nullable = false),但遇到一个异常,告诉我我不能在@ManyToOne集合上使用该批注.

谢谢!

解决方案

您必须使用@JoinColumn(name=..., nullable=false)而不是@Column

请参见完整的API

I am designing the persistence repository for an app.

I am new to Hibernate+JPA2 and I am having trouble creating more complex relationships in this case a Foreign mandatory key.

An example (just wrote on notepad, so it's not exactly this.)

I have a Top Class called Person which can hold several Posts (another class).

If I map my top class like this

@Entity
@Table(name="tb_people")
public class Person{
    @Id
    @GeneratedValue
    public long         id;

    @OneToMany(mappedBy="person")
    List<Post>          listOfPosts;

    .
    . more code
    .

}

@Entity
@Table(name="tb_posts")
public class Post{

    @Id
    @GeneratedValue
    public long         id;

    @ManyToOne
    @JoinColumn(name = "person_id")
    Person              person;

    .
    .more code
    .

}

How can I using annotations make the person field in Post mandatory ?

I tryed with @Column(nullable=false) but I get an exception telling me I cannot use that annotation on a @ManyToOne Collection.

Thank you !

解决方案

You have to use @JoinColumn(name=..., nullable=false) not @Column

See the complete API

这篇关于如何在JPA2中强制设置@ManyToOne字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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