How can I add/persist a record/bean without a field so that it gets the default value?
Trying to make a minimal example, suppose I have the postgres table created as:
CREATE TABLE FOO(id int, ts timestamp without time zone default current_timestamp);
and I have
@Entity
@Table(name = "foo")
public class FooBean {
@Id
@Column(name = "id", nullable = false)
private int id;
@Column(name = "ts", nullable = false, length = 50)
private Instant ts;
public int getId() {return id;}
public Instant getTs() {return ts;}
public void setId(int id) {
this.id = id;
}
public void setTs(Instant ts) {
this.ts = ts;
}
}
And then e.g.
@ApplicationScoped
public class FooService {
@Inject
EntityManager em;
@Transactional
public boolean addAFoo(int id){
//left out: make sure it is not already added, else return false, then:
FooBean fooBean = new FooBean();
fooBean.setId(id);
em.persist(fooBean);
return true;
}
}
The problem here is that although I did not setup explicitly fooBean.ts, it is null, and so postgres does not assign the default value, but tries to set ts to null on the created record (and we get an error,cause the column is not nullable ).
How can this be overcome / how can I tell JPA to allow the DB to use the default value at insertion time?