JPA在SQLServer 2008中将列LocalDateTime创建为datetime2

时间:2016-06-21 15:56:36

标签: hibernate date jpa datetime2

我的实体有这个属性......

@Convert(converter = LocalDateTimeAtributeConverter.class)
@Column(name="dthr_ult_atualizacao")
private LocalDateTime ultimaAtualizacao;

在服务器中,该列由JPA创建为:

dthr_ult_atualizacao    (datetime2(7), null)

通过代码,我将以下值保存在此列中:

2016-05-09T15:20:00.357

当我在数据库中选择直接时,值是正确的:

2016-05-09 15:20:00.3570000

但是当我通过JPA恢复这个值时,值是错误的:

2016-05-07T15:20:00.357

请注意,这一天错了两天。

所以,如果我手动更改数据类型,一切正常。怎么了?

我的转换器:

import java.time.LocalDateTime;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter
public class LocalDateTimeAtributeConverter implements AttributeConverter<LocalDateTime, java.sql.Timestamp> {

    @Override
    public java.sql.Timestamp convertToDatabaseColumn(LocalDateTime entityValue)    
    {
        if (entityValue != null) {
           return java.sql.Timestamp.valueOf(entityValue);
        }
        return null;
     }

     @Override
     public LocalDateTime convertToEntityAttribute(java.sql.Timestamp   databaseValue) {
         if (databaseValue != null) {
             return databaseValue.toLocalDateTime();
         }
        return null;
     }
   }

我正在使用Microsofr jdbc42和wildfly 9

1 个答案:

答案 0 :(得分:1)

您使用的是旧的JDBC驱动器吗?

SQL Server的JDBC版本3与Java7存在问题: https://support.microsoft.com/kb/2652061

您可以在此处获取新版本: https://www.microsoft.com/en-us/download/details.aspx?id=11774

我做了一些测试并得到了这个结果:

日期 - JDBC版本

2016-06-21 16:19:00.383 - 4.2.6420.100

2016-06-19 16:19:38.603 - 3.0.1301.101

Teste代码:

public static void main(String[] args) throws Exception {
    String url = "jdbc:sqlserver://localhost\\SQLEXPRESS;databasename=teste_date";
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    Connection connection = DriverManager.getConnection(url,"sa", "password");

    Date time = Calendar.getInstance().getTime();

    PreparedStatement psDel = connection.prepareStatement("delete from teste");
    psDel.executeUpdate();
    psDel.close();

    PreparedStatement psInsert = connection.prepareStatement("insert into teste values (? , ?)");
    psInsert.setInt(1, 1);
    psInsert.setTimestamp(2, new Timestamp(time.getTime()));
    psInsert.executeUpdate();
    psInsert.close();

    PreparedStatement ps = connection.prepareStatement("select * from teste");
    ResultSet rs = ps.executeQuery();
    String driverVersion = connection.getMetaData().getDriverVersion();
    while (rs.next()) {
        Timestamp date = rs.getTimestamp(2);
        System.out.println(date + " - " + driverVersion);
    }
    rs.close();
    ps.close();

    connection.close();
}