Java中的@UniqueConstraint注解

发布于 09-07 00:44 字数 312 浏览 9 评论 0原文

我有一个Java bean。现在,我想确保该字段应该是唯一的。

我正在使用以下代码:

@UniqueConstraint(columnNames={"username"})
public String username;

但我收到一些错误:

@UniqueConstraint is dissallowed for this location

使用唯一约束的正确方法是什么?

注意:我正在使用play框架。

I have a Java bean. Now, I want to be sure that the field should be unique.

I am using the following code:

@UniqueConstraint(columnNames={"username"})
public String username;

But I'm getting some error:

@UniqueConstraint is dissallowed for this location

What's the proper way to use unique constraints?

Note: I am using play framework.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

执着的年纪2024-09-14 00:44:15

为了确保字段值是唯一的,您可以编写

@Column(unique=true)
String username;

@UniqueConstraint 注释用于在表级别注释多个唯一键,这就是将其应用于字段时出现错误的原因。

参考文献 (JPA TopLink):

To ensure a field value is unique you can write

@Column(unique=true)
String username;

The @UniqueConstraint annotation is for annotating multiple unique keys at the table level, which is why you get an error when applying it to a field.

References (JPA TopLink):

遮云壑2024-09-14 00:44:15

您可以在类级别使用以下语法

@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames={"username"})})
public class SomeEntity {
    @Column(name = "username")
    public String username;
}

You can use at class level with following syntax

@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames={"username"})})
public class SomeEntity {
    @Column(name = "username")
    public String username;
}
只想待在家2024-09-14 00:44:15

我目前也在使用带有 hibernate 和 JPA 2.0 注释的 play 框架,这个模型工作没有问题

@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames = {"id_1" , "id_2"})})
public class class_name {

@Id
@GeneratedValue
public Long id;

@NotNull
public Long id_1;

@NotNull
public Long id_2;

}

希望它有帮助。

I'm currently using play framework too with hibernate and JPA 2.0 annotation and this model works without problems

@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames = {"id_1" , "id_2"})})
public class class_name {

@Id
@GeneratedValue
public Long id;

@NotNull
public Long id_1;

@NotNull
public Long id_2;

}

Hope it helped.

半枫2024-09-14 00:44:15

注意:在 Kotlin 中,在注释中声明数组的语法使用 arrayOf(...) 而不是 {...}

@Entity
@Table(uniqueConstraints=arrayOf(UniqueConstraint(columnNames=arrayOf("book", "chapter_number"))))
class Chapter(@ManyToOne var book:Book,
              @Column var chapterNumber:Int)

注意: 从 Kotlin 1.2 开始,可以使用 [...] 语法,因此代码变得更加简单

@Entity
@Table(uniqueConstraints=[UniqueConstraint(columnNames=["book", "chapter_number"])])
class Chapter(@ManyToOne var book:Book,
              @Column var chapterNumber:Int)

Note: In Kotlin the syntax for declaring the arrays in annotations uses arrayOf(...) instead of {...}

@Entity
@Table(uniqueConstraints=arrayOf(UniqueConstraint(columnNames=arrayOf("book", "chapter_number"))))
class Chapter(@ManyToOne var book:Book,
              @Column var chapterNumber:Int)

Note: As of Kotlin 1.2 its is possible to use the [...] syntax so the code become much simpler

@Entity
@Table(uniqueConstraints=[UniqueConstraint(columnNames=["book", "chapter_number"])])
class Chapter(@ManyToOne var book:Book,
              @Column var chapterNumber:Int)
无边思念无边月2024-09-14 00:44:15

方式1:

@Entity
@Table(name = "table_name", 
       uniqueConstraints={
                          @UniqueConstraint(columnNames = "column1"),
                          @UniqueConstraint(columnNames = "column2")
                         }
      )

->这里 Column1 和 Column2 分别充当唯一约束。
例如:如果任何时候column1 或column2 值匹配,那么您将收到 UNIQUE_CONSTRAINT 错误。

