英文:
Why @Column(unique = true) does not work?
问题
我有以下代码:
``` java
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "LAST_NAME")
private String lastName;
@NotNull
@Column(name = "LOGIN", unique = true)
private String login;
@Column(name = "PASSWORD")
private String password;
@Column(name = "ROLE")
private UserRole role;
@Column(name = "E_MAIL", unique = true)
private String email;
@Convert(converter = UserStrategyConverter.class)
@Column(name = "STRATEGY")
private UserStrategy userStrategy;
@Column(name = "SUBSCRIPTION")
private Boolean subscription;
@Column(name = "MONEY")
private BigDecimal money;
我的问题:当我从 Postman 中以 JSON 形式发送此对象时:
{
"firstName": "Daniel",
"lastName": "xxx",
"password": "daniel",
"role": "ROLE_USER",
"email": "test@test.pl",
"subscription": false,
"money": "1200"
}
它会在实体中创建对象。问题是,我可以多次复制此对象,而不是在列(email
和 login
)中使用 unique = true
。有谁可以解释一下为什么?
<details>
<summary>英文:</summary>
I have following code:
``` java
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "LAST_NAME")
private String lastName;
@NotNull
@Column(name = "LOGIN", unique = true)
private String login;
@Column(name = "PASSWORD")
private String password;
@Column(name = "ROLE")
private UserRole role;
@Column(name = "E_MAIL", unique = true)
private String email;
@Convert(converter = UserStrategyConverter.class)
@Column(name = "STRATEGY")
private UserStrategy userStrategy;
@Column(name = "SUBSCRIPTION")
private Boolean subscription;
@Column(name = "MONEY")
private BigDecimal money;
My problem: When I put this object from postman in json:
{
"firstName": "Daniel",
"lastName": "xxx",
"password": "daniel",
"role": "ROLE_USER",
"email": "test@test.pl",
"subscription": false,
"money": "1200"
}
It create object in entity. Problem is because I can multiply this object again and again instead of unique = true
in columns (email
and login
). Can anyone explain me why?
答案1
得分: 1
Hibernate只会在模式生成时考虑unique = true
约束。
在模式生成期间,将添加以下约束:
alter table User
add constraint UK_u31e1frmjp9mxf8k8tmp990i unique (email)
如果不使用模式生成,那么使用unique = true
是没有意义的。
英文:
Hibernate will take into account the constraint unique = true
only at the time of schema generation.
During schema generation the following constraint will be added:
alter table User
add constraint UK_u31e1frmjp9mxf8k8tmp990i unique (email)
If you do not use the schema generation there is no sense of using unique = true
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论