hibernate教程--常用配置和核心API详解

一、Hibernate的常用的配置及核心API.

1.1 Hibernate的常见配置:

1.1.1、核心配置:

核心配置有两种方式进行配置:

 1)属性文件的配置:

* hibernate.properties

* 格式:

* key=value

 hibernate.connection.driver_class=com.mysql.jdbc.Driver

 注意:没有办法在核心配置文件中加载映射文件.(必须手动编码的方式进行加载.)

2)XML格式文件配置:

* hibernate.cfg.xml

* 格式:

<property name="hibernate.connection.username">root</property>

3)核心配置中:

1.必须的配置:

* 连接数据库4个基本参数:

hibernate.connection.driver_class  连接数据库驱动程序

hibernate.connection.url   连接数据库URL

hibernate.connection.username  数据库用户名

hibernate.connection.password   数据库密码

* Hibernate的方言:

hibernate.dialect   操作数据库方言

2.可选的配置:

hibernate.show_sql  true 在控制台上输出SQL语句

hibernate.format_sql  true  格式化控制台输出的SQL语句

hibernate.connection.autocommit  true 事务是否自动提交

hibernate.hbm2ddl.autocreate/create-drop/update/validate

* create:每次执行的时候,创建一个新的表.(如果以前有该表,将该表删除重新创建.) 一般测试的时候的使用.

* create-drop:每次执行的时候,创建一个新的表,程序执行结束后将这个表,删除掉了.一般测试的时候使用.

* update:如果数据库中没有表,创建一个新的表,如果有了,直接使用这个表.可以更新表的结构.

* validate:会使用原有的表.完成校验.校验映射文件与表中配置的字段是否一致.不一致报错.

3.映射的配置:

* 在核心配置文件中加载映射文件:

 <mapping resource="cn/itcast/hibernate3/demo1/Customer.hbm.xml" />

* 使用手动编码的方式进行加载 :

核心配置实例

<?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:///hibernate3_test
	</property>
	<property name="hibernate.connection.username">root</property>
	<property name="hibernate.connection.password">123</property>
	<!-- Hibernate的方言 -->
	<!-- 生成底层SQL不同的 -->
	<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>
	
	<property name="hibernate.connection.autocommit">false</property>
	<!-- hbm:映射 to DDL: create drop alter -->
	<property name="hibernate.hbm2ddl.auto">update</property>

	<!-- C3P0连接池设定-->
	<!-- 使用c3po连接池  配置连接池提供的供应商-->
	<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider                                                                                                                                                     </property>
	
	<!--在连接池中可用的数据库连接的最少数目 -->
	<property name="c3p0.min_size">5</property>
	<!--在连接池中所有数据库连接的最大数目  -->
	<property name="c3p0.max_size">20</property>
	<!--设定数据库连接的过期时间,以秒为单位,
	如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->
	<property name="c3p0.timeout">120</property>
	 <!--每3000秒检查所有连接池中的空闲连接 以秒为单位-->
	<property name="c3p0.idle_test_period">3000</property>

	<!-- 通知Hibernate加载那些映射文件 -->
	<mapping resource="com/sihai/hibernate3/demo1/Customer.hbm.xml" />

</session-factory>
</hibernate-configuration>

1.1.2、映射文件的配置:

ORM:对象和关系映射.

* 配置Java对象与表映射.

* 配置类与表的映射:

* name:类的全路径:

* table:表的名称:(可以省略的.使用类的名称作为表名.)

<class name="com.sihai.hibernate3.demo1.Order" table=”orders”>

 配置普通属性与字段映射:

<property name="name" column="name" type="string" length=”20”/>

type:三种写法

* Java类型:java.lang.String

* Hibernate类型:string

* SQL类型:不能直接使用type属性,需要子标签<column>

* <column name="name" sql-type="varchar(20)"/>

配置唯一标识与主键映射:

* 一个表中只有一个主键的形式:

<id name=”id” column=”id”>

* 生成策略:

* 一个表对应多个主键形式:(复合主键:)---了解.

* <composite-id></composite-id>

* 关联关系:

* 命名SQL:

<query name="findAll">

from Customer

</query>

<sql-query name="sqlFindAll">

select * from customer

</sql-query>

