一,Hibernate框架介绍  

  没有Hibernate之前,使用jdbc来连接数据库时,需要反射加载驱动,再获取连接

  在连接上获取sql承载块,传入sql语句执行,获取结果集,解析结果

  Hibernate框架,核心对象就是使用连接字串获取的session,自动完成对象关系映射,不需要手动来解析对象

二,程序实例

1.新建web项目,导入框架包

2.编写  User.java

  1. package com.zhaolong.bean;
  2.  
  3. import java.sql.Date;
  4.  
  5. public class User {
  6.  
  7. private Integer id;
  8. private String name;
  9. private String gender;
  10. private String age;
  11. private Date birthday;
  12. private String phone;
  13. private String address;
  14. private String card;
  15. private String email;
  16. private String wechat;
  17. public Integer getId() {
  18. return id;
  19. }
  20. public void setId(Integer id) {
  21. this.id = id;
  22. }
  23. public String getName() {
  24. return name;
  25. }
  26. public void setName(String name) {
  27. this.name = name;
  28. }
  29. public String getGender() {
  30. return gender;
  31. }
  32. public void setGender(String gender) {
  33. this.gender = gender;
  34. }
  35.  
  36. public String getAge() {
  37. return age;
  38. }
  39. public void setAge(String age) {
  40. this.age = age;
  41. }
  42. public Date getBirthday() {
  43. return birthday;
  44. }
  45. public void setBirthday(Date birthday) {
  46. this.birthday = birthday;
  47. }
  48. public String getPhone() {
  49. return phone;
  50. }
  51. public void setPhone(String phone) {
  52. this.phone = phone;
  53. }
  54. public String getAddress() {
  55. return address;
  56. }
  57. public void setAddress(String address) {
  58. this.address = address;
  59. }
  60. public String getCard() {
  61. return card;
  62. }
  63. public void setCard(String card) {
  64. this.card = card;
  65. }
  66. public String getEmail() {
  67. return email;
  68. }
  69. public void setEmail(String email) {
  70. this.email = email;
  71. }
  72. public String getWechat() {
  73. return wechat;
  74. }
  75. public void setWechat(String wechat) {
  76. this.wechat = wechat;
  77. }
  78.  
  79. public User(String name, String gender, String age, Date birthday,
  80. String phone, String address, String card, String email,
  81. String wechat) {
  82. super();
  83. this.name = name;
  84. this.gender = gender;
  85. this.age = age;
  86. this.birthday = birthday;
  87. this.phone = phone;
  88. this.address = address;
  89. this.card = card;
  90. this.email = email;
  91. this.wechat = wechat;
  92. }
  93. public User() {
  94. super();
  95. // TODO Auto-generated constructor stub
  96. }
  97. @Override
  98. public String toString() {
  99. return "User [id=" + id + ", name=" + name + ", gender=" + gender
  100. + ", age=" + age + ", birthday=" + birthday + ", phone="
  101. + phone + ", address=" + address + ", card=" + card
  102. + ", email=" + email + ", wechat=" + wechat + "]";
  103. }
  104.  
  105. }

3.编写实体类的映射文件  User.hbm.xml

  1. <?xml version="1.0"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  5. <hibernate-mapping>
  6. <class name="com.zhaolong.bean.User" table="HUQB_USER">
  7. <id name="id">
  8. <generator class="native"/>
  9. </id>
  10. <property name="name"/>
  11. <property name="gender"/>
  12. <property name="age"/>
  13. <property name="birthday"/>
  14. <property name="phone"/>
  15. <property name="address"/>
  16. <property name="card"/>
  17. <property name="email"/>
  18. <property name="wechat"/>
  19. </class>
  20.  
  21. <!-- 创建命名查询 -->
  22.  
  23. <query name="findAllUsers">
  24. <![CDATA[
  25. from User
  26. ]]>
  27. </query>
  28.  
  29. <!-- 查询年龄大于30的所有人 -->
  30. <query name="findUsersByAge">
  31. <![CDATA[
  32. from User u where u.age>:age
  33. ]]>
  34. </query>
  35.  
  36. <!-- 本地命名查询 -->
  37. <sql-query name="findAllUsersLocal">
  38. <!-- 通过return 标签指定返回结果的映射 -->
  39. <return class="com.zhaolong.bean.User"/>
  40. <![CDATA[
  41. select * from huqb_user
  42. ]]>
  43. </sql-query>
  44.  
  45. </hibernate-mapping>

