I have a JPA/EclipseLink model with multiple parameters whose values are set as defaults by the PostgreSQL database. Specifically, I have:
id
column of type SERIAL
which auto-increments when new rows are addedcreated_at
column of type TIMESTAMP
which defaults to now()
My model looks like this:
import javax.persistence.*;
@Entity
@Table(name="entity")
@NamedQuery(name="Entity.findAll", query="SELECT e from Entity e")
public class Entity {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="created_at")
private java.sql.Timestamp createdAt;
// constructor, getters, and setters
}
When I try to insert a row with persist()
in javax.persistence.EntityManager
, the insertion fails because a NULL
value is being set for the created_at
column. Rather than inserting NULL
, I want to simply not insert anything into that column and allow PostgreSQL to set it to now()
. Essentially, I would like to use @GeneratedValue
on createdAt
, but that annotation is only for primary keys and cannot be used on multiple attributes. Is there another annotation I can use that will accomplish this?
use @Transient to make JPA ignoring the field.
@Column. Let's start with the @Column annotation. It is an optional annotation that enables you to customize the mapping between the entity attribute and the database column.
Annotation Type TransientSpecifies that the property or field is not persistent. It is used to annotate a property or field of an entity class, mapped superclass, or embeddable class. Example: @Entity public class Employee { @Id int id; @Transient User currentUser; ... }
columnDefinition definition: The SQL fragment that is used when generating the DDL for the column. columnDefinition default: Generated SQL to create a column of the inferred type.
You may want insertable=false
in the Column
annotation:
@Column(name="created_at", insertable=false)
private java.sql.Timestamp createdAt;
From: http://docs.oracle.com/javaee/5/api/javax/persistence/Column.html
boolean insertable (Optional) Whether the column is included in SQL INSERT statements generated by the persistence provide
You can add @DynamicInsert
on your entity class. The insert statement will include null fields when without this annotation. Also, you can add @ DynamicUpdate
when executing the update statement.
@Entity
@DynamicInsert
@DynamicUpdate
@Table(name="entity")
@NamedQuery(name="Entity.findAll", query="SELECT e from Entity e")
public class Entity {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="created_at")
private java.sql.Timestamp createdAt;
// constructor, getters, and setters
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With