Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: Database Generated columns

I am facing an issue with Hibernate and JPA. My requirement is column CreatedDTTM and LastUPDATEDDTTM should be populated at the DB level. I have tried following but no use. My columns are set NOT NULL. I get a "cannot insert Null into LastUpdatedDttm" exception. Any guidance is appreciated.

@Column(name="LAST_UPDATED_DTTM", insertable=false, updatable=false, columnDefinition="Date default SYSDATE") 
@org.hibernate.annotations.Generated(value=GenerationTime.INSERT) 
@Temporal(javax.persistence.TemporalType.DATE) 
private Date lastUpdDTTM; 

@Column(name="CREATED_DTTM”, insertable=false, updatable=false) 
@org.hibernate.annotations.Generated(value=GenerationTime.ALWAYS) 
@Temporal(javax.persistence.TemporalType.DATE) 
private Date createdDTTM;
like image 732
jpanewbie Avatar asked May 06 '10 07:05

jpanewbie


1 Answers

Cannot reproduce. I've tested the following entity on Derby:

@Entity
public class EntityWithGeneratedField {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "LAST_UPDATED_DTTM", insertable = false, updatable = false,
            columnDefinition = "Date default CURRENT_DATE")
    @org.hibernate.annotations.Generated(value = GenerationTime.INSERT)
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date lastUpdDTTM;

    // getters, setters
}

And the following test method passes:

@Test
public void testDateGenerationWhenInsertingEntityWithNullDate() {
    EntityWithGeneratedField e = new EntityWithGeneratedField();
    session.persist(e);
    session.flush();
    assertNotNull(e.getId());
    assertNotNull(e.getLastUpdDTTM());
}

Below, the generated SQL:

Hibernate: insert into EntityWithGeneratedField (id) values (?)
Hibernate: select entitywith_.LAST_UPDATED_DTTM as LAST2_83_ from EntityWithGeneratedField entitywith_ where entitywith_.id=?

Everything is working as expected.

My advice: check the DDL of your table, check that things do work with a raw SQL INSERT. I suspect an issue at the database level, not at Hibernate level.

like image 171
Pascal Thivent Avatar answered Oct 14 '22 08:10

Pascal Thivent