如何在Hibernate中设置只读列?

clo*_*her 1 java database orm hibernate relational-database

我不知道如何在Hibernate中强制只读列.

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

Hibernate: insert into groups (description, name, account_idaccount, idgroup) values (?, ?, ?, ?) 
Run Code Online (Sandbox Code Playgroud)

但我想获得:

insert into groups (description, name, account_idaccount) values (?, ?, ?) 
Run Code Online (Sandbox Code Playgroud)

这是我的课程:

@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;
}
..
}
Run Code Online (Sandbox Code Playgroud)
@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;
}
..
}
Run Code Online (Sandbox Code Playgroud)

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

Bob*_*gon 7

我认为你可以将@Column注释标记为updatable=false


J. *_*rez 6

简单的:

@Column(insertable = false, updatable = false)
Run Code Online (Sandbox Code Playgroud)

  • 考虑添加更多信息来说明如何解决 OP 的问题 (3认同)