English 中文(简体)
JPA: Partial contraint
原标题:JPA: Partial contraint

我需要一个实体的“部分禁止<>>。

@Entity
public class MyEntity 
{
  @NotNull
  private String name;

  @ManyToOne @NotNull
  private Type type;
}

Only for a sinlge type I need the name to be unique.

可通过@UniqueConstraint查询。 或者,我是否需要用@PrePersist@PreUpdate倾听者? 迄今为止,我没有执行过这样的听众,但即使我检查了这名听众中的反攻,这是否保证防止重复入境?

<>Update>

Let s assume the constraint should only be active for type=special

  • Allowed {id=1,type=normal,name=Test},{id=2,type=normal,name=Test}
  • Not allowed: {id=3,type=special,name=Test},{id=4,type=special,name=Test}
最佳回答

My understanding of the @UniqueContraint is that it may contain a list of column names that together define the uniqueness.

See: unique constraint check in JPA

   @UniqueConstraint(columnNames={"name", "type"}) 

I would expect this to enforce uniqueness across name and type. (No time to test though.)

Edit:

Aha. 因此,我现在理解这个问题。 这种做法如何带来第三个特征:

 int mySpecialValue;

这种属性没有公共规定。 相反,其价值由 set类确定:

 public void setType(String theType){

      type = theType;          

      if ( "special".equals(type) ){
              mySpecialValue = 0;
      } else {
              mySpecialValue = makeUniqueInt(); // eg. some date twiddling
      }

 }

现在是把我的特别任务包括在内的独特制约因素。 因此,对于所有专业人员来说,独一无二的特性完全取决于名称,因为其他人总是有不同的名称,因此姓名可以重复。

       Allowed {id=1,type=normal,name=Test, msv = 343223 },
                {id=2,type=normal,name=Test, msv = 777654 } <== not dup
       Not allowed: {id=3,type=special,name=Test, msv =0 },
                        {id=4,type=special,name=Test, msv =0} <== dup  
问题回答




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签