加载中...

Hibernate框架简介(二)基本使用增、删、改、查


一、Hibernate框架简介

Hibernate是一个优秀的Java持久化层解决方案,是当今主流的对象-关系映射(ORM,ObjectRelationalMapping)工具

1.1、理解持久化

  • 瞬时状态:在程序运行的时候,有些程序数据是保存在内存中,当程序退出后,这些数据就不复存在了,所以称这些数据的状态为瞬时状态
  • 持久状态:在使用一此软件的时候,有些数据,在程序退出后,还以文件等形式保存在硬盘或者数据库中,称这些数据的状态是持久状态
  • 持久化:持久化就是将程序中的数据在瞬时状态和持久状态之间转换的机制。(如:JDBC)

1.2、对象-关系映射(ORM)

Java是一种面象对象的设计语言。在程序运行时的数据是以对象形式存在内存中,而保存数据时,又要以对象的形式存在关系型数据库中。

ORM简单讲:就是能在对象和关系型数据库两者之间进行数据转换的机制。Hibernate就是这样一个中间的解决方案。关系如下图

 

1.3、ORM框架综述

ORM:对象关系映射(Object Relation Mapping)

Hibernate框架:能够实现ORM框架

Hibernate是一个优秀的Java持久化层解决方案,是当今主流的对象-关系映射(ORM,ObjectRelationalMap

Hibernate框架对JDBC时行和封装,简化了数据访问层。可应用在任何使用JDBC的场合如:Servlet、JSP的WEB应用,JAVA客户端等。

 二、Hibernate下载

官网:http://sourceforge.net/projects/hibernate/files/hibernate3/

这里下载的是3.3.2GA,

解压后,将根目录下的hibernate3.jar和将lib目录下全部的jar导入项目中

同时将数据库驱动也导入这里使用Oracle 11g

其中加入了一些其它的jar包如:JSTL包

 

当然也可以用MyEclipse完全集成,不用下载

三、Hibernate配置

 3.1、创建hibernate.cfg.xml文件.

这是配置文件默认名.一般放在src目录下:作用指定数据库连接的信息及映射文件路径

获取配置文件进行修改。当然如果记得了就全写也可以。在下载的Hibernate解压目录下就有配置文件模板

hibernate-distribution-3.3.2.GA-dist\hibernate-distribution-3.3.2.GA\project\tutorials\web\src\main\resources此目录下就有,将其复制到src目录下进行修改

  1. <?xml version='1.0' encoding='utf-8'?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  5.  
  6. <hibernate-configuration>
  7.  
  8. <session-factory>
  9.  
  10. <!-- Database connection settings -->
  11. <!-- 数据库驱动 不同的数据库不一样-->
  12. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  13. <!-- 数据库访问url 不同的数据库不一样-->
  14. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
  15. <!-- 数据库连接用户名 -->
  16. <property name="connection.username">sa</property>
  17. <!--数据库连接用户名的密码 -->
  18. <property name="connection.password"></property>
  19.  
  20. <!-- JDBC connection pool (use the built-in) -->
  21. <!--数据库连接池默认连接数量 -->
  22. <property name="connection.pool_size">2</property>
  23.  
  24. <!-- SQL dialect -->
  25. <!--方言,不同的数据不同的版都有所不同 -->
  26. <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
  27.  
  28. <!-- Enable Hibernate's current session context -->
  29. <!-- Session设置 -->
  30. <property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>
  31.  
  32. <!-- Disable the second-level cache -->
  33. <!--二级缓存 -->
  34. <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
  35.  
  36. <!-- Echo all executed SQL to stdout -->
  37. <!-- 在执行数据操作时,是不是在控制台显示SQL语句,true为显示 -->
  38. <property name="show_sql">true</property>
  39.  
  40. <!-- Drop and re-create the database schema on startup -->
  41. <!--根据数据库表得到类,根据类到表 -->
  42. <property name="hbm2ddl.auto">create</property>
  43. <!--对类的配置文件映射 -->
  44. <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>
  45. <mapping resource="org/hibernate/tutorial/domain/Person.hbm.xml"/>
  46.  
  47. </session-factory>
  48.  
  49. </hibernate-configuration>

这里暂时只做数据库的连接配置Oracle的

  1. <?xml version='1.0' encoding='utf-8'?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  5.  
  6. <hibernate-configuration>
  7.  
  8. <session-factory>
  9.  
  10. <!-- Database connection settings -->
  11. <!-- 数据库驱动 不同的数据库不一样-->
  12. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  13. <!-- 数据库访问url 不同的数据库不一样-->
  14. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
  15. <!-- 数据库连接用户名 -->
  16. <property name="connection.username">accp</property>
  17. <!--数据库连接用户名的密码 -->
  18. <property name="connection.password">accp</property>
  19.  
  20. </session-factory>
  21.  
  22. </hibernate-configuration>

 

3.2、创建持久化类和映射文件

也就是创建实体类的配置文件如:Login.hbm.xml(Login为类名),并在hibernate.cfg.xml文件下方</session-factory>前面中添加映射文件路径

1、在数据库中创建一张表

  1. create table login
  2. (
  3. username varchar2(20) primary key,
  4. password varchar2(20)
  5. );

2、创建Login实体类

  1. package com.pb.entity;
  2. /*
  3. * 登录实体类
  4. */
  5. public class Login {
  6. private String username;
  7. private String password;
  8. public String getUsername() {
  9. return username;
  10. }
  11. public void setUsername(String username) {
  12. this.username = username;
  13. }
  14. public String getPassword() {
  15. return password;
  16. }
  17. public void setPassword(String password) {
  18. this.password = password;
  19. }
  20. }

3、在实体类的同一个包下创建实体类的配置文件

  1. <?xml version='1.0' encoding='utf-8'?>
  2. <!-- 这里与hibernate.cfg.xml配置文件不一样注意 -->
  3. <!DOCTYPE hibernate-mapping PUBLIC
  4. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  5. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- 这里与hibernate.cfg.xml配置文件不一样注意 -->
  6.  
  7.  
  8. <hibernate-mapping>
  9. <!--类名和数据库中的表名相对应 哪个用户 -->
  10. <class name="com.pb.entity.Login" table="LOGIN" schema="accp">
  11. <!-- id代表主键 column列表 type代表数据类型-->
  12. <!-- 类中的属性 -->
  13. <id name="username" type="java.lang.String">
  14. <!-- 表中哪一个字段或者是列名 -->
  15. <column name="USERNAME" length="20" />
  16. <!--生成的方式 assigned代表由外部外部程序负责生成,在 save() 之前必须指定一个-->
  17. <!-- native由hibernate根据使用的数据库自行判断采用identity、hilo、sequence其中一种作为主键生成方式,灵活性很强。如果能支持identity则使用identity,如果支持sequence则使用sequence。-->
  18. <generator class="assigned" />
  19. </id>
  20. <!-- 密码段设置 -->
  21. <!--类中的名字和数据类型 -->
  22. <property name="password" type="java.lang.String">
  23. <!-- 表中的字段名,长度可心不要,是不为空true为不能为空,false是可以为空 -->
  24. <column name="PASSWORD" length="20" not-null="true"/>
  25. </property>
  26. <!--如果还有其它的属性,设置方式与password一样设置 -->
  27. </class>
  28. </hibernate-mapping>

 

在src下的配置文件中添加映射

  1. <?xml version='1.0' encoding='utf-8'?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  5.  
  6. <hibernate-configuration>
  7.  
  8. <session-factory>
  9.  
  10. <!-- Database connection settings -->
  11. <!-- 数据库驱动 不同的数据库不一样-->
  12. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  13. <!-- 数据库访问url 不同的数据库不一样-->
  14. <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
  15. <!-- 数据库连接用户名 -->
  16. <property name="connection.username">accp</property>
  17. <!--数据库连接用户名的密码 -->
  18. <property name="connection.password">accp</property>
  19. <!--为实体类配置文件添加映射 -->
  20. <mapping resource="com/pb/entity/Login.hbm.xml"/>
  21. </session-factory>
  22.  
  23. </hibernate-configuration>

3.3、创建Hibernate连接工具类

Hibernater主要接口和类:

Configuration

SessionFactory:DriverManager

Session:Connection

Transaction

Query:Statement和PreparedStatement

在下载的包中有提供好的一个比较简单的工具类

  1. package com.pb.until;
  2. import org.hibernate.SessionFactory;
  3. import org.hibernate.cfg.Configuration;
  4. public class HibernateUtil {
  5. private static final SessionFactory sessionFactory;
  6. static {
  7. try {
  8. // Create the SessionFactory from hibernate.cfg.xml
  9. sessionFactory = new Configuration().configure().buildSessionFactory();
  10. } catch (Throwable ex) {
  11. // Make sure you log the exception, as it might be swallowed
  12. System.err.println("Initial SessionFactory creation failed." + ex);
  13. throw new ExceptionInInitializerError(ex);
  14. }
  15. }
  16. public static SessionFactory getSessionFactory() {
  17. return sessionFactory;
  18. }
  19. }

这个比较,也可以增加一功能

相比较MyEclipse提供的一个比较完美

  1. package com.pb.until;
  2. import org.hibernate.HibernateException;
  3. import org.hibernate.Session;
  4. import org.hibernate.cfg.Configuration;
  5. /**
  6. * Configures and provides access to Hibernate sessions, tied to the
  7. * current thread of execution. Follows the Thread Local Session
  8. * pattern, see {@link http://hibernate.org/42.html }.
  9. */
  10. public class HibernateSessionFactory {
  11. /**
  12. * Location of hibernate.cfg.xml file.
  13. * Location should be on the classpath as Hibernate uses
  14. * #resourceAsStream style lookup for its configuration file.
  15. * The default classpath location of the hibernate config file is
  16. * in the default package. Use #setConfigFile() to update
  17. * the location of the configuration file for the current session.
  18. */
  19. private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
  20. private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
  21. private static Configuration configuration = new Configuration();
  22. private static org.hibernate.SessionFactory sessionFactory;
  23. private static String configFile = CONFIG_FILE_LOCATION;
  24. static {
  25. try {
  26. configuration.configure(configFile);
  27. sessionFactory = configuration.buildSessionFactory();
  28. } catch (Exception e) {
  29. System.err
  30. .println("%%%% Error Creating SessionFactory %%%%");
  31. e.printStackTrace();
  32. }
  33. }
  34. private HibernateSessionFactory() {
  35. }
  36. /**
  37. * Returns the ThreadLocal Session instance. Lazy initialize
  38. * the <code>SessionFactory</code> if needed.
  39. *
  40. * @return Session
  41. * @throws HibernateException
  42. */
  43. public static Session getSession() throws HibernateException {
  44. Session session = (Session) threadLocal.get();
  45. if (session == null || !session.isOpen()) {
  46. if (sessionFactory == null) {
  47. rebuildSessionFactory();
  48. }
  49. session = (sessionFactory != null) ? sessionFactory.openSession()
  50. : null;
  51. threadLocal.set(session);
  52. }
  53. return session;
  54. }
  55. /**
  56. * Rebuild hibernate session factory
  57. *
  58. */
  59. public static void rebuildSessionFactory() {
  60. try {
  61. configuration.configure(configFile);
  62. sessionFactory = configuration.buildSessionFactory();
  63. } catch (Exception e) {
  64. System.err
  65. .println("%%%% Error Creating SessionFactory %%%%");
  66. e.printStackTrace();
  67. }
  68. }
  69. /**
  70. * Close the single hibernate session instance.
  71. *
  72. * @throws HibernateException
  73. */
  74. public static void closeSession() throws HibernateException {
  75. Session session = (Session) threadLocal.get();
  76. threadLocal.set(null);
  77. if (session != null) {
  78. session.close();
  79. }
  80. }
  81. /**
  82. * return session factory
  83. *
  84. */
  85. public static org.hibernate.SessionFactory getSessionFactory() {
  86. return sessionFactory;
  87. }
  88. /**
  89. * return session factory
  90. *
  91. * session factory will be rebuilded in the next call
  92. */
  93. public static void setConfigFile(String configFile) {
  94. HibernateSessionFactory.configFile = configFile;
  95. sessionFactory = null;
  96. }
  97. /**
  98. * return hibernate configuration
  99. *
  100. */
  101. public static Configuration getConfiguration() {
  102. return configuration;
  103. }
  104. }

根据需要选择

四、Hibernate的持久化操作的步骤

4.1、读取并散板配置文件

  1. Configuration config=new Configuration().configure();

4.2、读取并解析映射信息,创建SessionFactory

  1. SessionFactory factory=config.buildSessionFactory();

4.3、打开session

  1. Session session=factory.openSessin();

4.4、开始一个事务(增、删、改操作必须,查询操作可选)

  1. Transaction tran=session.beginTransaction();

4.5、操作化操作

  1. session.save(对象);
  2. session.update(对象);
  3. session.delete(对象);
  4. session.get(主键之类的);

4.6、提交事务

  1. tran.commit();

4.7、关闭session

  1. session.close();

五、Hibernate使用

 实现增、删、改、查的类

  1. package com.pb.LoginDao;
  2. import java.util.List;
  3. import org.hibernate.HibernateException;
  4. import org.hibernate.Query;
  5. import org.hibernate.Session;
  6. import org.hibernate.Transaction;
  7. import com.pb.entity.Login;
  8. import com.pb.until.HibernateSessionFactory;
  9. import com.pb.until.HibernateUtil;
  10. public class LoginDao {
  11. /*
  12. * 增加
  13. */
  14. public void save(Login login) {
  15. // 得到Session
  16. Session session = HibernateUtil.getSessionFactory().openSession();
  17. Transaction tran = null;
  18. // 也可以
  19. // Session session=new
  20. // Configuration().configure().buildSessionFactory().openSession();
  21. try {
  22. // 打开事务
  23. tran = session.beginTransaction();
  24. // 执行数据添加
  25. session.save(login);
  26. // 提交事务
  27. tran.commit();
  28. System.out.println("用户信息添加成功");
  29. } catch (HibernateException e) {
  30. // 事务回滚
  31. tran.rollback();
  32. e.printStackTrace();
  33. System.out.println("用户信息添加失败");
  34. } finally {
  35. // 关闭session
  36. session.close();
  37. }
  38. }
  39. /*
  40. * 修改根据用户名
  41. */
  42. public void update(Login login) {
  43. // 得到Session
  44. Session session = HibernateUtil.getSessionFactory().openSession();
  45. Transaction tran = null;
  46. // 也可以
  47. // Session session=new
  48. // Configuration().configure().buildSessionFactory().openSession();
  49. try {
  50. // 打开事务
  51. tran = session.beginTransaction();
  52. // 执行数据添加
  53. session.update(login);
  54. // 提交事务
  55. tran.commit();
  56. System.out.println("用户信息修改成功");
  57. } catch (HibernateException e) {
  58. // 事务回滚
  59. tran.rollback();
  60. e.printStackTrace();
  61. System.out.println("用户信息修改失败");
  62. } finally {
  63. // 关闭session
  64. session.close();
  65. }
  66. }
  67. /*
  68. * 修改根据用户名修改密码
  69. */
  70. public void delte(Login login) {
  71. // 得到Session
  72. Session session = HibernateUtil.getSessionFactory().openSession();
  73. Transaction tran = null;
  74. // 也可以
  75. // Session session=new
  76. // Configuration().configure().buildSessionFactory().openSession();
  77. try {
  78. // 打开事务
  79. tran = session.beginTransaction();
  80. // 执行数据添加
  81. session.delete(login);
  82. // 提交事务
  83. tran.commit();
  84. System.out.println("用户信息删除成功");
  85. } catch (HibernateException e) {
  86. // 事务回滚
  87. tran.rollback();
  88. e.printStackTrace();
  89. System.out.println("用户信息删除失败");
  90. } finally {
  91. // 关闭session
  92. session.close();
  93. }
  94. }
  95. /*
  96. * 查询一查询全部用户
  97. */
  98. public List<Login> QueryALL() {
  99. // 使用myeclipse提供的工具类来得到session
  100. Session session = HibernateSessionFactory.getSession();
  101. // 建立查询
  102. Query query = session.createQuery("from Login");
  103. // 查询重到List集合
  104. List<Login> list = query.list();
  105. // 关闭session
  106. session.close();
  107. // 返回结果集合
  108. return list;
  109. }
  110. /*
  111. * 查询二 查询指定的用户名的
  112. */
  113. public Login QueryByName(String username) {
  114. // 使用myeclipse提供的工具类来得到session
  115. Session session = HibernateSessionFactory.getSession();
  116. // 建立查询
  117. Query query = session.createQuery("from Login l where l.username=?");
  118. // 占位
  119. query.setString(0, username);
  120. // 查询返回唯一
  121. Login login = (Login) query.uniqueResult();
  122. // 关闭session
  123. session.close();
  124. // 返回结果集合
  125. return login;
  126. }
  127. /*
  128. * 查询三,模糊查询
  129. */
  130. public List<Login> QueryLikeName(String username) {
  131. // 使用myeclipse提供的工具类来得到session
  132. Session session = HibernateSessionFactory.getSession();
  133. // 建立查询
  134. Query query = session
  135. .createQuery("from Login l where l.username like ?");
  136. // 占位
  137. query.setString(0, "%" + username + "%");
  138. // 查询重到List集合
  139. List<Login> list = query.list();
  140. // 关闭session
  141. session.close();
  142. // 返回结果集合
  143. return list;
  144. }
  145. }

测试类:

  1. package com.pb.test;
  2. import java.util.List;
  3. import com.pb.LoginDao.LoginDao;
  4. import com.pb.entity.Login;
  5. public class Test {
  6. public static void main(String[] args) {
  7. //声明LoginDao对象
  8. LoginDao loginDao=new LoginDao();
  9. //声明对象并赋初始值
  10. Login login=new Login();
  11. login.setUsername("Jack");
  12. login.setPassword("blue");
  13. //执行添加
  14. loginDao.save(login);
  15. //执行修改
  16. login.setUsername("Jack");
  17. login.setPassword("while");
  18. loginDao.update(login);
  19. //执行删除
  20. loginDao.delte(login);
  21. System.out.println("=========查询全部========");
  22. //查询全部
  23. List<Login> list=loginDao.QueryALL();
  24. for (Login log : list) {
  25. System.out.println("用户名:"+log.getUsername()+" 密码:"+log.getPassword());
  26. }
  27. System.out.println("=========精确查询========");
  28. //查询一个用户
  29. Login lg=loginDao.QueryByName("ffff");
  30. if(lg!=null){
  31. System.out.println("用户名:"+lg.getUsername()+" 密码:"+lg.getPassword());
  32. }else{
  33. System.out.println("没有此用户");
  34. }
  35. System.out.println("=========模糊查询========");
  36. //模糊查询
  37. List<Login> likelist=loginDao.QueryLikeName("t");
  38. for (Login lo : likelist) {
  39. System.out.println("用户名:"+ lo.getUsername()+" 密码:"+ lo.getPassword());
  40. }
  41. }
  42. }

 


还没有评论.