相关疑难解决方法(0)

使用Hibernate和MySQL创建时间戳和上次更新时间戳

对于某个Hibernate实体,我们需要存储其创建时间和上次更新时间.你会怎么设计这个?

  • 您将在数据库中使用哪些数据类型(假设MySQL,可能在与JVM不同的时区)?数据类型是时区感知的吗?

  • 你会在Java中使用什么数据类型(Date,Calendar,long,...)?

  • 您将负责设置时间戳 - 数据库,ORM框架(Hibernate)或应用程序员?

  • 您将使用哪些注释进行映射(例如@Temporal)?

我不只是在寻找一个可行的解决方案,而是一个安全且设计良好的解决方案.

java timestamp hibernate

228
推荐指数
10
解决办法
25万
查看次数

由于GUID重复,无法与会话org.hibernate.exception.ConstraintViolationException同步数据库状态

我使用休眠模式使用自动生成的GUID将数据插入到表中,但是有时会由于GUID重复而导致插入失败。

例如:

在Logs中,通过打印重复的GUID'0500edac-0074-4324-3436-31444231342d',在前两次尝试中插入失败。花费的时间如下

     1st attempt :08-27-2018 04:27:00.012,

     2nd attempt :08-27-2018 04:27:01.024,

     3rd attempt was not logged ,as it was successful
Run Code Online (Sandbox Code Playgroud)

但是在数据库中,我看到在'08 -27-2018 04:27:01.054'创建的GUID为'0500edac-0074-4324-3436-31444231342d'的行

所以我不确定为什么我会在前两次尝试中获得异常,然后成功地将其插入到第3次。

SQL表属性:我有一个名为“ DataHistory”的SQL Server表,其中的列名为

"DataHistoryGuid" with the following properties uniqueidentifier,ROWGUIDCOL,Primary Key column,newsequentialid .
Run Code Online (Sandbox Code Playgroud)

Hibernate属性:我正在使用hibernate将数据存储在该表中,对于GUID列,我正在使用

<id name="dataHistoryGuid" type="java.util.UUID" >
        <column name="DataHistoryGuid"/>
        <generator class="guid"/>
    </id>
Run Code Online (Sandbox Code Playgroud)

以下是异常跟踪:

[event.def.AbstractFlushingEventListener:performExecutions:324]
Could not synchronize database state with session 
org.hibernate.exception.ConstraintViolationException: could not 
 insert: [com.testProj.dataprocessor.model.sql.SqlDataHistory] 
  at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94) 
  at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) 
  at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2295) 
  at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2688) 
  at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79) 
  at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279) 
  at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263) 
  at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167) 
  at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) 
  at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) …
Run Code Online (Sandbox Code Playgroud)

java sql sql-server hibernate

7
推荐指数
1
解决办法
226
查看次数

标签 统计

hibernate ×2

java ×2

sql ×1

sql-server ×1

timestamp ×1