Hibernate中對映時間和日期的配置
阿新 • • 發佈:2019-02-10
在資料庫中存放時間或者日期是在Modle對映的方法。
第一步:編寫Modle類在這裡模擬一個Person的表屬性有id 人的姓名 人的生日 和人的年齡
package com.ygc.hibernate.modle; import java.io.Serializable; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name="Person") public class Person implements Serializable { private int id; private String name; private Date birthDay; private int age; @Id @GeneratedValue(strategy=GenerationType.AUTO) public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Temporal(value=TemporalType.DATE) public Date getBirthDay() { return birthDay; } public void setBirthDay(Date birthDay) { this.birthDay = birthDay; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
第二步:編寫Main方法測試類
package com.ygc.hibernate.main; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.ygc.hibernate.modle.Person; import com.ygc.hibernate.utils.HibernateUtils; public class PeronTest { /** * @param args */ public static void main(String[] args) { Person person = new Person(); person.setName("張三"); person.setAge(32); person.setBirthDay(new Date()); SessionFactory sessionFactory = HibernateUtils.getHibernates().getFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(person); session.getTransaction().commit(); session.close(); sessionFactory.close(); } }
第三步:編寫工具類
package com.ygc.hibernate.utils; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; public class HibernateUtils { private static HibernateUtils instance; private HibernateUtils(){} public static HibernateUtils getHibernates(){ if(instance==null){ instance = new HibernateUtils(); } return instance; } public SessionFactory getFactory(){ Configuration configuration = new AnnotationConfiguration().configure(); return configuration.buildSessionFactory(); } }
第四步:修改hibernate.cfg.xml配置檔案的對映
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool (use the built-in) -->
<!--<property name="connection.pool_size">1</property>-->
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<!--<property name="current_session_context_class">thread</property>-->
<!-- Disable the second-level cache -->
<!--<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>-->
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!--自動建立表-->
<property name="hbm2ddl.auto">create</property>
<!-- Drop and re-create the database schema on startup -->
<!--<property name="hbm2ddl.auto">update</property>-->
<!--<mapping resource="com/ygc/hibernate/modle/Students.hbm.xml"/>-->
<mapping class="com.ygc.hibernate.modle.Person"/>
</session-factory>
</hibernate-configuration>
第五步:修改log4j.xml或新增日誌配置
# Configure logging for testing: optionally with log file
# debug,info,warn,error,fatal
log4j.rootLogger=debug, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=D:/logs/hibernate.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.logger.org.hibernate.tool.hbm2ddl=debug
最後執行檢視結果 如果配置@Temporal(value=TemporalType.DATE)時插入的是日期,如果配置的是@Temporal(value=TemporalType.TIME)是插入的是時間。
效果:
登入mysql:
C:\Documents and Settings\Administrator>mysql -uroot -proot
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.5.15 MySQL Community Server (GPL)
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
檢視資料庫
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| hibernate |
| hibernates |
| mysql |
| performance_schema |
| test |
| xqwy |
+--------------------+
7 rows in set (0.02 sec)
使用資料庫
mysql> use hibernate;
Database changed
查詢資料庫看結果 配置為@Temporal(value=TemporalType.DATE)
mysql> select * from person;
+----+-----+------------+------+
| id | age | birthDay | name |
+----+-----+------------+------+
| 1 | 32 | 2013-09-21 | 張三 |
+----+-----+------------+------+
1 row in set (0.01 sec)
查詢資料庫看結果 配置為@Temporal(value=TemporalType.TIME)
mysql> select * from person;
+----+-----+----------+------+
| id | age | birthDay | name |
+----+-----+----------+------+
| 1 | 32 | 15:46:51 | 張三 |
+----+-----+----------+------+
1 row in set (0.00 sec)
通過查詢資料庫可以看出當配置為Date是插入的是日期,當配置為Time是插入的是時間,在開發中就可以靈活應用了,對了預設情況下是日期和時間都會插入的
查詢資料庫檢視結果。配置為@Temporal(value=TemporalType.TIMESTAMP) 預設是這個配置。
mysql> select * from person;
+----+-----+---------------------+------+
| id | age | birthDay | name |
+----+-----+---------------------+------+
| 1 | 32 | 2013-09-21 15:49:00 | 張三 |
+----+-----+---------------------+------+
1 row in set (0.00 sec)