<?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.sihai.hibernate3.demo1.Customer" table="customer">
		<!-- 建立类中属性与表中的字段映射 -->
		<!-- 唯一标识 -->
		<!-- 使用id的标签 配置唯一属性 -->
		<!-- 在<id>标签中配置一个主键的生成策略. -->
		<id name="id" column="id">
			<generator class="assigned"/>
		</id>
		
		<!-- 普通属性 -->
		<!-- property标签:映射类中的普通属性 name:类中的属性名称, column:表中字段名称 -->
		<!-- 
			type:三种写法
				* Java类型		:java.lang.String
				* Hibernate类型	:string
				* SQL类型		:不能直接使用type属性,需要子标签<column>
					* <column name="name" sql-type="varchar(20)"/>
		 -->
		<property name="name" column="name" type="string" length="20"/>
		<property name="age" column="age"/>
		
		
	</class>
	

</hibernate-mapping>

二、 Hibernate的核心API:

2.1 Hibernate的核心API:

Configuration:负责管理 Hibernate 的配置信息

2.1.1.加载核心配置文件:

核心配置有两种:

* hibernate.properties:

* 加载:

* Configuration configuration = new Configuration();

* hibernate.cfg.xml:

* 加载:

* Configuration configuration = new Configuration().configure();

2.1.2.加载映射文件:

* 第一种写法:

* configuration.addResource("cn/itcast/hibernate3/demo1/Customer.hbm.xml");

* 第二种写法:(要求:映射文件名称要规范,类与映射在同一个包下)

* configuration.addClass(Customer.class);

SessionFactory:Session工厂.

Configuration对象根据当前的配置信息生成 SessionFactory对象

SessionFactory 对象中保存了当前的数据库配置信息和所有映射关系以及预定义的SQL语句

SessionFactory 对象是线程安全的

SessionFactory还负责维护Hibernate的二级缓存

SessionFactory对象根据数据库信息,维护连接池,创建Session(相当于Connection)对象.

抽取工具类:

public class HibernateUtils {

private static Configuration configuration;

private static SessionFactory sessionFactory;

static{

configuration = new Configuration().configure();

sessionFactory = configuration.buildSessionFactory();

}

public static Session openSession(){

return sessionFactory.openSession();

}

public static void main(String[] args) {

openSession();

}

}

2.2.3在Hibernate中使用c3p0连接池:

* 引入c3p0的jar包

* 在核心配置中添加一段配置:

<!-- C3P0连接池设定-->

<!-- 使用c3po连接池  配置连接池提供的供应商-->

<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider                                                                                                                                        </property>

<!--在连接池中可用的数据库连接的最少数目 -->

<property name="c3p0.min_size">5</property>

<!--在连接池中所有数据库连接的最大数目  -->

<property name="c3p0.max_size">20</property>

<!--设定数据库连接的过期时间,以秒为单位,

如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 -->

<property name="c3p0.timeout">120</property>

 <!--每3000秒检查所有连接池中的空闲连接 以秒为单位-->

<property name="c3p0.idle_test_period">3000</property>

2.2.4、Session:

相当于 JDBC的 Connection

Session 是应用程序与数据库之间交互操作的一个单线程对象,是 Hibernate 运作的中心

Session是线程不安全的

所有持久化对象必须在 session 的管理下才可以进行持久化操作

Session 对象有一个一级缓存,显式执行 flush 之前,所有的持久化操作的数据都缓存在 session 对象处

持久化类与 Session 关联起来后就具有了持久化的能力

Session维护了Hiberante一级缓存.

save()/persist():添加.

update() :修改

saveOrUpdate() :增加和修改对象

delete()  :删除对象

get()/load()  :根据主键查询

createQuery() :创建一个Query接口,编写HQL语句

createSQLQuery() :创建一个SQLQuery接口,编写SQL语句数据库操作对象

createCriteria()  :返回一个Criteria接口.条件查询

 

2.2.5、Transaction:

获得:

Transaction tx = session.beginTransaction();

常用方法:

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

rollback():撤销事务操作

wasCommitted():检查事务是否提交

 

如果没有开启事务,那么每个Session的操作,都相当于一个独立的事务

2.2.6、Query

Query代表面向对象的一个Hibernate查询操作

session.createQuery 接受一个HQL语句

HQL是Hibernate Query Language缩写, 语法很像SQL语法,但是完全面向对象的

2.2.7、Criteria

Criteria条件查询:

package com.sihai.hibernate3.demo1;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

/**
 * Hibernate入门案例的测试:
 * @author sihai
 *
 */
public class HibernateTest1 {
	
