开发笔记_JAVA常用三大框架 _01_Hibernate

Java常用三大框架

        —— Hibernate 框架


项目的三层结构

                一个完整的WEB项目,一般情况下都分为三层结构:WEB层、业务层、持久层。

                WEB层:与客户端进行数据交互。客户端发送请求到WEB层, WEB层接收并简单的封装后传递给业务层。

                业务层 :处理业务逻辑。将处理过后的数据交给持久层。

                持久层 :负责与底层数据交互。主要体现在与数据库的交互。


JAVA三大框架简单介绍


                JAVA 最常用最基础的两套框架分别是 SSH 和 SSM 框架。

                本次主要学习 JAVA 的 SSH 三大框架。

                SSH 三大框架是指:Struct2 + Spring + Hibernate。

                Struct2 : 开源框架。主要体现在 WEB 层。当服务器启动后,根据配置文件加载服务到内存。

                                  提供了数据实体(JAVABean)、视图(View)、控制器(Controller)的相关组件。

                Spring:    主要体现在业务层。

                                  提供了管理业务对象的一致方法,鼓励使用接口式编程。还提供了唯一的数据管理,包括JDBC框架。

                Hibernate:开源的对象关系映射框架。主要体现在持久层。

                                  对JDBC进行了轻量级的对象封装,更加方便的操作数据库。

Hibernate 框架介绍

                Hibernate 是一个开源的对象关系映射框架。对JDBC进行了轻量级的对象封装,将POJO与数据库表建立了映射关系。是一个全自动的ORM(Object Relational Mapping:对象关系映射)框架。可以自动生成SQL语句,自动执行SQL语句,使得程序员可以方便的使用操作对象的思维操作数据库。使用Hibernate框架主要用于完成数据的持久化。

                优点

                        1、对JDBC访问数据库的代码做了封装,极大的简化了数据访问层繁琐的重复性代码;

                        2、基于JDBC的主流持久化框架,是一个非常优秀的ORM实现,很大程度的简化了DAO层的编码工作;

                        3、性能非常好,因为它是一个轻量级框架,映射的灵活性非常出色,且支持很多关系型数据库,从一对一到一对多的各种复杂关系。


Hibernate 框架开发入门

Step 1 :下载Hibernate运行环境

        https://sourceforge.net/projects/hibernate/files/hibernate-orm/5.0.7.Final/hibernate-release-5.0.7.Final.zip/download  点击打开链接


Step 2: 创建数据表结构(以MySQL数据库为例)

