无法使@ManyToOne关系可为空 [英] Cannot make @ManyToOne relationship nullable

查看:763
本文介绍了无法使@ManyToOne关系可为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多对一的关系,我想可以为空:

I have a many-to-one relationship that I want to be nullable:

@ManyToOne(optional = true)
@JoinColumn(name = "customer_id", nullable = true)
private Customer customer;

不幸的是,JPA一直将数据库中的列设置为NOT NULL.谁能解释一下?有办法使它起作用吗?请注意,我使用带有Hibernate的JBoss 7,JPA 2.0作为持久性提供程序和PostgreSQL 9.1数据库.

Unfortunately, JPA keeps setting the column in my database as NOT NULL. Can anyone explain this? Is there a way to make it work? Note that I use JBoss 7, JPA 2.0 with Hibernate as persistence provider and a PostgreSQL 9.1 database.

编辑:

我找到了造成问题的原因.显然,这是由于我在引用的实体Customer中定义主键的方式:

I found the cause of my problem. Apparently it is due to the way I defined the primary key in the referenced entity Customer:

@Entity
@Table
public class Customer { 
    @Id
    @GeneratedValue
    @Column(columnDefinition="serial")
    private int id;
}

似乎对主键使用@Column(columnDefinition="serial")会自动将引用它的外键设置为数据库中的NOT NULL.将列类型指定为serial时,这确实是预期的行为吗?在这种情况下,是否有启用空的外键的解决方法?

It seems that using @Column(columnDefinition="serial") for the primary key automatically sets the foreign keys referencing it to NOT NULL in the database. Is that really the expected behavior when specifying the column type as serial? Is there a workaround for enabling nullable foreign keys in this case?

谢谢.

推荐答案

我找到了解决问题的方法.在实体Customer中定义主键的方式很好,问题出在外键声明中.应该这样声明:

I found the solution to my problem. The way the primary key is defined in entity Customer is fine, the problem resides in the foreign key declaration. It should be declared like this:

@ManyToOne
@JoinColumn(columnDefinition="integer", name="customer_id")
private Customer customer;

实际上,如果省略了属性columnDefinition="integer",则默认情况下会将外键设置为源列:具有其自身序列的非空序列.当然这不是我们想要的,因为我们只想引用自动递增的ID,而不是创建一个新的ID.

Indeed, if the attribute columnDefinition="integer" is omitted the foreign key will by default be set as the source column: a not-null serial with its own sequence. That is of course not what we want as we just want the to reference the auto-incremented ID, not to create a new one.

此外,正如我在执行一些测试时所观察到的那样,似乎还需要属性name=customer_id.否则,外键列仍将设置为源列.我认为这是一种奇怪的行为.欢迎发表评论或其他信息以澄清这一点!

Besides, it seems that the attribute name=customer_id is also required as I observed when performing some testing. Otherwise the foreign key column will still be set as the source column. This is a strange behavior in my opinion. Comments or additional information to clarify this are welcome!

最后,此解决方案的优势在于ID是由数据库(而不是JPA)生成的,因此,当手动插入数据或通过脚本进行数据插入或维护时,我们无需担心插入ID.

Finally, the advantage of this solution is that the ID is generated by the database (not by JPA) and thus we do not have to worry about it when inserting data manually or through scripts which often happens in data migration or maintenance.

这篇关于无法使@ManyToOne关系可为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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