關於Hinernate三個很是重要的類,配置類(Configuration)、會話工廠類(SessionFactory)、會話類(Session)。java
配置類主要負責管理Hibernate的配置信息以及啓動信息。如:hibernate.cfg.xml和*.hbm.xml。mysql
會話工廠類(SessionFactory)是生成Session的工廠,它保存了當前數據庫中全部的映射關係,他只有一個可選的二級緩存對象,而且是線程安全的。會話工廠類是一個很是重量級對象,他的初始化過程會消耗大量的資源。sql
會話類Session是數據庫持久化操做的核心。經過他能夠實現數據庫的增刪改查操做。它不是線程安全的。數據庫
<!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> <!-- 數據庫驅動 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 數據庫鏈接URL --> <property name="connection.url">jdbc:mysql://localhost:3306/book</property> <!-- 數據庫鏈接用戶名 --> <property name="connection.username">sa</property> <!-- 數據庫鏈接密碼 --> <property name="connection.password">123</property> <!-- 數據庫官方語言 --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 輸出sql語句 --> <property name="show_sql">true</property> <!-- 映射文件.經過xml方式 --> <mapping resource="com/hbn/bean/Book.hbm.xml"/> </session-factory> </hibernate-configuration>
添加HibernateUtil.java緩存
public class HibernateUtil { /** * 爲每一個session提供獨立的副本 */ private static final ThreadLocal<Session> THREAD_LOCAL = new ThreadLocal<Session>(); private static SessionFactory sessionFactory = null; static { // 建立sessionFactory rebuildSessionFactory(); } /** * 建立sessionFactory */ public static void rebuildSessionFactory() { Configuration cfg = new Configuration().configure(); try { // 此方法在4.3中已通過時,採用以下方法: // sessionFactory = cfg.buildSessionFactory(); sessionFactory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build()); } catch (HibernateException e) { System.out.println("建立sessionFactory異常:" + e); e.printStackTrace(); } } /** * 獲取sessionFactory對象 * * @return */ public static SessionFactory getSessionFactory() { return sessionFactory; } /** * 獲取session * * @return 返回回去的session對象 */ public static Session getSession() throws HibernateException { Session session = THREAD_LOCAL.get(); if (null == session || !session.isConnected()) { if (null == sessionFactory) { // 建立會話工廠 rebuildSessionFactory(); } // getCurrentSession會自動關閉 // getCurrentSession建立的session韓劇i綁定在當前線程中 // 使用getCurrentSeesion須要在配置文件中加入<property name="hibernate.current_session_context_class">thread</property> //session = sessionFactory != null ? sessionFactory.getCurrentSession() : null; // openSession 不會自動關閉,必須手動關閉 // openSession 建立的session不會綁定在本地中 session = sessionFactory != null ? sessionFactory.openSession() : null; THREAD_LOCAL.set(session); } return session; } /** * 關閉Session * * @throws HibernateException */ public static void clsoeSession() throws HibernateException { Session session = THREAD_LOCAL.get(); THREAD_LOCAL.set(null); if (null != session) { session.close(); } } }
須要注意的是:安全
sessionFactory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build());
若是使用的是本地事務(jdbc事務) <property name="hibernate.current_session_context_class">thread</property> or 若是使用的是全局事務(jta事務) <property name="current_session_context_class">jta</property>
否則那會報錯:org.hibernate.HibernateException: No CurrentSessionContext configured!session
二、使用openSession獲取session:app
sesion不會自動關閉,回去手動關閉。測試
openSession建立的 session不綁定在當前線程中。ui
3.建立一個實體類Book.java:
public class Book implements Serializable { /** * */ private static final long serialVersionUID = 1L; private int id; private String name; private double price; private int count; private String auth; private String remark; public Book() { } 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; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getCount() { return count; } public void setCount(int count) { count = count; } public String getAuth() { return auth; } public void setAuth(String auth) { this.auth = auth; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
添加實體類的映射文件:Book.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.hbn.bean.Book" table="book"> <!-- id值 --> <id name="id" column="id" type="int"> <generator class="native" /> </id> <property name="name" type="string"> <column name="name" /> </property> <property name="price" type="double"> <column name="price" /> </property> <property name="count" type="int"> <column name="count" /> </property> <property name="auth" type="string"> <column name="auth" /> </property> <property name="remark" type="string"> <column name="remark" /> </property> </class> </hibernate-mapping>
該配置必須最好是和實體類放在同一目錄,及實體類在那,他就在那。
添加後,須要在hibernate.cfg.xml中添加該映射文件,供hibernate加載:
<!-- 映射文件 --> <mapping resource="com/hbn/bean/Book.hbm.xml"/>
基本建立好後,能夠編寫一個test來測試啦!
public class TestBook { @Test public void test() { Book book = new Book(); book.setName("hibernate"); book.setAuth("mrk"); book.setCount(1); book.setPrice(12.5); book.setRemark("hibernate Test"); // 使用hibernate Session session = null; try { session = HibernateUtil.getSession(); session.beginTransaction(); session.save(book); session.getTransaction().commit(); System.out.println("保存成功!"); } catch (Exception e) { System.err.println("保存失敗:" + e); e.printStackTrace(); if (null != session) { session.getTransaction().rollback(); } } finally { HibernateUtil.clsoeSession(); } } }
運行結果:
INFO: HHH000397: Using ASTQueryTranslatorFactory Hibernate: insert into book (name, price, count, auth, remark) values (?, ?, ?, ?, ?) 六月 22, 2016 11:23:17 下午 org.hibernate.engine.jdbc.spi.SqlExceptionHelper$StandardWarningHandler logWarning WARN: SQL Warning Code: 1265, SQLState: 01000 六月 22, 2016 11:23:17 下午 org.hibernate.engine.jdbc.spi.SqlExceptionHelper$StandardWarningHandler logWarning WARN: Data truncated for column 'price' at row 1 保存成功!
hibernate第一次坑太多,使用註解的時候若是出現 unkown entity...檢查下你註解使用的Entity是否是hibernate的,若是是請換位javax.xxx.entity的。