CREATE DATABASE db_hibernate_test;
USE db_hibernate_test;
CREATE TABLE `t_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=1 DEFAULT CHARSET=utf8;


Step 3: 搭建Hibernate开发环境

    1、安装JDK + Myeclipse开发环境 + Tomcat

    2、启动MyEclipse,新建Web项目。

        

  3、导入MySQL驱动包 + Hibernate 驱动包 + 日志包

        

Step 4:编写JavaBean实体类

        

package com.mcd.domain;
/**
 * 客户的JavaBean实体类
 * @author 
 */
public class Customer {
	
	private Long cust_id;	//建议使用包装类型,包装类型的默认值是null, 而基本类型的默认值是 0。
	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;
	// ...  Set/Get方法自动生成 这里省略
}

Step 5:创建类与表结构之间的映射

   1、建议映射的配置文件与JavaBean放置在同一目录;

   2、建议映射文件名称为 JavaBean的名字 + .hbm.xml;    (hbm:意为 :Hibernate Map)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<!-- 配置类和表结构的映射 -->
	<class name="com.mcd.domain.Customer" table="t_customer">
		<!-- 配置id 
			name属性,JavaBean的属性
			column属性,是表结构的字段
		-->
		<id name="cust_id" column="cust_id">
			<!-- 主键的生成策略 -->
			<generator class="native"/>
		</id>	
		<!-- 配置其他的属性 -->
		<property name="cust_name" column="cust_name"/>
		<property name="cust_user_id" column="cust_user_id"/>
		<property name="cust_create_id" column="cust_create_id"/>
		<property name="cust_source" column="cust_source"/>
		<property name="cust_industry" column="cust_industry"/>
		<property name="cust_level" column="cust_level"/>
		<property name="cust_linkman" column="cust_linkman"/>
		<property name="cust_phone" column="cust_phone"/>
		<property name="cust_mobile" column="cust_mobile"/>		
	</class>	
</hibernate-mapping>   

Step 6 : 创建Hibernate核心配置文件

   核心配置文件整个项目只需要写一个。   

   1、核心配置文件必须放在src的根目录下;

   2、核心配置文件名必须为:hibernate.cfg.xml;      (cfg:意为:configuration)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<!-- 先配置SessionFactory标签,一个数据库对应一个SessionFactory标签 -->
	<session-factory>
		<!-- 必须要配置的参数有5个,4个连接参数(驱动 + 数据库名 + 用户名 + 密码) + 数据库的方言参数 -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql:///db_hibernate_test</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		<!-- 数据库的方言 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

		<!-- 可选配置 -->
		<!-- 显示SQL语句,在控制台显示 -->
		<property name="hibernate.show_sql">true</property>
		<!-- 格式化SQL语句 -->
		<property name="hibernate.format_sql">true</property>
		<!-- 生成数据库的表结构 
			update:如果没有表结构,创建表结构。如果存在,不会创建,添加数据
		-->
		<property name="hibernate.hbm2ddl.auto">update</property>
		<!-- 映射配置文件,需要引入映射的配置文件 -->
		<mapping resource="com/mcd/domain/Customer.hbm.xml"/>
	</session-factory>
</hibernate-configuration>	

Step 7 :测试一下框架搭建是否正常

   1、创建测试包,导入单元测试的Jar, 创建单元测试

package com.mcd.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import com.mcd.domain.Customer;

/**
 * 测试 Hibernate 框架
 * @author 
 *
 */
public class TestDemo1 {

	/**
	 * 单元测试  测试保存客户功能
	 */
	@Test
	public void testSave(){
		
		//1、加载配置文件
		Configuration config = new Configuration();	
		//默认加载src目录下 hibernate.cfg.xml 配置文件
		config.configure();
		
		//2、创建SessionFactory对象, 生成Session对象
		SessionFactory factory = config.buildSessionFactory();
		
		//3、创建Session对象
		Session session = factory.openSession();
		
		//4、开启事务
		Transaction tr = session.beginTransaction();
		
		//5、编写保存客户的代码
		Customer c = new Customer();
//		c.setCust_id(cust_id);		主键 由框架自动管理 且自动递增 这里不需要手动设置
		c.setCust_name("测试用户");
		c.setCust_user_id(1000000);
		c.setCust_create_id(1680502);
		c.setCust_industry("系统开发");
		c.setCust_level("A");
		c.setCust_linkman("MCD");
		c.setCust_mobile("188********");
		c.setCust_phone("496203");
		c.setCust_source("");
		//保存数据 操作对象就相当于操作数据库表的结构
		session.save(c);
		
		//6、提交事务
		tr.commit();
		
		//7、释放资源
		session.close();
		factory.close();
	}
}

   2、Run AS "JUint Test" 运行单元测试, 控制台会有以下提示

log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Hibernate: 
    insert 
    into
        t_customer
        (cust_name, cust_user_id, cust_create_id, cust_source, cust_industry, cust_level, cust_linkman, cust_phone, cust_mobile) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?, ?)

同时, 数据库中多出一条数据

说明框架搭建没有问题。

step 8 :Session对象的CRUD操作

  1、 为了方便操作,先写一个工具类

package com.mcd.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * Hibernate 框架 的工具类
 */

public class HibernateUtils {

	private static final Configuration CONFIG;
	private static final SessionFactory FACTORY;
	
	static {
		
		//加载XML的配置文件
		CONFIG = new Configuration().configure();
		
		//构造工厂
		FACTORY = CONFIG.buildSessionFactory();
	}
	
	/**
	 * 从工厂中获取Session对象
	 * @return
	 */
	public static Session getSession() {
		return FACTORY.openSession();
	}
}

   2、测试 Session 对象的 CRUD 操作(TestDemo1 类中)

        /**
	 * 单元测试 3 测试Session对象的CRUD
	 */
	@Test
	public void testSave3(){
		Session session = HibernateUtils.getSession();
		Transaction tr = session.beginTransaction();
		
		//查询 :第一个参数是JavaBean的反射, 第二个参数是需要查询的数据的 主键 (因为我们定义的主键是Long类型的,所以加L后缀)
		Customer c = session.get(Customer.class, 1L);
		System.out.println(c);
		
		//修改:参数为对象
		//★ 修改 删除 都建议先查询 后进行改删操作
		c.setCust_create_id(1234567);
		c.setCust_phone("7654321");
		session.update(c);
		
		//删除:参数为对象
		session.delete(c);
                
                //新增或修改:如果存在则修改,如果不存在则新增
                c.setCust_create_id(987);    //★新增:主键由Hibernate自动处理,切记不要操作主键
                session.saveOrUpdate(c);

		tr.commit();
		session.close();
	}

  3、控制台输出内容

log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Hibernate: 
    select
        customer0_.cust_id as cust_id1_0_0_,
        customer0_.cust_name as cust_nam2_0_0_,
        customer0_.cust_user_id as cust_use3_0_0_,
        customer0_.cust_create_id as cust_cre4_0_0_,
        customer0_.cust_source as cust_sou5_0_0_,
        customer0_.cust_industry as cust_ind6_0_0_,
        customer0_.cust_level as cust_lev7_0_0_,
        customer0_.cust_linkman as cust_lin8_0_0_,
        customer0_.cust_phone as cust_pho9_0_0_,
        customer0_.cust_mobile as cust_mo10_0_0_ 
    from
        t_customer customer0_ 
    where
        customer0_.cust_id=?
Customer [cust_id=1, cust_name=测试用户, cust_user_id=1000000, cust_create_id=1680502, cust_source=, cust_industry=系统开发, cust_level=A, cust_linkman=MCD, cust_phone=496203, cust_mobile=188********]
Hibernate: 
    delete 
    from
        t_customer 
    where
        cust_id=?
Hibernate: 
    insert 
    into
        t_customer
        (cust_name, cust_user_id, cust_create_id, cust_source, cust_industry, cust_level, cust_linkman, cust_phone, cust_mobile) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?, ?)

   4、刚才查询到的数据已经被删除


step 9 : Session 对象的综合查询

    @Test
	public void testSave4(){
		
		Session session = HibernateUtils.getSession();
		Transaction tr =  session.beginTransaction();
		
		//创建查询接口
		Query query = session.createQuery("from Customer");
		//查询所有数据 select * from Customer
		List<Customer> list = query.list();
		for (Customer item : list) {
			System.out.println(item);
		}
		
		tr.commit();//事务的提交方法
		// tr.rollback();  // 事务的回滚方法 -- 一般写在 catch 语句中
		session.close();
	}

猜你喜欢

转载自blog.csdn.net/shaotaiban1097/article/details/80738852
今日推荐