首页 > 解决方案 > 休眠日期,时间戳类型令人困惑

问题描述

我是休眠新手,请帮助我。谢谢你。

我对.. 、 和 的类型hibernate感到java困惑oracle

  1. 我在Oracle 11g 数据库中有 2 种数据类型。-> Date,Timestamp(6)

  2. 我使用hibernate映射了这个。-> ,datetimestamp

  3. 它可以映射Date(DB)totimestamp(hbm)Date(DB)to Date(hbm)?

  4. 反之亦然timestamp(DB)todate(hbm)timestamp(DBto timestamp(hbm)?

  5. 那么我应该在 Java 代码中使用什么类型呢?

Oracle DB / Hibernate / Java 代码

  1. 日期/日期/日期或时间戳??

  2. 日期/时间戳/日期或时间戳??

  3. 时间戳/日期/日期或时间戳??

  4. 时间戳/时间戳/日期或时间戳??

四种情况都有可能吗?我很困惑..我在我的 oracle 数据库中进行了测试。

出现一些问题,例如我无法保存小时、分钟、秒..

帮助我学习hibernate的基础知识。

hbm.xml 映射文件

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:oracle</property>
        <property name="hibernate.connection.username">scott</property>
        <property name="hibernate.connection.password">scott</property>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
        <!-- <property name="hibernate.default_schema">MKYONG</property> -->
        <property name="show_sql">true</property>
        <mapping resource="com/mkyong/user/DBUser.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

用户代码 (java)

public class DBUser implements java.io.Serializable {
    private int userId;
    private String username;
    private String createdBy;
    private Date createdDate;
    private Date createdTimestamp;
    private String createdTest;
    //something getter setter ~~
}

标签: javaoraclehibernatedatetimestamp

解决方案


您可以同时使用 HBM 和 JAVA。

java.sql.Timestamp用于时间戳。Oracle java.sql.Date中的TIMESTAMP 用于日期。Oracle 中的日期

上述两个类都从 java.util.Date 扩展而来。您可以对两者都使用java.sql.Timestamp,但 Oracle 将在 INSERT/UPDATE 期间为 DATE 丢弃时间组件。使用java.sql.Date作为 DATE 会让你更清楚。

从 Java 8 开始,您可以在下面使用。

org.hibernate.type.LocalDateType - Maps a java.time.LocalDate to a Oracle DATE    
org.hibernate.type.LocalDateTimeType - Maps a java.time.LocalDateTime to a Oracle TIMESTAMP

推荐阅读