mysql hibernate timestamp update_time 自动更新时间问题

博客探讨了在MySQL中使用Hibernate时,如何处理timestamp字段的自动更新问题。当更新数据时,如何确保update_time字段自动更新为当前时间。提出了在更新前手动设置当前时间的解决方案,并讨论了触发器作为替代方案的优缺点。还列举了TIMESTAMP的不同设置选项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(这是博主第一篇真正意义上的原创,该问题来源于工作中遇到的小问题)

需求分析:

一个表中,有两个字段,createtime和updatetime。

1 当insert的时候,sql两个字段都不设置,会设置为当前的时间

2 当update的时候,sql中两个字段都不设置,updatetime会变更为当前的时间


设计数据库如下:

该数据表需要一个数据的创建时间create time,和一个数据最近更新时间last update time。

CREATE TABLE `test` (
  `id` int(10) NOT NULL AUTO_INCREMENT COMMENT 'auto increase',
  `imsi` varchar(20) NOT NULL COMMENT 'imsi',
  `last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'last_update time',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'data create time',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT='test'

timestamp设置默认值是当前时间 Default CURRENT_TIMESTAMP

timestamp设置随着表变化而自动更新是ON UPDATE CURRENT_TIMESTAMP

 可以设置2个timestape字段 ,把一个字段设置为默认值更新, 另一个不自动更新。

mysql5.5不能同时设置两个字段为CURRENT_TIMESTAMP,但mysql5.6是可以的,

所以以上数据库设计是能正常实现需要的update time 和create time功能的:

测试如下:

1.直接用数据库软件(Navicat或者Sequel pro)在数据库里面

    插入一条数据,update time 和create time为当前时间;

    更新imsi,update time 变为当前时间,create time不改变;

2.用sql语句

    插入数据: INSERT INTO test set imsi='forttest' 

    update time 和create time为当前时间;

    

    更新数据:update test set imsi='forttest1' where id=1

    

(时间显示3点是指UTC+0的时间,北京时间UTC+8,是11点)


存在问题:

在hibernate映射类中设计
    @Expose(serialize = false, deserialize = false)
    @Column(name = "last_update")
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    private DateTime lastUpdate;

    @Expose(serialize = false, deserialize = false)
    @Column(name = "create_time")
    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    private DateTime createTime;

插入新的数据时不指定update_time和create_time,数据表中会自动生成插入的当前时间。(这个没问题)

更新操作时,如果update更新的是新new的一个对象,只跟原数据的id值一样的话,更新的时候update_time和create_time会同时更新为当前时间。

这个没异议,解决方案有2种,可根据业务选择:

1. 更新update的是新new的对象数据,就把原数据的create_time赋值给新new的对象;

2.更新update原数据,把要更新的字段赋值给原数据后更新;(问题出现在这里,看下面解决办法)


出现的问题:

更新update原数据,代码中last_update_time不指定赋值时,数据表中last_update时间不更新,怎么让更行操作时自动更新时间?

我的解决方案是,在更新时,将当前时间赋值给last update。就是在调用update()函数更新前,加一行代码:

databaseTest.setLastUpdate(new DateTime());

(end...   如果哪位大神有好的解决方法,请告诉我哦~)


参考方案里面有纯sql的解决办法: 

使用触发器。

当insert和update的时候触发器触发时间设置。

网上有人使用这种方法。当然不怀疑这个方法的可用性。但是对于实际的场景来说,无疑是为了解决小问题,增加了复杂性。

触发器语句:

CREATE TRIGGER `update_interface_update_time_trigger` BEFORE UPDATE ON `interface`
 FOR EACH ROW SET NEW.`updateTime` = NOW()

 

TIMESTAMP的变体
1,TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
在创建新记录和修改现有记录的时候都对这个数据列刷新

2,TIMESTAMP DEFAULT CURRENT_TIMESTAMP
在创建新记录的时候把这个字段设置为当前时间,但以后修改时,不再刷新它

3,TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
在创建新记录的时候把这个字段设置为0,以后修改时刷新它

4,TIMESTAMP DEFAULT ‘yyyy-mm-dd hh:mm:ss’ ON UPDATE CURRENT_TIMESTAMP 
在创建新记录的时候把这个字段设置为给定值,以后修改时刷新它


参考自:

mysql多个TimeStamp设置

mysql多个Timestamp设置

hibernate updatetime 自动更新时间问题

mysql5.5不能同时设置两个字段为CURRENT_TIMESTAMP

2025-06-06 21:18:24 - Initializing Spring DispatcherServlet 'dispatcherServlet' 2025-06-06 21:18:24 - Initializing Servlet 'dispatcherServlet' 2025-06-06 21:18:24 - Detected StandardServletMultipartResolver 2025-06-06 21:18:24 - Detected AcceptHeaderLocaleResolver 2025-06-06 21:18:24 - Detected FixedThemeResolver 2025-06-06 21:18:24 - Detected org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator@47a99e2e 2025-06-06 21:18:24 - Detected org.springframework.web.servlet.support.SessionFlashMapManager@4f67f6b3 2025-06-06 21:18:24 - enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data 2025-06-06 21:18:24 - Completed initialization in 1 ms 2025-06-06 21:18:24 - GET "/product/list", parameters={} 2025-06-06 21:18:24 - Mapped to com.ecommerce.controller.ProductController#productList(Model) 2025-06-06 21:18:24 - {dataSource-1} inited 2025-06-06 21:18:24 - ==> Preparing: SELECT id, name, description, price, stock, category, image_url, create_time, update_time FROM goods 2025-06-06 21:18:24 - ==> Parameters: 2025-06-06 21:18:24 - Using @ExceptionHandler com.ecommerce.exception.GlobalExceptionHandler#handleRuntimeException(RuntimeException, Model) 2025-06-06 21:18:24 - Resolved [org.springframework.jdbc.BadSqlGrammarException: <EOL><EOL>### Error querying database. Cause: java.sql.SQLSyntaxErrorException: Unknown column 'update_time' in 'field list'<EOL><EOL>### The error may exist in file [E:\webapp - 副本\webapp - 副本\target\classes\mapper\ProductMapper.xml]<EOL><EOL>### The error may involve defaultParameterMap<EOL><EOL>### The error occurred while setting parameters<EOL><EOL>### SQL: SELECT id, name, description, price, stock, category, image_url, create_time, update_time FROM goods<EOL><EOL>### Cause: java.sql.SQLSyntaxErrorException: Unknown column 'update_time' in 'field list'<EOL>; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: Unknown column 'update_time' in 'field list'] to ModelAndView [view="error"; model={error=操作错误: ### Error querying database. Cause: java.sql.SQLSyntaxErrorException: Unknown column 'update_time' in 'field list' ### The error may exist in file [E:\webapp - 副本\webapp - 副本\target\classes\mapper\ProductMapper.xml] ### The error may involve defaultParameterMap ### The error occurred while setting parameters ### SQL: SELECT id, name, description, price, stock, category, image_url, create_time, update_time FROM goods ### Cause: java.sql.SQLSyntaxErrorException: Unknown column 'update_time' in 'field list' ; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: Unknown column 'update_time' in 'field list'}] 2025-06-06 21:18:24 - Using resolved error view: ModelAndView [view="error"; model={error=操作错误: ### Error querying database. Cause: java.sql.SQLSyntaxErrorException: Unknown column 'update_time' in 'field list' ### The error may exist in file [E:\webapp - 副本\webapp - 副本\target\classes\mapper\ProductMapper.xml] ### The error may involve defaultParameterMap ### The error occurred while setting parameters ### SQL: SELECT id, name, description, price, stock, category, image_url, create_time, update_time FROM goods ### Cause: java.sql.SQLSyntaxErrorException: Unknown column 'update_time' in 'field list' ; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: Unknown column 'update_time' in 'field list'}] 2025-06-06 21:18:25 - Completed 200 OK这是为什么
最新发布
06-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值