4.编写连接字串配置文件  hibernate.cfg.xml

  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. <!-- Generated by MyEclipse Hibernate Tools. -->
  6. <hibernate-configuration>
  7.  
  8. <session-factory>
  9. <!--<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  10. <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
  11. <property name="connection.username">root</property>
  12. <property name="connection.password">java</property>
  13. <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  14. -->
  15. <!-- 配置方言 -->
  16. <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
  17. <!-- 配置连接地址 -->
  18. <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
  19. <!-- 配置用户名 -->
  20. <property name="connection.username">mart</property>
  21. <!-- 配置密码 -->
  22. <property name="connection.password">java</property>
  23. <!-- 配置驱动 -->
  24. <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  25.  
  26. <property name="show_sql">true</property>
  27. <!-- 对sql语句进行格式化 -->
  28. <property name="format_sql">true</property>
  29. <property name="hbm2ddl.auto">update</property>
  30. <mapping resource="com/zhaolong/bean/User.hbm.xml"/>
  31. </session-factory>
  32.  
  33. </hibernate-configuration>

5.根据cfg文件获取操作数据库的session,可以自己编写,也可以选择自动生成  HibernateSessionFactory

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

6.编写数据测试类  AddTest

  1. package com.zhaolong.test;
  2.  
  3. import java.sql.Date;
  4.  
  5. import org.hibernate.Session;
  6. import org.hibernate.Transaction;
  7.  
  8. import com.zhaolong.bean.User;
  9. import com.zhaolong.util.HibernateSessionFactory;
  10.  
  11. public class AddTest {
  12.  
  13. public static void main(String[] args) {
  14.  
  15. Session session = HibernateSessionFactory.getSession();
  16.  
  17. Transaction tx = session.beginTransaction();
  18.  
  19. User u1=new User("诸葛亮", "男", "35",
  20. new Date(System.currentTimeMillis())
  21. , "110", "蜀国", "1234567890", "zgl@huqb.com", "zhugeliang01");
  22. User u2=new User("黄月英", "女", "33",
  23. new Date(System.currentTimeMillis()+100000000)
  24. , "119", "蜀国", "0987654321", "hyy@huqb.com", "huangyueying01");
  25.  
  26. User u3=new User("曹丕", "男", "45",
  27. new Date(System.currentTimeMillis())
  28. , "120", "魏国", "1234567890", "cp@huqb.com", "caopi");
  29. User u4=new User("甄姬", "女", "33",
  30. new Date(System.currentTimeMillis()+100000000)
  31. , "114", "魏国", "0987654321", "zj@huqb.com", "zhenji01");
  32. User u5=new User("荀彧", "男", "45",
  33. new Date(System.currentTimeMillis())
  34. , "120", "魏国", "1234567890", "cp@huqb.com", "caopi");
  35. User u6=new User("曹操", "男", "33",
  36. new Date(System.currentTimeMillis()+100000000)
  37. , "114", "魏国", "0987654321", "zj@huqb.com", "zhenji01");
  38.  
  39. session.save(u1);
  40. session.save(u2);
  41. session.save(u3);
  42. session.save(u4);
  43. session.save(u5);
  44. session.save(u6);
  45. tx.commit();
  46.  
  47. session.close();
  48.  
  49. }
  50. }

