2016-06-21 27 views
2

我的實體有這個屬性...JPA創建列LocalDateTime如DATETIME2 SQLServer的在2008年

@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 

當我做一個選擇直接在數據庫中,該值爲correc T:

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

您使用的舊的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年6月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(); 
} 
+1

謝謝。就是它。你解決了我的問題。 –