2

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

@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;
     }
   }

我正在使用带有 Wildfly 9 的微软 jdbc42

4

1 回答 1

1

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

带有 Java7 的 SQL Server 的 JDBC 版本 3 存在问题: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

测试代码:

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();
}
于 2016-06-21T19:21:56.533 回答