	@Test
	// 查询所有记录:SQL
	public void demo7(){
		// 1.加载核心配置文件
		Configuration configuration = new Configuration().configure();
		// 2.构建Session工厂
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		// 3.通过工厂创建Session
		Session session = sessionFactory.openSession();
		// 4.开启事务
		Transaction tx = session.beginTransaction();
		
		// 5.操作
		// 查询所有:SQL
		/*SQLQuery query = session.createSQLQuery("select * from customer");
		List<Object[]> list = query.list();
		
		for (Object[] objs : list) {
			System.out.println(Arrays.toString(objs));
		}*/
		SQLQuery query = session.createSQLQuery("select * from customer");
		query.addEntity(Customer.class);
		List<Customer> list = query.list();
		for (Customer customer : list) {
			System.out.println(customer);
		}
		
		// 6.事务提交
		tx.commit();
		// 7.释放资源
		session.close();
		sessionFactory.close();
		
	}
	
	@Test
	// 查询所有:QBC
	public void demo6(){
		// 1.加载核心配置文件
		Configuration configuration = new Configuration().configure();
		// 2.构建Session工厂
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		// 3.通过工厂创建Session
		Session session = sessionFactory.openSession();
		// 4.开启事务
		Transaction tx = session.beginTransaction();
		
		// 5.操作:
		// 查询所有 :QBC.
		/*Criteria criteria = session.createCriteria(Customer.class);
		List<Customer> list = criteria.list();*/
		Criteria criteria = session.createCriteria(Customer.class);
		criteria.add(Restrictions.eq("name", "sihai"));
		List<Customer> list = criteria.list();
		
		for (Customer customer : list) {
			System.out.println(customer);
		}
		
		// 6.事务提交
		tx.commit();
		// 7.释放资源
		session.close();
		sessionFactory.close();
	}
	
	@Test
	// 查询所有:HQL.
	// HQL:Hibernate Query Language.Hibernate查询语言.面向对象的查询.
	public void demo5(){
		// 1.加载核心配置文件
		Configuration configuration = new Configuration().configure();
		// 手动编码加载映射文件:
		// configuration.addResource("com/sihai/hibernate3/demo1/Customer.hbm.xml");
		// configuration.addClass(Customer.class);
		// 2.构建Session工厂
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		// 3.通过工厂创建Session
		Session session = sessionFactory.openSession();
		// 4.开启事务
		Transaction tx = session.beginTransaction();	
		
		// 5.操作
		// 1.查询所有的客户
		/*Query query = session.createQuery("from Customer");
		List<Customer> list = query.list();*/
		// 2.按名称查询
		/*Query query = session.createQuery("from Customer where name = ?");
		query.setParameter(0, "sihai");*/
		Query query = session.createQuery("from Customer where name = :aaa");
		query.setParameter("aaa", "sihai");
		List<Customer> list = query.list();
		
		for (Customer customer : list) {
			System.out.println(customer);
		}
		
		// 6.事务提交
		tx.commit();
		// 7.释放资源
		session.close();
		sessionFactory.close();
	}
	
	@Test
	// 删除记录
	public void demo4(){
		// 1.加载核心配置文件
		Configuration configuration = new Configuration().configure();
		// 2.构建Session工厂
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		// 3.通过工厂创建Session
		Session session = sessionFactory.openSession();
		// 4.开启事务
		Transaction tx = session.beginTransaction();	
		
		// 5.操作
		// 删除记录有两种方式:
		// 5.1手动创建对象的方式
		/*Customer customer = new Customer();
		customer.setId(2);
		
		session.delete(customer);*/
		
		// 5.2先查询在删除的方式
		Customer customer = (Customer)session.get(Customer.class, 1);
		session.delete(customer);
		
		// 6.事务提交
		tx.commit();
		// 7.释放资源
		session.close();
		sessionFactory.close();
	}
	
	@Test
	// 修改记录
	public void demo3(){
		// 1.加载核心配置文件
		Configuration configuration = new Configuration().configure();
		// 2.构建Session工厂
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		// 3.通过工厂创建Session
		Session session = sessionFactory.openSession();
		// 4.开启事务
		Transaction tx = session.beginTransaction();	
		
		// 5.操作:
		// 修改记录:两种方式可以进行修改.
		// 5.1手动创建对象的方式
		/*Customer customer = new Customer();
		customer.setId(2);
		customer.setName("sihai");
		
		session.update(customer);*/
		
		// 5.2先查询在修改的方式
		Customer customer = (Customer) session.get(Customer.class, 1);
		customer.setName("sihai");
		
		session.update(customer);
		
		// 6.事务提交
		tx.commit();
		// 7.释放资源
		session.close();
		sessionFactory.close();
	}
	
