Hibernate是一個(gè)優(yōu)秀的java持久化層解決方案,是當(dāng)今主流的對(duì)象-關(guān)系映射(ORM,ObjectRelationalMapping)工具
1.1、理解持久化Java是一種面象對(duì)象的設(shè)計(jì)語(yǔ)言。在程序運(yùn)行時(shí)的數(shù)據(jù)是以對(duì)象形式存在內(nèi)存中,而保存數(shù)據(jù)時(shí),又要以對(duì)象的形式存在關(guān)系型數(shù)據(jù)庫(kù)中。
ORM簡(jiǎn)單講:就是能在對(duì)象和關(guān)系型數(shù)據(jù)庫(kù)兩者之間進(jìn)行數(shù)據(jù)轉(zhuǎn)換的機(jī)制。Hibernate就是這樣一個(gè)中間的解決方案。關(guān)系如下圖

ORM:對(duì)象關(guān)系映射(Object Relation Mapping)
Hibernate框架:能夠?qū)崿F(xiàn)ORM框架
Hibernate是一個(gè)優(yōu)秀的Java持久化層解決方案,是當(dāng)今主流的對(duì)象-關(guān)系映射(ORM,ObjectRelationalMap
Hibernate框架對(duì)JDBC時(shí)行和封裝,簡(jiǎn)化了數(shù)據(jù)訪問層。可應(yīng)用在任何使用JDBC的場(chǎng)合如:Servlet、jsp的WEB應(yīng)用,JAVA客戶端等。

官網(wǎng):http://sourceforge.net/PRojects/hibernate/files/hibernate3/
這里下載的是3.3.2GA,
解壓后,將根目錄下的hibernate3.jar和將lib目錄下全部的jar導(dǎo)入項(xiàng)目中
同時(shí)將數(shù)據(jù)庫(kù)驅(qū)動(dòng)也導(dǎo)入這里使用Oracle 11g
其中加入了一些其它的jar包如:JSTL包
當(dāng)然也可以用MyEclipse完全集成,不用下載
三、Hibernate配置3.1、創(chuàng)建hibernate.cfg.xml文件.這是配置文件默認(rèn)名.一般放在src目錄下:作用指定數(shù)據(jù)庫(kù)連接的信息及映射文件路徑
獲取配置文件進(jìn)行修改。當(dāng)然如果記得了就全寫也可以。在下載的Hibernate解壓目錄下就有配置文件模板
hibernate-distribution-3.3.2.GA-dist/hibernate-distribution-3.3.2.GA/project/tutorials/web/src/main/resources此目錄下就有,將其復(fù)制到src目錄下進(jìn)行修改
<?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> <!-- Database connection settings --> <!-- 數(shù)據(jù)庫(kù)驅(qū)動(dòng) 不同的數(shù)據(jù)庫(kù)不一樣--> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <!-- 數(shù)據(jù)庫(kù)訪問url 不同的數(shù)據(jù)庫(kù)不一樣--> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> <!-- 數(shù)據(jù)庫(kù)連接用戶名 --> <property name="connection.username">sa</property> <!--數(shù)據(jù)庫(kù)連接用戶名的密碼 --> <property name="connection.passWord"></property> <!-- JDBC connection pool (use the built-in) --> <!--數(shù)據(jù)庫(kù)連接池默認(rèn)連接數(shù)量 --> <property name="connection.pool_size">2</property> <!-- SQL dialect --> <!--方言,不同的數(shù)據(jù)不同的版都有所不同 --> <property name="dialect">org.hibernate.dialect.HSQLDialect</property> <!-- Enable Hibernate's current session context --> <!-- Session設(shè)置 --> <property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property> <!-- Disable the second-level cache --> <!--二級(jí)緩存 --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <!-- 在執(zhí)行數(shù)據(jù)操作時(shí),是不是在控制臺(tái)顯示SQL語(yǔ)句,true為顯示 --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <!--根據(jù)數(shù)據(jù)庫(kù)表得到類,根據(jù)類到表 --> <property name="hbm2ddl.auto">create</property> <!--對(duì)類的配置文件映射 --> <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/> <mapping resource="org/hibernate/tutorial/domain/Person.hbm.xml"/> </session-factory></hibernate-configuration>
這里暫時(shí)只做數(shù)據(jù)庫(kù)的連接配置Oracle的
<?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> <!-- Database connection settings --> <!-- 數(shù)據(jù)庫(kù)驅(qū)動(dòng) 不同的數(shù)據(jù)庫(kù)不一樣--> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <!-- 數(shù)據(jù)庫(kù)訪問url 不同的數(shù)據(jù)庫(kù)不一樣--> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> <!-- 數(shù)據(jù)庫(kù)連接用戶名 --> <property name="connection.username">accp</property> <!--數(shù)據(jù)庫(kù)連接用戶名的密碼 --> <property name="connection.password">accp</property> </session-factory></hibernate-configuration>3.2、創(chuàng)建持久化類和映射文件
也就是創(chuàng)建實(shí)體類的配置文件如:Login.hbm.xml(Login為類名),并在hibernate.cfg.xml文件下方</session-factory>前面中添加映射文件路徑
1、在數(shù)據(jù)庫(kù)中創(chuàng)建一張表
create table login( username varchar2(20) primary key, password varchar2(20));
2、創(chuàng)建Login實(shí)體類
package com.pb.entity;/* * 登錄實(shí)體類 */public class Login { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }3、在實(shí)體類的同一個(gè)包下創(chuàng)建實(shí)體類的配置文件
<?xml version='1.0' encoding='utf-8'?> <!-- 這里與hibernate.cfg.xml配置文件不一樣注意 --><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- 這里與hibernate.cfg.xml配置文件不一樣注意 --><hibernate-mapping> <!--類名和數(shù)據(jù)庫(kù)中的表名相對(duì)應(yīng) 哪個(gè)用戶 --> <class name="com.pb.entity.Login" table="LOGIN" schema="accp"> <!-- id代表主鍵 column列表 type代表數(shù)據(jù)類型--> <!-- 類中的屬性 --> <id name="username" type="java.lang.String"> <!-- 表中哪一個(gè)字段或者是列名 --> <column name="USERNAME" length="20" /> <!--生成的方式 assigned代表由外部外部程序負(fù)責(zé)生成,在 save() 之前必須指定一個(gè)--> <!-- native由hibernate根據(jù)使用的數(shù)據(jù)庫(kù)自行判斷采用identity、hilo、sequence其中一種作為主鍵生成方式,靈活性很強(qiáng)。如果能支持identity則使用identity,如果支持sequence則使用sequence。--> <generator class="assigned" /> </id> <!-- 密碼段設(shè)置 --> <!--類中的名字和數(shù)據(jù)類型 --> <property name="password" type="java.lang.String"> <!-- 表中的字段名,長(zhǎng)度可心不要,是不為空true為不能為空,false是可以為空 --> <column name="PASSWORD" length="20" not-null="true"/> </property> <!--如果還有其它的屬性,設(shè)置方式與password一樣設(shè)置 --> </class></hibernate-mapping>
在src下的配置文件中添加映射
<?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> <!-- Database connection settings --> <!-- 數(shù)據(jù)庫(kù)驅(qū)動(dòng) 不同的數(shù)據(jù)庫(kù)不一樣--> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <!-- 數(shù)據(jù)庫(kù)訪問url 不同的數(shù)據(jù)庫(kù)不一樣--> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> <!-- 數(shù)據(jù)庫(kù)連接用戶名 --> <property name="connection.username">accp</property> <!--數(shù)據(jù)庫(kù)連接用戶名的密碼 --> <property name="connection.password">accp</property> <!--為實(shí)體類配置文件添加映射 --> <mapping resource="com/pb/entity/Login.hbm.xml"/> </session-factory></hibernate-configuration>3.3、創(chuàng)建Hibernate連接工具類
Hibernater主要接口和類:
Configuration
SessionFactory:DriverManager
Session:Connection
Transaction
Query:Statement和PreparedStatement
在下載的包中有提供好的一個(gè)比較簡(jiǎn)單的工具類
package com.pb.until;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { // Create the SessionFactory from hibernate.cfg.xml sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; }}這個(gè)比較,也可以增加一功能
相比較MyEclipse提供的一個(gè)比較完美
package com.pb.until;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.cfg.Configuration;/** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; }}
根據(jù)需要選擇
四、Hibernate的持久化操作的步驟4.1、讀取并散板配置文件Configuration config=new Configuration().configure();4.2、讀取并解析映射信息,創(chuàng)建SessionFactory
SessionFactory factory=config.buildSessionFactory();4.3、打開session
Session session=factory.openSessin();4.4、開始一個(gè)事務(wù)(增、刪、改操作必須,查詢操作可選)
Transaction tran=session.beginTransaction();4.5、操作化操作
session.save(對(duì)象);session.update(對(duì)象);session.delete(對(duì)象);session.get(主鍵之類的);4.6、提交事務(wù)
tran.commit();4.7、關(guān)閉session
session.close();五、Hibernate使用
實(shí)現(xiàn)增、刪、改、查的類
package com.pb.LoginDao;import java.util.List;import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;import com.pb.entity.Login;import com.pb.until.HibernateSessionFactory;import com.pb.until.HibernateUtil;public class LoginDao { /* * 增加 */ public void save(Login login) { // 得到Session Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tran = null; // 也可以 // Session session=new // Configuration().configure().buildSessionFactory().openSession(); try { // 打開事務(wù) tran = session.beginTransaction(); // 執(zhí)行數(shù)據(jù)添加 session.save(login); // 提交事務(wù) tran.commit(); System.out.println("用戶信息添加成功"); } catch (HibernateException e) { // 事務(wù)回滾 tran.rollback(); e.printStackTrace(); System.out.println("用戶信息添加失敗"); } finally { // 關(guān)閉session session.close(); } } /* * 修改根據(jù)用戶名 */ public void update(Login login) { // 得到Session Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tran = null; // 也可以 // Session session=new // Configuration().configure().buildSessionFactory().openSession(); try { // 打開事務(wù) tran = session.beginTransaction(); // 執(zhí)行數(shù)據(jù)添加 session.update(login); // 提交事務(wù) tran.commit(); System.out.println("用戶信息修改成功"); } catch (HibernateException e) { // 事務(wù)回滾 tran.rollback(); e.printStackTrace(); System.out.println("用戶信息修改失敗"); } finally { // 關(guān)閉session session.close(); } } /* * 修改根據(jù)用戶名修改密碼 */ public void delte(Login login) { // 得到Session Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tran = null; // 也可以 // Session session=new // Configuration().configure().buildSessionFactory().openSession(); try { // 打開事務(wù) tran = session.beginTransaction(); // 執(zhí)行數(shù)據(jù)添加 session.delete(login); // 提交事務(wù) tran.commit(); System.out.println("用戶信息刪除成功"); } catch (HibernateException e) { // 事務(wù)回滾 tran.rollback(); e.printStackTrace(); System.out.println("用戶信息刪除失敗"); } finally { // 關(guān)閉session session.close(); } } /* * 查詢一查詢?nèi)坑脩? */ public List<Login> QueryALL() { // 使用myeclipse提供的工具類來得到session Session session = HibernateSessionFactory.getSession(); // 建立查詢 Query query = session.createQuery("from Login"); // 查詢重到List集合 List<Login> list = query.list(); // 關(guān)閉session session.close(); // 返回結(jié)果集合 return list; } /* * 查詢二 查詢指定的用戶名的 */ public Login QueryByName(String username) { // 使用myeclipse提供的工具類來得到session Session session = HibernateSessionFactory.getSession(); // 建立查詢 Query query = session.createQuery("from Login l where l.username=?"); // 占位 query.setString(0, username); // 查詢返回唯一 Login login = (Login) query.uniqueResult(); // 關(guān)閉session session.close(); // 返回結(jié)果集合 return login; } /* * 查詢?nèi):樵? */ public List<Login> QueryLikeName(String username) { // 使用myeclipse提供的工具類來得到session Session session = HibernateSessionFactory.getSession(); // 建立查詢 Query query = session .createQuery("from Login l where l.username like ?"); // 占位 query.setString(0, "%" + username + "%"); // 查詢重到List集合 List<Login> list = query.list(); // 關(guān)閉session session.close(); // 返回結(jié)果集合 return list; }}測(cè)試類:
package com.pb.test;import java.util.List;import com.pb.LoginDao.LoginDao;import com.pb.entity.Login;public class Test { public static void main(String[] args) { //聲明LoginDao對(duì)象 LoginDao loginDao=new LoginDao();//聲明對(duì)象并賦初始值 Login login=new Login(); login.setUsername("Jack"); login.setPassword("blue"); //執(zhí)行添加 loginDao.save(login); //執(zhí)行修改 login.setUsername("Jack"); login.setPassword("while"); loginDao.update(login); //執(zhí)行刪除 loginDao.delte(login); System.out.println("=========查詢?nèi)?======="); //查詢?nèi)? List<Login> list=loginDao.QueryALL(); for (Login log : list) { System.out.println("用戶名:"+log.getUsername()+" 密碼:"+log.getPassword()); } System.out.println("=========精確查詢========"); //查詢一個(gè)用戶 Login lg=loginDao.QueryByName("ffff"); if(lg!=null){ System.out.println("用戶名:"+lg.getUsername()+" 密碼:"+lg.getPassword()); }else{ System.out.println("沒有此用戶"); } System.out.println("=========模糊查詢========"); //模糊查詢 List<Login> likelist=loginDao.QueryLikeName("t"); for (Login lo : likelist) { System.out.println("用戶名:"+ lo.getUsername()+" 密碼:"+ lo.getPassword()); } }}新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注