如何在Hibernate中设置只读列? [英] How to set read-only columns in Hibernate?
问题描述
我不知道如何在Hibernate中强制使用只读列.
I don't know how to force read-only columns in Hibernate.
我想将idgroup设置为只读列.即使我设置了insertable=false
和updatable=false
,在休眠SQL中我也可以读取:
I would like to set idgroup as read only column. Even if I set insertable=false
and updatable=false
, in the hibernate SQL I can read:
Hibernate: insert into groups (description, name, account_idaccount, idgroup) values (?, ?, ?, ?)
但我想获得:
insert into groups (description, name, account_idaccount) values (?, ?, ?)
这是我的课程:
@Entity
@Table(name = "groups")
public class Group implements java.io.Serializable {
private static final long serialVersionUID = -2948610975819234753L;
private GroupId id;
private Account account;
private String name;
private String description;
@EmbeddedId
@AttributeOverrides({@AttributeOverride(name = "idgroup", column = @Column(name = "idgroup", insertable = false)),
@AttributeOverride(name = "accountIdaccount", column = @Column(name = "account_idaccount", nullable = false))})
public GroupId getId() {
return id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "account_idaccount", nullable = false, insertable = false, updatable = false)
public Account getAccount() {
return account;
}
@Column(name = "description", length = 512)
public String getDescription() {
return description;
}
@Column(name = "name", nullable = false, length = 128)
public String getName() {
return name;
}
..
}
@Embeddable
public class GroupId implements java.io.Serializable {
private int idgroup;
private int accountIdaccount;
@Column(name = "idgroup", insertable= false, updatable= false)
public int getIdgroup() {
return this.idgroup;
}
@Column(name = "account_idaccount", nullable = false)
public int getAccountIdaccount() {
return this.accountIdaccount;
}
..
}
我想为idgroup创建一个只读列,因为我可以利用DBMS的id自动生成功能,我不希望在Hibernate中使用密钥自动生成功能,因为它不是群集安全的.
I would like to have a read only column for idgroup because I can exploit the id auto-generation of the DBMS, I do not want to use the key auto-generation in Hibernate because it is not cluster-safe.
推荐答案
解决方案使用包装器类,例如Integer
,非原始类型,例如int
.
当Hibernate获得空指针时,它将把ID的生成委托给DBMS.
The solution is using wrapper classes, such as Integer
, not primitive types like int
.
When Hibernate will get a null pointer it will delegate the generation of the id to the DBMS.
这篇关于如何在Hibernate中设置只读列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!