hibernate系列之一

时间:2022-07-24
本文章向大家介绍hibernate系列之一,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

通过自己不断的学习框架以及相关知识的学习,自己学会总结了学习路上遇到的一些问题以及疑惑,自己现在跟着相关的学习资料又进行了一些总结和实践,希望通过自己走过的学习之路能够帮助小伙伴们解决一些学习上问题或者存在的疑问。

如果在总结过程中出现理解上的错误,希望各位及时指正,欢迎各位大佬在下面评论。

首先先从hibernate的基础知识进行学习和总结:

学过框架的伙伴们都知道hibernate中重要的几个API吧,下面就先从hibernate的相关API进行学习,中间可能还会有相关的面试题哟;

1、Configuration:配置对象

作用主要是用于加载映射文件;

configuration实例主要用于启动加载管理hibernate的配置文件。

1.1通常使用Configuration config = new Confifuration().configure()创建实例,

默认(此种)方式会默认去项目下的src下读取hibernate.cf.xml文件;

1.2如果想要指定目录下配置文件,则需要在configure()中传递一个文件路径参数;

方式:Configuration config = new Configuration().configure("xml文件路径");

2、SessionFactory:session工厂对象(二级缓存)

SessionFactory接口负责hibernate的初始化和建立session对象,他在hibernate中起到缓冲的作用,所以是hibernate中的二级缓存;

hibernate可以将自动生成的SQL语句、映射数据以及某些可重复利用的数据放在放在缓冲区;

获取方式:SessionFactory sessionFactory = config.buildSessionFactory();

SessionFactory特点:线程安全,它的一个实例能够供多个线程共享;

3、Session(一级缓存):应用程序和数据之间交互操作的一个单线程对象,所有的持久化对象必须在session的管理下才可以进行持久化操作;

创建方式:Session session = sessionFactory.openSession();

方式2:Session session = sessionFactory.getCurrentSession();

两者之间的区别在于:是否能够自动关闭资源(即释放session),前者需要手动关闭session,session.close();

后者创建Session实例会被绑定在当前线程中,他在提交或者回滚操作时会自动关闭;

Session特点:session时线程不安全的,多个线程同时操作一个session时,会导致session存取混乱

session 中的常用方法和面试题:

  save()、update()和saveOrUpdate():用于增加和修改对象;

 面试题:之间的区别???有兴趣的伙伴可以留言互动一下。

  delete()删除对象

  get()和load():根据主键查询;面试题:二者之间的区别???

  createQuery()和createSQLQuery():用于数据库操作对象;

4、Transaction:事务

Transaction接口主要用于管理事务,对底层的事务接口进行了封装;

获取对象:Transaction transaction= session.beginTransaction();

  commit():提交相关关联的session实例

  rollback():撤销事务操作;发生异常时需要使用rollback()方法进行事务回滚,避免数据发生错误;

下面进行一个实例练习以及注意添加的注释说明:

环境:myeclipse+JDK1.8+hibernate相关jar包(注意mysql的连接驱动)+mysql

创建数据库表

