Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude an entity field when doing an update with JPA

Is there a way to make a field non-persistent at update operation but persistent at create operation with JPA - Hibernate 4?

I tried it in this way

@Transient
@Id
@Column(name = "USER_NAME", nullable = false, length = 75)
private String userName;

but with @Transient annotation the field will be transient across all CRUD operations and I want a way to specify that only on this operation is persistent (create).

Is there a way to do this?

Thanks!

like image 692
aurelius Avatar asked Feb 06 '15 10:02

aurelius


Video Answer


1 Answers

You need to set updatable attribute of the @Column annotation to false:

@Column(name = "USER_NAME", nullable = false, length = 75, updatable= false)
private String userName;

The updatable attribute instruct Hibernate to omit this column from the generated UPDATE SQL statement.

I removed the @Transient and the @Id annotations.

If this column is your PK (mapped to the entity identifier), then you can only set it during INSERT, since Hibernate doesn't allow you to update an entity identifier (the updatable attribute being redundant in this case).

like image 50
Vlad Mihalcea Avatar answered Sep 18 '22 10:09

Vlad Mihalcea