`

java Date(util.Date/sql.Date/sql.Timestamp/sql.Time) & Oracle DATE Type 时分秒 精度问题

阅读更多
遇到的问题描述:
数据库为Oracle,其jdbc驱动为ojdbc14.jar。打算用Hibernate原生SQL通过setResultTransformer()的方式将查询结果赋给不被Hibernate管理的bean:
public List<FidsDepfDto> queryAllFidsDepfDto() {
		String sql = "select id as \"id\",iata as \"iata\",flight as \"flight\",dest as \"dest\",domint as \"domint\" " +
			" ,sdt as \"sdt\",task_nature as \"taskNature\",est_date as \"estDate\",act_date as \"actDate\",remark as \"remark\" " +
			" from FIDS_DEPF";
		return this.getSessionFactory().getCurrentSession().createSQLQuery(sql)
				.setResultTransformer(Transformers.aliasToBean(FidsDepfDto.class))
				.list();  
结果发现:返回的FidsDepfDto list中所有FidsDepfDto对象的时间字段sdt/estDate/actDate都丢失了时分秒精度。
如果使用的是HQL(或还是原生sql,只不过使用addEntity(Class clazz)的方式(这个方法接受的参数clazz应是被hibernate管理的持久化bean,否则会抛异常)),则避免这种精度丢失的方式有:
1 XML元数据的方式配置Hibernate: 将返回日期类型(且想保留时分秒)的列在XML配置文件中指明其type为Timestamp或java.util.Date;
2 注解方式配置Hibernate:在日期类型的get方法上使用@Temporal注解:
@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "UDATE", length = 7)
	public Date getUdate() {
		return this.udate;
	}
但这里因为是想使用setResultTransformer()将原生SQL的查询结果赋给不被Hibernate管理的bean,所以上面的方式用不了。解决办法这里列举几个:
1 使用addScalar()为返回的列指定其java bean对应的类型:
String sql = "select id as \"id\",iata as \"iata\",flight as \"flight\",dest as \"dest\",domint as \"domint\" " +
			" ,sdt as \"sdt\",task_nature as \"taskNature\",est_date as \"estDate\",act_date as \"actDate\",remark as \"remark\" " +
			" from FIDS_DEPF";
		return this.getSessionFactory().getCurrentSession().createSQLQuery(sql)
				.addScalar("sdt", Hibernate.TIMESTAMP)
				//必须为所有的select返回列都指定addScalar()
				//否则未指定的列所映射的属性值会为null
				//这里省略其他select返回列的addScalar()操作
				.setResultTransformer(Transformers.aliasToBean(FidsDepfDto.class))
				.list();  

2 原生sql语句中使用oracle的to_char()将Oracle内置数据类型DATE转换为varchar后在bean中用String类型接收它。
3 其他几个牵动比较大的解决办法(具体原因见下文论述):在使用Oracle 9.2 - 10.2 jdbc驱动的时候,数据库类型别用DATE,而用TIMESTAMP;设置数据连接属性V8Compatible为true;变更oracle驱动,使用11g的jdbc驱动。

造成时分秒精度丢失的根本原因是什么那?是Oracle 驱动的问题!
在Oracle9.2之后,引入了内置数据类型TIMESTAMP。之所以引入它,是因为内置数据类型DATE的最小单位为秒;DATE的主要问题是它粒度不能足够区别出两个事件哪个先发生。9.2版本后ORACLE在DATE数据类型上扩展出来了TIMESTAMP数据类型,它包括了所有DATE数据类型的年月日时分秒的信息,而且包括了小数秒(纳秒Nanoseconds级的)的信息。如果你想把DATE类型转换成TIMESTAMP类型,就使用CAST函数。
也正是从oracle 9.2开始,内置数据类型DATE和TIMESTAMP在使用9i的JDBC驱动做查询时,DATE被映射为java.sql.Date,TIMESTAMP被映射为java.sql.Timestamp。
幸运的是,从Oracle11开始,其JDBC驱动程序又重新开始回归为将内置类型DATE映射为java.sql.Timestamp(正如9.2之前的那样)。
综上,时分秒精度的丢失与hibernate无关,是oracle jdbc驱动的问题。最好的解决办法就是:换驱动。经测试,将最开始使用的10g的驱动ojdbc14.jar换为11g的驱动ojdbc5.jar后,时分秒精度丢失的问题成功解决!

英文原文:
http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-faq-090281.html#08_00
引用
Prior to 9.2, the Oracle JDBC drivers mapped the DATE SQL type to java.sql.Timestamp. This made a certain amount of sense because the Oracle DATE SQL type contains both date and time information as does java.sql.Timestamp. The more obvious mapping to java.sql.Date was somewhat problematic as java.sql.Date does not include time information. It was also the case that the RDBMS did not support the TIMESTAMP SQL type, so there was no problem with mapping DATE to Timestamp.

In 9.2 TIMESTAMP support was added to the RDBMS. The difference between DATE and TIMESTAMP is that TIMESTAMP includes nanoseconds and DATE does not. So, beginning in 9.2, DATE is mapped to Date and TIMESTAMP is mapped to Timestamp. Unfortunately if you were relying on DATE values to contain time information, there is a problem.

There are several ways to address this problem in the 9.2 through 10.2 drivers:
  • Alter your tables to use TIMESTAMP instead of DATE. This is probably rarely possible, but it is the best solution when it is.
  • Alter your application to use defineColumnType to define the columns as TIMESTAMP rather than DATE. There are problems with this because you really don't want to use defineColumnType unless you have to (see What is defineColumnType and when should I use it? ).
  • Alter you application to use getTimestamp rather than getObject. This is a good solution when possible, however many applications contain generic code that relies on getObject, so it isn't always possible.
  • Set the V8Compatible connection property. This tells the JDBC drivers to use the old mapping rather than the new one. You can set this flag either as a connection property or a system property. You set the connection property by adding it to the java.util.Properties object passed to DriverManager.getConnection or to OracleDataSource.setConnectionProperties. You set the system property by including a -D option in your java command line.
java -Doracle.jdbc.V8Compatible="true" MyApp

Oracle JDBC 11.1 fixes this problem. Beginning with this release the driver maps SQL DATE columns to java.sql.Timestamp by default. There is no need to set V8Compatible to get the correct mapping. V8Compatible is strongly deprecated. You should not use it at all. If you do set it to true it won't hurt anything, but you should stop using it.

Although it was rarely used that way, V8Compatible existed not to fix the DATE to Date issue but to support compatibility with 8i databases. 8i (and older) databases did not support the TIMESTAMP type. Setting V8Compatible not only caused SQL DATE to be mapped to Timestamp when read from the database, it also caused all Timestamps to be converted to SQL DATE when written to the database. Since 8i is desupported, the 11.1 JDBC drivers do not support this compatibility mode. For this reason V8Compatible is desupported.

As mentioned above, the 11.1 drivers by default convert SQL DATE to Timestamp when reading from the database. This always was the right thing to do and the change in 9i was a mistake. The 11.1 drivers have reverted to the correct behavior. Even if you didn't set V8Compatible in your application you shouldn't see any difference in behavior in most cases. You may notice a difference if you use getObject to read a DATE column. The result will be a Timestamp rather than a Date. Since Timestamp is a subclass of Date this generally isn't a problem. Where you might notice a difference is if you relied on the conversion from DATE to Date to truncate the time component or if you do toString on the value. Otherwise the change should be transparent.

If for some reason your app is very sensitive to this change and you simply must have the 9i-10g behavior, there is a connection property you can set. Set mapDateToTimestamp to false and the driver will revert to the default 9i-10g behavior and map DATE to Date.




oracle 9/10的jdbc驱动将内置数据类型DATE映射为java.sql.Date,为什么会造成时分秒精度的丢失那?
答:java.sql.Date can not hold time,but java.util.Date can。
JDK中的说法(下贴三楼):
http://stackoverflow.com/questions/383783/oracle-sql-date-conversion-problem-using-ibatis-via-java-jdbc
引用
To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

java.sql.Date is not a real date:
http://www.thunderguy.com/semicolon/2003/08/14/java-sql-date-is-not-a-real-date/
引用
java.sql.Date stores only date information, not times. Simply converting a java.util.Date into a java.sql.Date will silently set the time to midnight. So, to store date/times to be manipulated as java.util.Date objects



Native Query的自定义转换器:
http://www.cnblogs.com/highriver/archive/2011/03/03.html
分享到:
评论

相关推荐

    java.sql.与java.util

    `java.sql.Time`仅包含时间信息(小时、分钟和秒),而`Timestamp`则包含日期和时间,精度到纳秒,可以视为`java.util.Date`的增强版,适用于需要高精度的场景。 在数据库操作中,有时需要将字符串转换为`java.sql....

    Oracle Timestamp with Time zone & java

    Java 8引入的`java.time`包相比于旧的`java.util.Date`和`java.sql.Timestamp`,在性能和易用性上都有显著提升。但在数据库层面,Oracle也有优化的索引策略,如B树索引或函数索引,来提高对Timestamp with Time Zone...

    浅谈java中六大时间类的使用和区别

    Java提供了多种时间类来满足不同的需求,包括`java.util.Date`, `java.sql.Date`, `java.sql.Time`, `java.sql.Timestamp`, `java.text.SimpleDateFormat`, 和 `java.util.Calendar`。下面我们将深入探讨这些类的...

    mybatis如何使用Java8的日期LocalDate和LocalDateTime详解

    Oracle引入了全新的日期时间API,包括`LocalDate`、`LocalTime`和`LocalDateTime`,这些类提供了更加直观且强大的日期时间处理能力,替代了传统且复杂的`java.sql.Date`、`java.sql.Timestamp`和`java.util.Date`。...

    时间类型DateTime的处理.docx

    在Java中,DateTime处理涉及到多个类,包括`java.util.Date`, `java.sql.Date`, 和 `java.sql.Timestamp`。这些类各自有不同的用途和特点: 1. **`java.util.Date`**: 这是Java中的基础日期类,表示从1970年1月1日...

    Mysql、orcale 中的数据类型与java中的数据类型对应表.pdf

    在 Oracle 中,Date 类型对应 Java 中的 java.util.Date 和 java.sql.Date 类型。其中 java.util.Date 类型的作用范围更广泛,因此通常应用于业务逻辑层,而 java.sql.Date 类型主要用于数据库交互。 在数据类型...

    时间类型DateTime的处理.pdf

    java.sql.Date sqlDate = new java.sql.Date(sqlTimestamp.getTime()); ``` 需要注意的是,`SimpleDateFormat`的`setLenient(false)`方法用于确保日期时间格式的严格匹配,避免因不规范的输入导致意外的结果。 在...

    Java中Date,Calendar,Timestamp的区别以及相互转换与使用

    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); ``` - 在数据库操作中,如 `ResultSet` 的 `getDate()` 和 `PreparedStatement` 的 `setDate()` 方法通常使用 `java.sql.Date`。 3. **java....

    Hibernate类型映射

    13. `time`:映射Java的`java.util.Date`或`java.sql.Time`,对应的SQL类型是`TIME`。用于存储时间。 14. `timestamp`:映射Java的`java.util.Date`或`java.sql.TimeStamp`,对应的SQL类型是`TIMESTAMP`。用于存储...

    在oracle中插入当前时间

    Timestamp sqlTimestamp = new java.sql.Timestamp(time); // 如果需要自定义时间格式 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); Timestamp ts = new Timestamp(sdf....

    java实现oracle插入当前时间的方法

    在Java编程中,当需要将当前时间插入到Oracle数据库时,必须注意Java...在处理日期时间时,不仅要考虑Java和Oracle之间的类型匹配,还要注意时区和精度的问题。遵循这些原则,可以避免转换错误,确保数据的正确插入。

    Hibernate中数据类型

    - **日期时间类型**:`java.util.Date` 和 `java.sql.Date` 对应于 `DATE`,`java.util.Date` 和 `java.sql.Time` 映射为 `TIME`,而 `java.util.Date`、`java.sql.Timestamp` 和 `java.util.Calendar` 则映射到 `...

    hibernate映射类型.doc

    11. `java.util.Date` 或 `java.sql.Timestamp`: 映射到 `Timestamp`,表示日期和时间。 12. `byte[]`: 映射到 `Blob`,用于存储二进制大对象,如图片或文档。 13. `String`: 映射到 `CLOB` (Oracle的 `Clob`),用于...

    hibernate的知识总结

    - **时间精度映射**:通过`@Temporal`注解定义映射到数据库的时间精度,比如指定时间类型是`java.util.Date`、`java.sql.Date`还是`java.sql.Timestamp`。 ### Hibernate注解配置 内容中还涉及了Hibernate注解配置...

    java日常处理函数

    Java 8之前,主要使用`java.util.Date`, `java.util.Calendar`以及`SimpleDateFormat`类来处理日期。然而,这些API被普遍认为设计复杂且易出错。从Java 8开始,引入了新的日期时间API,`java.time`包,包括以下核心...

    DB2 与ORACLE的比对.docx

    在 ORM 框架如 Hibernate 中,DB2 的 DATE 字段映射为 Java 的 `java.util.Date` 时,可能导致错误,需要改为 TIMESTAMP。 6. **分页处理**: - ORACLE 使用 `rownum` 进行分页,而 DB2 使用 `rownumber() over()`...

    JDBC.入门到精通教程

    18. **JDBC与Java.util.Date**:通过java.sql.Date和Timestamp处理日期和时间。 19. **JDBC与Java集合**:使用ArrayList或Vector存储结果集,方便进一步处理。 20. **JDBC与Java批处理API**:结合Java 8的Stream ...

    03_Hibernate&JPA .pptx

    `@Temporal`注解用于将`java.util.Date`对象映射为数据库中的date、time、datetime或timestamp类型,通过指定`TemporalType`的类型来决定。 5. Boolean值的映射: Hibernate和JPA会自动处理Boolean类型的映射,通常...

    JDBC说明文档

    - **常用日期格式**:在Java中处理日期时,经常使用的有`java.util.Date`、`java.sql.Date`和`java.sql.Timestamp`等。 - **转换**:从字符串到`java.util.Date`,再到`java.sql.Date`,最后可以通过`...

    Hibernate单表操作实例解析

    - `timestamp`:映射到 `java.util.Date` 或 `java.sql.Timestamp`,包含日期和时间。 在数据库中,可以通过修改 `XX.hbm.xml` 文件中 `property` 的 `type` 属性来改变映射的数据库类型。 ### 对象类型映射 ...

Global site tag (gtag.js) - Google Analytics