框架之 hibernate简单入门
来源:互联网 发布:星际战甲画质优化 编辑:程序博客网 时间:2024/04/29 21:47
hibernate框架的搭建
View Code
Hibernate框架的概述
1. Hibernate框架的概述 * Hibernate称为 * Hibernate是一个开放源代码的对象关系映射(ORM)框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 * Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用。 * Hibernate是轻量级JavaEE应用的持久层解决方案,是一个关系数据库ORM框架
2. 记住:Hibernate是一个持久层的ORM框架!!!
什么是ORM(对象关系映射)
1. ORM映射:Object Relational Mapping * O:面向对象领域的Object(JavaBean对象) * R:关系数据库领域的Relational(表的结构) * M:映射Mapping(XML的配置文件)2. 简单一句话:Hibernate使程序员通过操作对象的方式来操作数据库表记录
Hibernate优点
1. 优点 * Hibernate对JDBC访问数据库的代码做了封装,大大简化了数据访问层繁琐的重复性代码 * Hibernate是一个基于jdbc的主流持久化框架,是一个优秀的orm实现,它很大程度的简化了dao层编码工作 * Hibernate的性能非常好,因为它是一个轻量级框架。映射的灵活性很出色。它支持很多关系型数据库,从一对一到多对多的各种复杂关系
技术分析之Hibernate框架的快速入门
第一步:下载Hibernate5的运行环境
1. 下载相应的jar包等 * http://sourceforge.net/projects/hibernate/files/hibernate-orm/5.0.7.Final/hibernate-release-5.0.7.Final.zip/download 2. 解压后对目录结构有一定的了解
第二步:创建表结构
1. 建表语句如下 Create database hibernate_day01; Use hibernate_day01; CREATE TABLE `cst_customer` ( `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)', `cust_name` varchar(32) NOT NULL COMMENT '客户名称(公司名称)', `cust_user_id` bigint(32) DEFAULT NULL COMMENT '负责人id', `cust_create_id` bigint(32) DEFAULT NULL COMMENT '创建人id', `cust_source` varchar(32) DEFAULT NULL COMMENT '客户信息来源', `cust_industry` varchar(32) DEFAULT NULL COMMENT '客户所属行业', `cust_level` varchar(32) DEFAULT NULL COMMENT '客户级别', `cust_linkman` varchar(64) DEFAULT NULL COMMENT '联系人', `cust_phone` varchar(64) DEFAULT NULL COMMENT '固定电话', `cust_mobile` varchar(16) DEFAULT NULL COMMENT '移动电话', PRIMARY KEY (`cust_id`) ) ENGINE=InnoDB AUTO_INCREMENT=94 DEFAULT CHARSET=utf8;
第三步:搭建Hibernate的开发环境
1. 创建WEB工程,引入Hibernate开发所需要的jar包 * MySQL的驱动jar包 * Hibernate开发需要的jar包(资料/hibernate-release-5.0.7.Final/lib/required/所有jar包) * 日志jar包(资料/jar包/log4j/所有jar包)
第四步:编写JavaBean实体类
1. Customer类的代码如下: public class Customer { private Long cust_id; private String cust_name; private Long cust_user_id; private Long cust_create_id; private String cust_source; private String cust_industry; private String cust_level; private String cust_linkman; private String cust_phone; private String cust_mobile; // 省略get和set方法 }
第五步:创建类与表结构的映射
1. 在JavaBean所在的包下创建映射的配置文件 * 默认的命名规则为:实体类名.hbm.xml * 在xml配置文件中引入约束(引入的是hibernate3.0的dtd约束,不要引入4的约束) <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">2. 如果不能上网,编写配置文件是没有提示的,需要自己来配置 * 先复制http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd --> window --> preferences --> 搜索xml --> 选择xml catalog --> 点击add --> 现在URI --> 粘贴复制的地址 --> 选择location,选择本地的DTD的路径3. 编写映射的配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 6 <hibernate-mapping> 7 <class name="com.xujingyang.hibernate.Customer" table="cst_customer"> 8 <id name="cust_id" column="cust_id"> 9 <generator class="native"></generator>10 </id>11 12 <property name="cust_name" column="cust_name"></property>13 <property name="cust_user_id" column="cust_user_id"></property>14 <property name="cust_create_id" column="cust_create_id"></property>15 <property name="cust_source" column="cust_source"></property>16 <property name="cust_industry" column="cust_industry"></property>17 <property name="cust_level" column="cust_level"></property>18 <property name="cust_linkman" column="cust_linkman "></property>19 <property name="cust_phone" column="cust_phone"></property>20 <property name="cust_mobile" column="cust_mobile"></property>21 </class>22 </hibernate-mapping>
第六步:编写Hibernate核心的配置文件
1. 在src目录下,创建名称为hibernate.cfg.xml的配置文件2. 在XML中引入DTD约束 <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">3. 打开:资料/hibernate-release-5.0.7.Final/project/etc/hibernate.properties,可以查看具体的配置信息 * 必须配置的4大参数 #hibernate.connection.driver_class com.mysql.jdbc.Driver #hibernate.connection.url jdbc:mysql:///test #hibernate.connection.username gavin #hibernate.connection.password * 数据库的方言(必须配置的) #hibernate.dialect org.hibernate.dialect.MySQLDialect * 可选的配置 #hibernate.show_sql true #hibernate.format_sql true #hibernate.hbm2ddl.auto update * 引入映射配置文件(一定要注意,要引入映射文件,框架需要加载映射文件) * <mapping resource="com/xujingyang/domain/Customer.hbm.xml"/> 4. 具体的配置如下
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 6 <hibernate-configuration> 7 <session-factory> 8 <!-- * 必须配置的4大参数 9 #hibernate.connection.driver_class com.mysql.jdbc.Driver10 #hibernate.connection.url jdbc:mysql:///test11 #hibernate.connection.username gavin12 #hibernate.connection.password13 -->14 15 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>16 <property name="hibernate.connection.url">jdbc:mysql:///hibernate_day01</property>17 <property name="hibernate.connection.username">root</property>18 <property name="hibernate.connection.password">root</property>19 20 <!-- 21 * 数据库的方言(必须配置的)22 #hibernate.dialect org.hibernate.dialect.MySQLDialect23 -->24 <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>25 <!-- 26 * 可选的配置27 #hibernate.show_sql true28 #hibernate.format_sql true29 #hibernate.hbm2ddl.auto update30 -->31 32 <property name="hibernate.show_sql">true</property>33 <property name="hibernate.format_sql">true</property>34 <!-- <property name="hibernate.hbm2ddl.auto">update</property> -->35 36 <!-- 37 * 引入映射配置文件(一定要注意,要引入映射文件,框架需要加载映射文件)38 * <mapping resource="com/itheima/domain/Customer.hbm.xml"/> 39 -->40 <mapping resource="com/xujingyang/hibernate/Customer.hbm.xml"/>41 </session-factory>42 </hibernate-configuration>
回忆:快速入门
1. 下载Hibernate框架的开发包2. 编写数据库和表结构3. 创建WEB的项目,导入了开发的jar包 * MySQL驱动包、Hibernate开发的必须要有的jar包、日志的jar包4. 编写JavaBean,以后不使用基本数据类型,使用包装类5. 编写映射的配置文件(核心),先导入开发的约束,里面正常配置标签6. 编写hibernate的核心的配置文件,里面的内容是固定的7. 编写代码,使用的类和方法
第七步:编写Hibernate入门代码
1 package com.xujingyang.test ; 2 3 import java.util.List ; 4 import org.hibernate.Query ; 5 import org.hibernate.SQLQuery ; 6 import org.hibernate.Session ; 7 import org.hibernate.SessionFactory ; 8 import org.hibernate.Transaction ; 9 import org.hibernate.cfg.Configuration ; 10 import org.junit.Test ; 11 import com.xujingyang.hibernate.Customer ; 12 import com.xujingyang.utils.HibernateUtil ; 13 14 public class TestHibernate { 15 16 @Test 17 public void testAddofUtils() { 18 Session session = HibernateUtil.getSession() ; 19 Transaction transaction = session.beginTransaction() ; 20 Customer c = new Customer() ; 21 c.setCust_name("hehe") ; 22 session.save(c) ; 23 transaction.commit() ; 24 session.close() ; 25 } 26 27 /** 28 * 添加数据 29 */ 30 @Test 31 public void testSave() { 32 // 加载配置文件 33 Configuration config = new Configuration().configure() ; 34 35 // 创建sessionFactory对象 36 SessionFactory sessionFactory = config.buildSessionFactory() ; 37 38 // 创建session对象 39 Session session = sessionFactory.openSession() ; 40 41 // 开启事物 42 Transaction transaction = session.beginTransaction() ; 43 44 // 编写操作代码 45 Customer c = new Customer() ; 46 c.setCust_name("小明") ; 47 48 // 保存用户 49 session.save(c) ; 50 51 // 提交事物 52 transaction.commit() ; 53 54 // 释放资源 55 session.close() ; 56 sessionFactory.close() ; 57 58 } 59 60 /** 61 * 根据id查询数据,只能查询一条 62 */ 63 @Test 64 public void testGet() { 65 // 加载配置文件 66 Configuration config = new Configuration().configure() ; 67 68 // 创建sessionFactory对象 69 SessionFactory sessionFactory = config.buildSessionFactory() ; 70 71 // 创建session对象 72 Session session = sessionFactory.openSession() ; 73 74 // 编写操作代码 75 Customer customer = session.get(Customer.class, 94L) ; 76 System.out.println(customer) ; 77 78 // 释放资源 79 session.close() ; 80 sessionFactory.close() ; 81 82 } 83 84 /** 85 * 更新数据 86 */ 87 @Test 88 public void testUpdate() { 89 // 加载配置文件 90 Configuration config = new Configuration().configure() ; 91 92 // 创建sessionFactory对象 93 SessionFactory sessionFactory = config.buildSessionFactory() ; 94 95 // 创建session对象 96 Session session = sessionFactory.openSession() ; 97 98 // 开启事物 99 Transaction transaction = session.beginTransaction() ;100 101 // 编写操作代码102 Customer c = session.get(Customer.class, 94L) ;103 c.setCust_mobile("12324343545") ;104 session.update(c) ;105 106 // 提交事物107 transaction.commit() ;108 109 // 释放资源110 session.close() ;111 sessionFactory.close() ;112 113 }114 115 /**116 *更新或添加,存在就更新,不存在就添加 117 */118 @Test119 public void testSaveOrUpdate() {120 // 加载配置文件121 Configuration config = new Configuration().configure() ;122 123 // 创建sessionFactory对象124 SessionFactory sessionFactory = config.buildSessionFactory() ;125 126 // 创建session对象127 Session session = sessionFactory.openSession() ;128 129 // 开启事物130 Transaction transaction = session.beginTransaction() ;131 132 // 编写操作代码133 // Customer c=session.get(Customer.class, 94L);134 Customer c = new Customer() ;135 c.setCust_name("小红2") ;136 c.setCust_mobile("22324343545") ;137 session.saveOrUpdate(c) ;138 139 // 提交事物140 transaction.commit() ;141 142 // 释放资源143 session.close() ;144 sessionFactory.close() ;145 146 }147 148 /**149 * 删除数据150 */151 @Test152 public void testDel() {153 // 加载配置文件154 Configuration config = new Configuration().configure() ;155 156 // 创建sessionFactory对象157 SessionFactory sessionFactory = config.buildSessionFactory() ;158 159 // 创建session对象160 Session session = sessionFactory.openSession() ;161 162 // 开启事物163 Transaction transaction = session.beginTransaction() ;164 165 // 编写操作代码166 Customer c = session.get(Customer.class, 94L) ;167 session.delete(c) ;168 169 // 提交事物170 transaction.commit() ;171 172 // 释放资源173 session.close() ;174 sessionFactory.close() ;175 176 }177 178 /**179 * 查询多条数据180 */181 @Test182 public void testGetList() {183 // 加载配置文件184 Configuration config = new Configuration().configure() ;185 186 // 创建sessionFactory对象187 SessionFactory sessionFactory = config.buildSessionFactory() ;188 189 // 创建session对象190 Session session = sessionFactory.openSession() ;191 192 // 按sql语句查找,并制定类型193 SQLQuery sqlQuery = session.createSQLQuery("select * from cst_customer").addEntity(194 Customer.class) ;195 196 List<Customer> list = sqlQuery.list() ;197 for (Customer customer : list) {198 System.out.println(customer) ;199 }200 201 // 释放资源202 session.close() ;203 sessionFactory.close() ;204 205 }206 207 /**208 *所有数据 209 */210 @Test211 public void testGetAllList() {212 // 加载配置文件213 Configuration config = new Configuration().configure() ;214 215 // 创建sessionFactory对象216 SessionFactory sessionFactory = config.buildSessionFactory() ;217 218 // 创建session对象219 Session session = sessionFactory.openSession() ;220 221 // 按sql语句查找,并制定类型222 Query query = session.createQuery("from Customer") ;223 224 List<Customer> list = query.list() ;225 226 for (Customer customer : list) {227 System.out.println(customer) ;228 }229 230 // Customer c=session.get(Customer.class, 94L);231 Customer c = new Customer() ;232 c.setCust_name("小红2") ;233 c.setCust_mobile("22324343545") ;234 session.saveOrUpdate(c) ;235 236 // 释放资源237 session.close() ;238 sessionFactory.close() ;239 240 }241 242 }
第八步:编写Hibernate的SessionFactory工具类
1 package com.xujingyang.utils ; 2 3 import org.hibernate.Session ; 4 import org.hibernate.SessionFactory ; 5 import org.hibernate.cfg.Configuration ; 6 7 public class HibernateUtil { 8 9 private static SessionFactory sessionFactory = null ;10 static {11 sessionFactory = new Configuration().configure().buildSessionFactory() ;12 }13 14 public static Session getSession() {15 return sessionFactory.openSession() ;16 }17 }
技术分析之:Hibernate常用的配置文件
Hibernate配置文件之映射配置文件
1. 映射文件,即Stu.hbm.xml的配置文件 * <class>标签 -- 用来将类与数据库表建立映射关系 * name -- 类的全路径 * table -- 表名.(类名与表名一致,那么table属性也可以省略) * catalog -- 数据库的名称,基本上都会省略不写 * <id>标签 -- 用来将类中的属性与表中的主键建立映射,id标签就是用来配置主键的。 * name -- 类中属性名 * column -- 表中的字段名.(如果类中的属性名与表中的字段名一致,那么column可以省略.) * length -- 字段的程度,如果数据库已经创建好了,那么length可以不写。如果没有创建好,生成表结构时,length最好指定。 * <property> -- 用来将类中的普通属性与表中的字段建立映射. * name -- 类中属性名 * column -- 表中的字段名.(如果类中的属性名与表中的字段名一致,那么column可以省略.) * length -- 数据长度 * type -- 数据类型(一般都不需要编写,如果写需要按着规则来编写) * Hibernate的数据类型 type="string" * Java的数据类型 type="java.lang.String" * 数据库字段的数据类型 <column name="name" sql-type="varchar"/>
Hibernate配置文件之核心配置文件
1. 核心配置文件的两种方式 * 第一种方式是属性文件的形式,即properties的配置文件 * hibernate.properties * hibernate.connection.driver_class=com.mysql.jdbc.Driver * 缺点 * 不能加载映射的配置文件,需要手动编写代码去加载 * 第二种方式是XML文件的形式,开发基本都会选择这种方式 * hibernate.cfg.xml * <property name="hibernate.connection.driver_class" >com.mysql.jdbc.Driver</property> * 优点 * 格式比较清晰 * 编写有提示 * 可以在该配置文件中加载映射的配置文件(最主要的)2. 关于hibernate.cfg.xml的配置文件方式 * 必须有的配置 * 数据库连接信息: hibernate.connection.driver_class -- 连接数据库驱动程序 hibernate.connection.url -- 连接数据库URL hibernate.connection.username -- 数据库用户名 hibernate.connection.password -- 数据库密码 * 方言: hibernate.dialect -- 操作数据库方言 * 可选的配置 * hibernate.show_sql -- 显示SQL * hibernate.format_sql -- 格式化SQL * hibernate.hbm2ddl.auto -- 通过映射转成DDL语句 * create -- 每次都会创建一个新的表.---测试的时候 * create-drop -- 每次都会创建一个新的表,当执行结束之后,将创建的这个表删除.---测试的时候 * update -- 如果有表,使用原来的表.没有表,创建一个新的表.同时更新表结构. * validate -- 如果有表,使用原来的表.同时校验映射文件与表中字段是否一致如果不一致就会报错. * 加载映射 * 如果XML方式:<mapping resource="com/xujingyang/domain/User.hbm.xml" />
技术分析之Hibernate常用的接口和类
Configuration类和作用
1. Configuration类 * Configuration对象用于配置并且启动Hibernate。 * Hibernate应用通过该对象来获得对象-关系映射文件中的元数据,以及动态配置Hibernate的属性,然后创建SessionFactory对象。 * 简单一句话:加载Hibernate的配置文件,可以获取SessionFactory对象。2. Configuration类的其他应用(了解) * 加载配置文件的种类,Hibernate支持xml和properties类型的配置文件,在开发中基本都使用XML配置文件的方式。 * 如果采用的是properties的配置文件,那么通过Configuration configuration = new Configuration();就可以假装配置文件 * 但是需要自己手动加载映射文件 * 例如:config.addResource("cn/itcast/domain/Student.hbm.xml"); * 如果采用的XML的配置文件,通过Configuration configuration = new Configuration().configure();加载配置文件
SessionFactory:重要
1. 是工厂类,是生成Session对象的工厂类2. SessionFactory类的特点 * 由Configuration通过加载配置文件创建该对象。 * SessionFactory对象中保存了当前的数据库配置信息和所有映射关系以及预定义的SQL语句。同时,SessionFactory还负责维护Hibernate的二级缓存。 * 预定义SQL语句 * 使用Configuration类创建了SessionFactory对象是,已经在SessionFacotry对象中缓存了一些SQL语句 * 常见的SQL语句是增删改查(通过主键来查询) * 这样做的目的是效率更高 * 一个SessionFactory实例对应一个数据库,应用从该对象中获得Session实例。 * SessionFactory是线程安全的,意味着它的一个实例可以被应用的多个线程共享。 * SessionFactory是重量级的,意味着不能随意创建或销毁它的实例。如果只访问一个数据库,只需要创建一个SessionFactory实例,且在应用初始化的时候完成。 * SessionFactory需要一个较大的缓存,用来存放预定义的SQL语句及实体的映射信息。另外可以配置一个缓存插件,这个插件被称之为Hibernate的二级缓存,被多线程所共享3. 总结 * 一般应用使用一个SessionFactory,最好是应用启动时就完成初始化。
Session接口
1. 概述 * Session是在Hibernate中使用最频繁的接口。也被称之为持久化管理器。它提供了和持久化有关的操作,比如添加、修改、删除、加载和查询实体对象 * Session 是应用程序与数据库之间交互操作的一个单线程对象,是 Hibernate 运作的中心 * Session是线程不安全的 * 所有持久化对象必须在 session 的管理下才可以进行持久化操作 * Session 对象有一个一级缓存,显式执行 flush 之前,所有的持久化操作的数据都缓存在 session 对象处 * 持久化类与 Session 关联起来后就具有了持久化的能力2. 特点 * 不是线程安全的。应避免多个线程使用同一个Session实例 * Session是轻量级的,它的创建和销毁不会消耗太多的资源。应为每次客户请求分配独立的Session实例 * Session有一个缓存,被称之为Hibernate的一级缓存。每个Session实例都有自己的缓存3. 常用的方法 * save(obj) * delete(obj) * get(Class,id) * update(obj) * saveOrUpdate(obj) -- 保存或者修改(如果没有数据,保存数据。如果有,修改数据) * createQuery() -- HQL语句的查询的方式
Transaction接口
1. Transaction是事务的接口2. 常用的方法 * commit() -- 提交事务 * rollback() -- 回滚事务3. 特点 * Hibernate框架默认情况下事务不自动提交.需要手动提交事务 * 如果没有开启事务,那么每个Session的操作,都相当于一个独立的事务
阅读全文
0 0
- 框架之 hibernate简单入门
- Hibernate框架之入门配置
- Hibernate框架之入门配置
- 框架之Struts2简单入门
- 【Hibernate框架】Hibernate入门
- 框架漫谈之hibernate(二)hibernate配置以及入门案例
- Hibernate框架入门
- Hibernate框架入门一
- hibernate框架的入门
- Hibernate框架基础入门
- Hibernate框架入门案例
- 【SSH框架】--Hibernate入门
- Hibernate框架入门(一)
- hibernate框架入门
- Hibernate框架入门2
- hibernate框架入门
- Hibernate框架入门Demo
- Hibernate框架入门
- 深入理解多线程,死锁再现
- JavaScript 闭包
- Linux中发布项目的一些命令笔记
- AFNetworking的介绍与使用
- Nginx --Windows下和Linux下搭建集群小记
- 框架之 hibernate简单入门
- 框架之 hibernate之二
- TCP握手和挥手
- 框架之 hibernate之关联关系映射
- 框架之 hibernate之各种查询
- 全源码教你一键锁屏
- 框架之Struts2简单入门
- java导出Excel 总结
- hibernate 关联关系 详解