2013-01-31 137 views
1

我不知道如何在Hibernate中强制只读列。如何在Hibernate中设置只读列?

我想将idgroup设置为只读列。即使我设置insertable=falseupdatable=false,在休眠SQL我可以读:

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; 
} 
.. 
} 

我想有一个只读col因为我可以利用IDMS自动生成DBMS,所以我不想在Hibernate中使用密钥自动生成,因为它不是群集安全的。

+0

看看http://docs.jboss.org/hibernate/orm/3.5/reference/en-US/html/readonly.html和http://ndpsoftware.com/HibernateMappingCheatSheet.html - 他们可能会给你提示 –

+0

谢谢瑞秋,但第一个链接指的是只读实体,而我没有看到第二个对我的案例 – daniele

+0

有用啊。以为你可以将乐观锁设置为true –

回答

-1

解决方案是使用包装类,如Integer,而不是原始类型,如int。 当Hibernate将得到一个空指针时,它将委托生成的id到DBMS。

4

我想你可以标记一个@Column标注为updatable=false

+0

已经完成了,如果你阅读了GroupId.getIdgroup() – daniele

0

你可以尝试使现场瞬间,这将是由实体管理器通过@Transient注释被忽略。

然后,当持久化实体时,该字段将不是查询的一部分。

+0

以上的代码并且当我阅读? – daniele

+0

它不会被包括在内。 –

-2

@ReadOnlyProperty注释将帮助你在这种情况下。

+0

添加关于*如何帮助的解释总是有用的。 – Tavo

+0

它没有帮助我。至少我发现的一个是org.springframework.data.annotation.ReadOnlyProperty。我没有找到该名称的Hibernate属性。 – MiguelMunoz