views:

237

answers:

1

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;
A: 

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.

Pascal Thivent
Thanks for responding. YOu were right, I hadnt set DEFAULT SYSDATE at DDL level. But now I have bumped into another problem. I have set UPDATABLE = true for LastUPdatedDttm but it is still not part of update statements generated by hibernate. I need LastUpdateDDttm to be updated by SYSDATE whenever reocrd is updated.
jpanewbie
@jpanewbie Could you post this as a separate question? It's a best practice to not mix problems in a single question. Thanks.
Pascal Thivent
done. Can you please help now?
jpanewbie