方式2:

@Entity
@Table(name = "table_name", 
       uniqueConstraints={@UniqueConstraint(columnNames ={"column1","column2"})})

->这里,column1 和column2 组合值都充当唯一约束

Way1 :

@Entity
@Table(name = "table_name", 
       uniqueConstraints={
                          @UniqueConstraint(columnNames = "column1"),
                          @UniqueConstraint(columnNames = "column2")
                         }
      )

-> Here both Column1 and Column2 acts as unique constraints separately.
Ex : if any time either the value of column1 or column2 value matches then you will get UNIQUE_CONSTRAINT Error.

Way2 :

@Entity
@Table(name = "table_name", 
       uniqueConstraints={@UniqueConstraint(columnNames ={"column1","column2"})})

-> Here both column1 and column2 combined values acts as unique constraints

牵强ㄟ2024-09-14 00:44:15

@UniqueConstraint 此注释用于在表级别注释以逗号分隔的单个或多个唯一键,这就是您收到错误的原因。
仅当您让 JPA 创建表时它才会起作用

示例

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder(builderClassName = "Builder", toBuilder = true)
@Entity
@Table(name = "users", uniqueConstraints = @UniqueConstraint(columnNames = {"person_id", "company_id"}))
public class AppUser extends BaseEntity {

    @Column(name = "person_id")
    private Long personId;

    @ManyToOne
    @JoinColumn(name = "company_id")
    private Company company;
}

https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/UniqueConstraint.html

另一方面,要确保字段值是唯一的,您可以写

@Column(unique=true)
String username;

@UniqueConstraint this annotation is used for annotating single or multiple unique keys at the table level separated by comma, which is why you get an error.
it will only work if you let JPA create your tables

Example

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder(builderClassName = "Builder", toBuilder = true)
@Entity
@Table(name = "users", uniqueConstraints = @UniqueConstraint(columnNames = {"person_id", "company_id"}))
public class AppUser extends BaseEntity {

    @Column(name = "person_id")
    private Long personId;

    @ManyToOne
    @JoinColumn(name = "company_id")
    private Company company;
}

https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/UniqueConstraint.html

On the other hand To ensure a field value is unique you can write

@Column(unique=true)
String username;
一生独一2024-09-14 00:44:15

定义列约束

只要唯一约束仅基于一个字段,我们就可以对该列使用@Column(unique=true)。

让我们在 personNumber 字段上定义一个唯一约束:

@Column(unique=true)
private Long personNumber;

当我们执行模式创建过程时,我们可以从日志中验证它:

[main] DEBUG org.hibernate.SQL -
    alter table Person add constraint UK_d44q5lfa9xx370jv2k7tsgsqt unique (personNumber)

定义唯一约束

JPA 帮助我们使用 @UniqueConstraint 注释来实现这一点。我们在 uniqueConstraints 属性下的 @Table 注释中执行此操作。让我们记住指定列的名称:

@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "personNumber", "isActive" }) })

我们可以在生成模式后对其进行验证:

[main] DEBUG org.hibernate.SQL -
    alter table Person add constraint UK5e0bv5arhh7jjhsls27bmqp4a unique (personNumber, isActive)

Defining the Column Constraints

Whenever the unique constraint is based only on one field, we can use @Column(unique=true) on that column.

Let's define a unique constraint on the personNumber field:

@Column(unique=true)
private Long personNumber;

When we execute the schema creation process, we can validate it from the logs:

[main] DEBUG org.hibernate.SQL -
    alter table Person add constraint UK_d44q5lfa9xx370jv2k7tsgsqt unique (personNumber)

Defining Unique Constraints

JPA helps us to achieve that with the @UniqueConstraint annotation. We do that in the @Table annotation under the uniqueConstraints attribute. Let's remember to specify the names of the columns:

@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "personNumber", "isActive" }) })

We can validate it once the schema is generated:

[main] DEBUG org.hibernate.SQL -
    alter table Person add constraint UK5e0bv5arhh7jjhsls27bmqp4a unique (personNumber, isActive)
