码迷,mamicode.com
首页 > Web开发 > 详细

框架之 hibernate简单入门

时间:2017-04-13 19:56:40      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:性能   ase   nec   begin   约束   close   1.5   var   gif   

hibernate框架的搭建

 

 

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/itheima/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.Driver
10             #hibernate.connection.url jdbc:mysql:///test
11             #hibernate.connection.username gavin
12             #hibernate.connection.password
13         -->
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.MySQLDialect
23          -->
24          <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
25          <!-- 
26         * 可选的配置
27             #hibernate.show_sql true
28             #hibernate.format_sql true
29             #hibernate.hbm2ddl.auto update
30          -->
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>

 


第七步:编写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     @Test
119     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     @Test
152     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     @Test
182     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     @Test
211     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 }
View Code

 

 


第八步:编写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简单入门

标签:性能   ase   nec   begin   约束   close   1.5   var   gif   

原文地址:http://www.cnblogs.com/xujingyang/p/6705676.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!