Ida*_*mit 8 java hibernate jpa sql-server-2012
我有一个DateTime列作为主键的表:
USE [idatest]
GO
CREATE TABLE [dbo].[DatesTbl](
[creationDate] [datetime] NOT NULL
CONSTRAINT [PK_DatesTbl] PRIMARY KEY CLUSTERED
(
[creationDate] ASC
))
GO
Run Code Online (Sandbox Code Playgroud)
当我在做entityManager.merge时,我得到重复的PK违规,因为datetime为milisec保存了3位数,但是hibernet将它转换为datetime2,它为milisec保存7位数.在java代码中,我使用LocaDatetime,它为milsec保存10位数.
我已经尝试过在Hibernate MSSQL datetime2映射中解释的解决方案, 但它不起作用:java代码如下所示:pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<groupId>com.example</groupId>
<artifactId>spring-jap-test</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>7.0.0.jre8</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
Run Code Online (Sandbox Code Playgroud)
DatesTbl类
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class DatesTbl {
@Column(columnDefinition = "DATETIME", nullable = false)
@Id
private LocalDateTime creationDate;
}
Run Code Online (Sandbox Code Playgroud)
主要课程
@EnableTransactionManagement
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Main.class);
EntityManagerFactory entityManagerFactory = context.getBean(EntityManagerFactory.class);
final EntityManager entityManager = entityManagerFactory.createEntityManager();
final LocalDateTime creationDate = LocalDateTime.of(2018, 12, 26, 8, 10, 40, 340);
entityManager.getTransaction().begin();
final DatesTbl datesTbl = entityManager.merge(new DatesTbl(creationDate));
entityManager.getTransaction().commit();
System.out.println("test");
}
@Bean
@Primary
public DataSource getDataSource() {
SQLServerDataSource ds = null;
try {
ds = new SQLServerDataSource();
ds.setServerName("localhost");
ds.setDatabaseName("idatest");
ds.setIntegratedSecurity(true);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return ds;
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(true);
hibernateJpaVendorAdapter.setGenerateDdl(true);
hibernateJpaVendorAdapter.setDatabase(Database.SQL_SERVER);
return hibernateJpaVendorAdapter;
}
@Bean
public LocalContainerEntityManagerFactoryBean abstractEntityManagerFactoryBean(
JpaVendorAdapter jpaVendorAdapter) {
Properties properties = new Properties();
properties.setProperty(FORMAT_SQL, String.valueOf(true));
properties.setProperty(SHOW_SQL, String.valueOf(true));
properties.setProperty(DIALECT, ModifiedSQLServerDialect.class.getTypeName());
LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean =
new LocalContainerEntityManagerFactoryBean();
localContainerEntityManagerFactoryBean.setDataSource(getDataSource());
localContainerEntityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
localContainerEntityManagerFactoryBean.setJpaProperties(properties);
localContainerEntityManagerFactoryBean.setPackagesToScan("enteties");
return localContainerEntityManagerFactoryBean;
}
@Bean
public PlatformTransactionManager platformTransactionManager(EntityManagerFactory emf) {
return new JpaTransactionManager(emf);
}
}
public class ModifiedSQLServerDialect extends SQLServer2012Dialect {
public ModifiedSQLServerDialect () {
super();
registerColumnType(Types.TIMESTAMP, "timestamp");
registerColumnType(Types.DATE, "timestamp");
registerColumnType(Types.TIME, "timestamp");
registerHibernateType(Types.TIMESTAMP, "timestamp");
registerHibernateType(Types.DATE, "timestamp");
registerHibernateType(Types.TIME, "timestamp");
}
}
Run Code Online (Sandbox Code Playgroud)
但我仍然在SQLServer探查器中看到:
exec sp_executesql N'select datestbl0_.creationDate as creation1_0_0_ from DatesTbl datestbl0_ where datestbl0_.creationDate=@P0 ',N'@P0 `datetime2`','2018-12-26 08:10:40.0000003'
Run Code Online (Sandbox Code Playgroud)
解决方案有什么问题?
该问题与mssql-jdbc(版本4.x和6.x)中的一个问题有关,PreparedStatement.setTimestamp(index,timestamp,calendar)存在数据类型转换问题,它总是将LocalDateTime具有datetime2数据类型的参数发送到SQL服务器(忽略)表的列类型)。由于datetime(0.00333秒)和datetime2(100纳秒)的精度不同,并且datetime用作PK,Hibernate在这种情况下工作错误。
当我们运行主程序时,其creationDate值为2018-12-26 08:10:40.000000340,并且该值在数据库中保存为2018-12-26 08:10:40.000,因为 Hibernate 在数据库中找不到具有相同键的记录。当我们再次运行主程序时,Hibernate 首先检查是否有具有相同键的记录,使用
'从 DatesTbldatestbl0_ 选择datestbl0_.creationDate作为creation1_0_0_,其中datestbl0_.creationDate=@P0',N'@P0'datetime2'','2018-12-26 08:10:40.0000003'
看来SQL Server将datetime表中的值向上转换来datetime2进行比较,并且没有返回任何记录。因此Hibernate再次插入记录,并导致主键冲突。
正如 Vlad Mihalcea 所建议的,使用 DATETIME 列作为 PK 并不是一个好主意。
但是,假设我们仍然需要该datetime列作为 PK,则以下解决方法应该有效。解决这个问题的关键是让datetime和之间的比较datetime2返回true。为了实现这一点,我们可以在传递给数据库之前将datetime2值截断/舍入为相应的datetime值。对主程序的以下更改使用 SQL Server 2012 Express 进行测试,没有错误。
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Main.class);
EntityManagerFactory entityManagerFactory = context.getBean(EntityManagerFactory.class);
final EntityManager entityManager = entityManagerFactory.createEntityManager();
LocalDateTime creationDate0 = LocalDateTime.of(2018, 12, 26, 8, 10, 40, 341340340);
LocalDateTime creationDate3 = LocalDateTime.of(2018, 12, 26, 8, 10, 40, 343340340);
LocalDateTime creationDate7 = LocalDateTime.of(2018, 12, 26, 8, 10, 40, 346670340);
LocalDateTime creationDate10 = LocalDateTime.of(2018, 12, 26, 8, 10, 40, 349670340);
entityManager.getTransaction().begin();
final DatesTbl datesTbl0 = entityManager.merge(new DatesTbl(roundNanoSecForDateTime(creationDate0)));
final DatesTbl datesTbl3 = entityManager.merge(new DatesTbl(roundNanoSecForDateTime(creationDate3)));
final DatesTbl datesTbl7 = entityManager.merge(new DatesTbl(roundNanoSecForDateTime(creationDate7)));
final DatesTbl datesTbl10 = entityManager.merge(new DatesTbl(roundNanoSecForDateTime(creationDate10)));
entityManager.getTransaction().commit();
System.out.println("test");
}
private static LocalDateTime roundNanoSecForDateTime(LocalDateTime localDateTime) {
int nanoSec = localDateTime.getNano();
// The rounding is based on following results on SQL server 2012 express
// select cast(cast('2018-12-26 08:10:40.3414999' as datetime2) as datetime);
// 2018-12-26 08:10:40.340
// select cast(cast('2018-12-26 08:10:40.3415000' as datetime2) as datetime);
// select cast(cast('2018-12-26 08:10:40.3444999' as datetime2) as datetime);
// 2018-12-26 08:10:40.343
// select cast(cast('2018-12-26 08:10:40.3445000' as datetime2) as datetime);
// select cast(cast('2018-12-26 08:10:40.3484999' as datetime2) as datetime);
// 2018-12-26 08:10:40.347
// select cast(cast('2018-12-26 08:10:40.3485000' as datetime2) as datetime);
// 2018-12-26 08:10:40.350
int last7DigitOfNano = nanoSec - (nanoSec / 10000000) * 10000000;
int roundedNanoSec = 0;
if (last7DigitOfNano < 1500000) {
roundedNanoSec = nanoSec - last7DigitOfNano;
} else if (last7DigitOfNano < 4500000) {
roundedNanoSec = nanoSec - last7DigitOfNano + 3000000;
} else if (last7DigitOfNano < 8500000) {
roundedNanoSec = nanoSec - last7DigitOfNano + 7000000;
} else {
roundedNanoSec = nanoSec - last7DigitOfNano + 10000000;
}
System.out.println("Before Rounding" + nanoSec);
System.out.println("After Rounding" + roundedNanoSec);
return localDateTime.withNano(roundedNanoSec);
}
Run Code Online (Sandbox Code Playgroud)
参考:
1. SQL Server 中的 DateTime2 与 DateTime
2.日期和时间数据类型和函数 (Transact-SQL)
| 归档时间: |
|
| 查看次数: |
336 次 |
| 最近记录: |