请别遗忘我2024-09-14 00:44:15
   @Entity @Table(name = "stock", catalog = "mkyongdb",
   uniqueConstraints = @UniqueConstraint(columnNames =
   "STOCK_NAME"),@UniqueConstraint(columnNames = "STOCK_CODE") }) public
   class Stock implements java.io.Serializable {

   }

唯一约束仅用于创建组合键,该组合键将是唯一的。它将表示该表作为主键组合为唯一。

   @Entity @Table(name = "stock", catalog = "mkyongdb",
   uniqueConstraints = @UniqueConstraint(columnNames =
   "STOCK_NAME"),@UniqueConstraint(columnNames = "STOCK_CODE") }) public
   class Stock implements java.io.Serializable {

   }

Unique constraints used only for creating composite key ,which will be unique.It will represent the table as primary key combined as unique.

指尖上的星空2024-09-14 00:44:15

您可以在类级别使用@UniqueConstraint,用于表中的组合主键。例如:

 @Entity
 @Table(name = "PRODUCT_ATTRIBUTE", uniqueConstraints = {
       @UniqueConstraint(columnNames = {"PRODUCT_ID"}) })
public class ProductAttribute{}

you can use @UniqueConstraint on class level, for combined primary key in a table. for example:

 @Entity
 @Table(name = "PRODUCT_ATTRIBUTE", uniqueConstraints = {
       @UniqueConstraint(columnNames = {"PRODUCT_ID"}) })
public class ProductAttribute{}
锦爱2024-09-14 00:44:15

唯一的注释应放置在属性声明的正上方。
UniqueContraints 进入数据类声明上方的 @Table 注释。见下文:

@Entity
@Table(uniqueConstraints= arrayOf(UniqueConstraint(columnNames = arrayOf("col_1", "col_2"))))
data class Action(
        @Id @GeneratedValue @Column(unique = true)
        val id: Long?,
        val col_1: Long?,
        val col_2: Long?,
)

Unique annotation should be placed right above the attribute declaration.
UniqueContraints go into the @Table annotation above the data class declaration. See below:

@Entity
@Table(uniqueConstraints= arrayOf(UniqueConstraint(columnNames = arrayOf("col_1", "col_2"))))
data class Action(
        @Id @GeneratedValue @Column(unique = true)
        val id: Long?,
        val col_1: Long?,
        val col_2: Long?,
)
注定孤独终老2024-09-14 00:44:15

length 属性的值必须大于或等于名称属性长度,否则将引发错误。

有效

@Column(name = "typ e", length = 4, unique = true)
private String type;

无效,type.length: 4 != length 属性: 3

@Column(name = "type", length = 3, unique = true)
private String type;

The value of the length property must be greater than or equal to name atribute length, else throwing an error.

Works

@Column(name = "typ e", length = 4, unique = true)
private String type;

Not works, type.length: 4 != length property: 3

@Column(name = "type", length = 3, unique = true)
private String type;
眼眸印温柔2024-09-14 00:44:15

对我来说添加 @Column(name = "column_name", length = 11, unique = true) 有效

For me adding @Column(name = "column_name", length = 11, unique = true) worked

寄风2024-09-14 00:44:15

使用 @UniqueConstraint 时要注意:

在某些情况下(使用 MySql 时),我们必须通过添加 @Column(name="product_id", length = 6) 来提供唯一约束中使用的列的长度,因为默认情况下 Hibernate 将创建具有最大大小(默认行为)的列,这会在创建唯一约束时在 MySql 中生成错误(指定的键太长;最大键长度为 1000 字节)

Be aware when using @UniqueConstraint :

In Some cases( when using MySql), we have to provide the length of columns used in unique contraint by adding @Column(name="product_id", length = 6), because by default Hibernate will create columns with the max size (default behavior) which generate an error in MySql when creating the unique constraint (Specified key was too long; max key length is 1000 bytes)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文