CREATE TABLE `customer` (
  `cust_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `cust_name` varchar(255) DEFAULT NULL,
  `cust_source` varchar(255) DEFAULT NULL,
  `cust_industry` varchar(255) DEFAULT NULL,
  `cust_level` varchar(255) DEFAULT NULL,
  `cust_linkman` varchar(255) DEFAULT NULL,
  `cust_phone` varchar(255) DEFAULT NULL,
  `cust_mobile` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`cust_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

首先创建实体类:

package com.itwx.hibernate.pojo;

/**
 * 创建持久化类(实体类)
 * @author wangxuan
 *
 */
public class Customer {

	private Long cust_id;
	private String cust_name;
	private String cust_source;
	private String cust_industry;
	private String cust_level;
	private String cust_phone;
	private String cust_mobile;
	public Long getCust_id() {
		return cust_id;
	}
	public void setCust_id(Long cust_id) {
		this.cust_id = cust_id;
	}
	public String getCust_name() {
		return cust_name;
	}
	public void setCust_name(String cust_name) {
		this.cust_name = cust_name;
	}
	public String getCust_industry() {
		return cust_industry;
	}
	public void setCust_industry(String cust_industry) {
		this.cust_industry = cust_industry;
	}
	public String getCust_level() {
		return cust_level;
	}
	public void setCust_level(String cust_level) {
		this.cust_level = cust_level;
	}
	public String getCust_phone() {
		return cust_phone;
	}
	public void setCust_phone(String cust_phone) {
		this.cust_phone = cust_phone;
	}
	public String getCust_mobile() {
		return cust_mobile;
	}
	public void setCust_mobile(String cust_mobile) {
		this.cust_mobile = cust_mobile;
	}
	public String getCust_source() {
		return cust_source;
	}
	public void setCust_source(String cust_source) {
		this.cust_source = cust_source;
	}
	
	
}

然后在实体类相同包下配置映射文件;

<?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:实体类的全类名
    		table:数据库中与实体类相对应的表
    	 -->
    	<class name="com.itwx.hibernate.pojo.Customer" table="customer">
    		<!--  建立主键和实体类中的字段映射关系-->
    			<!-- id:主键之间的映射关系 
    				name:实体类中与数据库表中的主键对应的字段
    				column:数据库中表中的主键属性(实体类和数据库表中的字段名称一致可以省略)
    			-->
    		<id name="cust_id" column="cust_id">
    			<!--  设置主键增长策略-->
    			<generator class="native"/>
    		</id>
    		<!--建立实体类的其他字段和数据库中表的其他字段映射关系 (因为都是在一个实体类中和一张表的对应,所以标签元素的位置注意在class中)-->
				<!-- 
					property:标签建立其他属性和表中的字段之间建立映射关系
					name:类中的属性名
					columnL:表中的字段名
					length:字段长度
					type:字段属性,java数据类型
				 -->
			<property name="cust_name" column="cust_name"></property>
			<property name="cust_source" column="cust_source"></property>
			<property name="cust_industry" column="cust_industry"></property>
			<property name="cust_level" column="cust_level"></property>
			<property name="cust_phone" column="cust_phone"></property>
			<property name="cust_mobile" column="cust_mobile"></property>
    	</class>
    </hibernate-mapping>

配置核心映射文件:配置连接数据库的基本信息和映射文件

<?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>
		<!--  配置连接数据库的基本信息参数-->
		<session-factory>
			<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>		
			<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_01</property>
			<property name="hibernate.connection.username">root</property>
			<property name="hibernate.connection.password">123456</property>
			<!-- 配置hibernate属性 -->
			<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
			<!-- hibernate显示SQL语句 -->
			<property name="hibernate.show_sql">true</property>
			<!-- hibernate格式化SQL语句 -->
			<property name="hibernate.foemat_sql">true</property>
			<property name="hibernate.hbm2ddl.auto">update</property>
			
			<!-- 配置加载映射文件:全路径-->
			<mapping resource="com/itwx/hibernate/pojo/Customer.hbm.xml"/>
		</session-factory>
	</hibernate-configuration>

定义测试类进行实现

package com.itwx.hibernate.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import com.itwx.hibernate.pojo.Customer;

public class HibernateTest {

	/**
	 * hibernate的执行步骤:
	 * 1.加载核心配置文件new COnfiguration().configure();
	 * 2.创建SessionFactory
	 * 3.创建Session
	 * 4.开启事务
	 * 5.执行操作
	 * 6.提交事务
	 * 7.释放资源(关闭session)
	 */
	@Test
	public void test(){
		//加载核心配置文件
		Configuration configuration = new Configuration().configure();
		
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		
		Session session = sessionFactory.openSession();
		
		Transaction transaction = session.beginTransaction();
		
		//执行操作
		Customer customer = new Customer();
		customer.setCust_name("王五");
		customer.setCust_source("推销");
		
		session.save(customer);
		
		transaction.commit();
		session.close();
	}
}