gpt4 book ai didi

java - Hibernate 的 nullable = false 在所有情况下都不起作用

转载 作者:行者123 更新时间:2023-11-29 12:14:06 24 4
gpt4 key购买 nike

我有以下类(class):

@Entity
@Table(name = "USERS")
public class User {

private Long userID;

@Id
@Column(name = "userID")
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
public Long getUserID() {
return userID;
}

@Column(nullable = false)
private boolean isActive;

@Column(nullable = false, unique = true)
private String email;

@Column(nullable = false)
private String password;


@Column
@Temporal(TemporalType.TIMESTAMP)
private Calendar lastLoggedIn;

@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Calendar createdDate;

@Version
private Integer version;

public String getEmail() {
return email;
}

public boolean isActive() {
return isActive;
}

public void setActive(boolean isActive) {
this.isActive = isActive;
}

public void setEmail(String email) {
this.email = email;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public Calendar getLastLoggedIn() {
return lastLoggedIn;
}

public void setLastLoggedIn(Calendar lastLoggedIn) {
this.lastLoggedIn = lastLoggedIn;
}

public Calendar getCreatedDate() {
return createdDate;
}

public void setCreatedDate(Calendar createdDate) {
this.createdDate = createdDate;
}

public Integer getVersion() {
return version;
}

public void setVersion(Integer version) {
this.version = version;
}

public void setUserID(Long userID) {
this.userID = userID;
}

public User(Long userID, String email, String password, Calendar lastLoggedIn, Calendar createdDate, Integer version) {

}

// No argument constructor
public User() {}
}

当我运行我的应用程序时,Hibernate 加载配置并为用户创建表。我正在使用 PostgreSQL。这是正在生成的 SQL 语句(由 hibernate 记录):

Hibernate: create table USERS 
(userID int8 not null, active boolean not null, createdDate timestamp,
email varchar(255), lastLoggedIn timestamp,
password varchar(255), version int4, primary key (userID))

为什么 boolean 值被创建为非空值而字符串/时间戳不是?如果您尝试插入没有电子邮件或密码的用户,我不会有异常(exception),但使用这个生成的模式它不会。还有另一种方法可以强制 Hibernate 将字段创建为不可空吗?

最佳答案

来自 5.1.4.1.2. Access type :

By default the access type of a class hierarchy is defined by the position of the @Id or @EmbeddedId annotations. If these annotations are on a field, then only fields are considered for persistence and the state is accessed via the field. If there annotations are on a getter, then only the getters are considered for persistence and the state is accessed via the getter/setter.

当您在 getter 上注释 @Id 时,您正在使用属性访问。因此,hibernate 将忽略字段上标记的所有映射注释,只使用 getter 上的注释来生成 DDL。因为 getter 上没有注解,所以使用默认设置。

如果您更改为在 userID 上注释 @Id 而不是 getUserID()

,您应该会得到想要的结果

关于java - Hibernate 的 nullable = false 在所有情况下都不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13354300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com