Hibernate框架用法的更多相关文章

  1. 1.Hibernate框架核心组件 (转自冯岩)

    Hibernate框架核心组件 在Hibernate框架简述中,演示了一个简单的Hibernate应用,但并没有深入说明其中程序,在这篇中将比较详细的介绍一下Hibernate的核心组件.首先最关键一 ...

  2. 粗浅看Struts2和Hibernate框架

    ----------------------------------------------------------------------------------------------[版权申明: ...

  3. Hibernate框架_搭建第一个Hibernate框架

    一.eclipse搭建 A.创建动态web项目 New-->Dynamic web project(web project) B.导入jar包 1.数据库驱动包 2.hibernate开发必须j ...

  4. Hibernate框架之Criteria查询 和注解(重点☆☆☆☆☆,难点☆☆☆)

    写好一篇博客,不是容易的事.原因是:你要给自己以后看的时候,还能看懂,最重要的是当别人看到你的博客文章的时候,也一样很清楚的明白你自己写的东西.其实这也是一种成就感!! 对于每一个知识点,要有必要的解 ...

  5. Hibernate 系列 01 - 框架技术 (介绍Hibernate框架的发展由来)

    引导目录: Hibernate 系列教程 目录 本篇导航: 为什么学习框架技术 框架的概念 主流框架的介绍 1.为什么学习框架技术 如何制作一份看上去具有专业水准的PPT文档呢?一个简单的方法就是使用 ...

  6. 2.0、Hibernate框架的简单搭建

    一.Hibernate:是一个开放源代码的对象关系映射框架,对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句 ...

  7. 【Hibernate框架】对象的三种持久化状态

    一.综述 hibernate中的对象有三种状态,分别是TransientObjects(瞬时对象).PersistentObjects(持久化对象)和DetachedObjects(托管对象也叫做离线 ...

  8. hibernate框架int和Integer类型区别

    hibernate 框架在定义实体时,int类型最好定义为Inttger类型,因为在注入时int是值类型不允许为空.

  9. SSH(Struts2+Spring+Hibernate)框架搭建流程<注解的方式创建Bean>

    此篇讲的是MyEclipse9工具提供的支持搭建自加包有代码也是相同:用户登录与注册的例子,表字段只有name,password. SSH,xml方式搭建文章链接地址:http://www.cnblo ...

随机推荐

  1. Java 使用poi导入excel,结合xml文件进行数据验证的例子(增加了jar包)

    ava 使用poi导入excel,结合xml文件进行数据验证的例子(增加了jar包) 假设现在要做一个通用的导入方法: 要求: 1.xml的只定义数据库表中的column字段,字段类型,是否非空等条件 ...

  2. 学习python第二天数据库day1

    day01: 关键字:desc 作用:查看表结构(字段名,数据类型&长度) 举例: desc python1808_laoguo; 追加数据到表中:(新增操作) 关键字:insert into ...

  3. iOS的图片:解码(CPU)与内存(缓存)

    图片的数据:资源数据(地址).原始数据(Data).显示数据(解码后的数据) 解压图片 - PNG或者JPEG压缩之后的图片文件会比同质量的位图小得多.但是在图片绘制到屏幕上之前,必须把它扩展成完整的 ...

  4. UVA10125 Sumsets

    嘟嘟嘟 很简单的折半搜索. 把式子变一下型,得到\(a + b = d - c\). 然后枚举\(a, b\),存到\(map\)里,再枚举\(c, d\)就好了. \(map\)以\(a,b\)两数 ...

  5. Centos7 KDE 桌面Konsole 光标错位解决方法

    在使用linux 系统,桌面为KDE 时,在使用Konsole 时,光标的位置是错位的. 如下图效果  解决办法 用命令进入/home/cfox/.kde/share/apps/konsole 修改S ...

  6. [LuoguP2158][SDOI2008]仪仗队

    [LuoguP2158][SDOI2008]仪仗队(Link) 现在你有一个\(N \times N\)的矩阵,求你站在\((1,1)\)点能看到的点的总数. 很简洁的题面. 这道题看起来很难,但是稍 ...

  7. Mac下python3配置Sklearn

    服务器要有Python 环境 ,也要有Python运行的依赖包,Java与Python使用Process进程进行通讯. 安装homebrew /usr/bin/ruby -e "$(curl ...

  8. Struts2+AJAX+JQuery 实现用户登入与注册功能

    要求:必备知识:JAVA/Struts2,JS/JQuery,HTML/CSS基础语法:开发环境:MyEclipse 10 关于UI部分请查看下列链接,有详细制作步骤: 利用:before和:afte ...

  9. SQL Server系统表sysobjects

    sysobjects 表  在数据库内创建的每个对象(约束.默认值.日志.规则.存储过程等)在表中占一行.只有在 tempdb 内,每个临时对象才在该表中占一行. sysobjects 表结构: 列名 ...

  10. typeof 和 instanceof 区别

    typeof操作符返回一个字符串,表示未经计算的操作数的类型. 可能返回值有:"undefined"."object"."boolean". ...