	@Test
	// 按id进行查询
	// get和load方法区别
	public void demo2(){
		// 1.加载核心配置文件
		Configuration configuration = new Configuration().configure();
		// 2.构建Session工厂
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		// 3.通过工厂创建Session
		Session session = sessionFactory.openSession();
		// 4.开启事务
		Transaction tx = session.beginTransaction();
		// 5.操作
		// 根据id进行查询:
		// get方法进行查询
		Customer customer = (Customer) session.get(Customer.class, 100); // 马上发生一条SQL进行查询
		
		System.out.println(customer);
		
		// load方法进行查询
		//Customer customer = (Customer) session.load(Customer.class, 100); // 没有发送SQL
		
		//System.out.println(customer);// 发送SQL.
		
		// 6.事务提交
		tx.commit();
		// 7.释放资源
		session.close();
		sessionFactory.close();
		
	}
	
	@Test
	// 保存记录
	public void demo1(){
		// 1.Hiberante框架加载核心配置文件(有数据库连接信息)
		Configuration configuration = new Configuration().configure();
		// 2.创建一个SessionFactory.(获得Session--相当连接对象)
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		// 3.获得Session对象.
		Session session = sessionFactory.openSession();
		// 4.默认的情况下,事务是不自动提交.
		Transaction tx = session.beginTransaction();
		// 5.业务逻辑操作
		
		// 向数据库中插入一条记录:
		Customer customer = new Customer();
		customer.setName("sihai");
		customer.setAge(38);
		
		session.save(customer);
		
		// 6.事务提交
		tx.commit();
		// 7.释放资源
		session.close();
		sessionFactory.close();
	}
}

三、 Hibernate中的持久化类:

持久化类:实体类 + 映射文件.

3.1、持久化类是有编写规范:

1、提供一个无参数 public访问控制符的构造器:用到反射.

2、提供一个标识属性,映射数据表主键字段:

3、java区分两个对象是否是同一个使用 地址.

4、 数据库区分两条记录是否一致:使用  主键.

5、 Hibernate中区分持久化对象是否是同一个,根据唯一标识:

6、 所有属性提供public访问控制符的 set  get 方法:框架中存值和取值的时候使用.

7、 标识属性应尽量使用基本数据类型的包装类型

8、 持久化类尽量不要使用final进行修饰:

 用final修饰的类是不能被继承.无法生成代理对象.(延迟加载的时候返回代理对象.延迟加载就失效.)

9、 尽量要Hibernate自己去维护主键:

 3.2、主键的生成策略:

1、 increment:自动增长.适合 short int long...不是使用数据库的自动增长机制.使用Hibernate框架提供的自动增长方式.

2、 select max(id) from 表; 在最大值的基础上+1.(多线程的问题.)在集群下不要使用

3、identity:自动增长.适合 short int long...采用数据库的自动增长机制.不适合于Oracle数据库.

4、 sequence:序列.适用于 short int long ... 应用在Oracle上 .

5、 uuid:适用于字符串类型的主键.采用随机的字符串作为主键.

6、 native:本地策略.底层数据库不同.自动选择适用identity 还是 sequence.

7、 assigned:Hibernate框架不维护主键,主键由程序自动生成.

8、 foreign:主键的外来的.(应用在多表一对一的关系.)

package com.sihai.hibernate3.demo1;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.sihai.utils.HibernateUtils;

/**
 * 主键生成策略
 * @author sihai
 *
 */
public class HibernateTest3 {
	
	@Test
	// 演示increment的问题:
	public void demo1(){
		Session session = HibernateUtils.openSession();
		Transaction tx = session.beginTransaction();
		
		Customer customer = new Customer();
		customer.setName("芙蓉");
		customer.setAge(26);
		
		session.save(customer);
		
		tx.commit();
		session.close();
	}
	
	@Test
	// 演示increment的问题:
	public void demo2(){
		Session session = HibernateUtils.openSession();
		Transaction tx = session.beginTransaction();
		
		Customer customer = new Customer();
		// customer.setId(100);
		customer.setName("sihai");
		customer.setAge(26);
		
		session.save(customer);
		
		tx.commit();
		session.close();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hello-java-maker

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值