在两个非空字段

时间:2017-12-14 10:36:14

标签: java sql oracle jpa

我有一个包含两个字段的实体:

@ManyToOne(fetch = FetchType.LAZY, optional = true)
private Organization organization;

@Column(length = 15)
private String ref;

我想在organizationref添加唯一键,只有在organizationref都不为空时,此唯一键才有效。

例如,当我在其中插入两个记录时:

organization = 1, ref = 'R1'

organization = 1, ref = 'R1'

这会产生约束违规,到目前为止我对这种情况没有任何问题。

当我在其中插入两个记录时:

organization = null, ref = null

organization = null, ref = null

这不会产生约束违规,到目前为止我对这种情况也没有问题。

我遇到的问题是:

organization = 1, ref = null

organization = 1, ref = null

或者

organization = null, ref = 'R1'

organization = null, ref = 'R1'

这两种情况都会产生一个我不想要的约束违规,因为如果只有organizationref都不为空,我只希望唯一约束有效。

这是我宣布唯一约束的方式:

@Table(uniqueConstraints = {
        @UniqueConstraint(columnNames = { "organization", "ref" })
})

我该如何解决这个问题。

PS:我正在使用Oracle 12c。

编辑:

  • 字段organizationref都可以为空。 JPA

  • 我声明的@UniqueConstraint注释将生成SQL代码:

    创建独特的索引“USERNAME”。“UK_TABLENAME_1”在“USERNAME”上。“TABLENAME”(“组织”,“参考”)

2 个答案:

答案 0 :(得分:0)

您需要为此创建基于函数的索引。

class TestForm( forms.Form):
   name = forms.CharField()
   ...
   customer_iid  = MultipleValueField( required=False) 

...

# POST
sanitize_keys( request, only=('customer_iid',) )
#print( 'Debug: customer_iid', request.POST.getlist('customer_iid', []) )
form = TestForm( request.POST)

答案 1 :(得分:0)

Oracle对于唯一索引非常奇怪:

  

升序唯一索引允许多个NULL值。但是,在   降序唯一索引,多个NULL值被视为   重复值,因此不允许。

因此,您可以使用唯一索引处理此问题:

create unique index unq_t_organization_ref on t(organization, ref);

索引应忽略唯一值。