我有以下课程:
@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))
为什么布尔值被创建为非null而字符串/时间戳不是?如果您尝试插入没有电子邮件或密码的用户,我将不会有例外,但是使用此生成的架构则不会。有没有另一种方法可以强制Hibernate创建不可空的字段?
答案 0 :(得分:2)
默认情况下,类层次结构的访问类型由 @Id或@EmbeddedId注释的位置。如果这些注释 在一个字段上,然后只考虑字段的持久性和 通过该字段访问该州。如果有注释 getter,然后只有getter被认为是持久性和 通过getter / setter访问state。
当您在getter上注释@Id
时,您正在使用属性访问权限。因此,hibernate将忽略字段上标记的所有映射注释,并仅在getter上使用注释来生成DDL。由于getter上没有注释,因此使用默认设置。
如果您更改为@Id
上的注释userID
而非getUserID()