Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set read-only columns in Hibernate?

I don't know how to force read-only columns in Hibernate.

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 (?, ?, ?, ?) 

but I would like to obtain:

insert into groups (description, name, account_idaccount) values (?, ?, ?) 

Here are my classes:

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

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.

like image 813
cloudy_weather Avatar asked Oct 16 '25 22:10

cloudy_weather


2 Answers

I think you can mark an @Column annotation as updatable=false

like image 136
Bob Flannigon Avatar answered Oct 18 '25 11:10

Bob Flannigon


Easy:

@Column(insertable = false, updatable = false)
like image 32
J. Jerez Avatar answered Oct 18 '25 10:10

J. Jerez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!