Setting a JPA timestamp column to be generated by the database?

前端 未结 12 2051
忘了有多久
忘了有多久 2020-12-12 23:19

In my SQL Server 2000 database, I have a timestamp (in function not in data type) column of type DATETIME named lastTouched set to getdate()<

12条回答
  •  悲哀的现实
    2020-12-13 00:15

    I do not think that every database has auto-update timestamps (e.g. Postgres). So I've decided to update this field manually everywhere in my code. This will work with every database:

    thingy.setLastTouched(new Date());
    HibernateUtil.save(thingy);
    

    There are reasons to use triggers, but for most projects, this is not one of them. Triggers dig you even deeper into a specific database implementation.

    MySQL 5.6.28 (Ubuntu 15.10, OpenJDK 64-Bit 1.8.0_66) seems to be very forgiving, not requiring anything beyond

    @Column(name="LastTouched")
    

    MySQL 5.7.9 (CentOS 6, OpenJDK 64-Bit 1.8.0_72) only works with

    @Column(name="LastTouched", insertable=false, updatable=false)
    

    not:

    FAILED: removing @Temporal
    FAILED: @Column(name="LastTouched", nullable=true)
    FAILED: @Column(name="LastTouched", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
    

    My other system info (identical in both environments)

    • hibernate-entitymanager 5.0.2
    • hibernate-validator 5.2.2
    • mysql-connector-java 5.1.38

提交回复
热议问题