Hibernate-框架基础

Hibernate-基础



1.常用接口

  • configuration接口

    用于加载Hibernate的配置文件及启动Hibernate,创建SessionFactory实例。

  • SessionFactory接口

    用于对Hibernate进行初始化操作。通常一个项目只有一个SessionFactory对象,对应一个数据库。

1.1、Session接口

操作数据库的核心对象,负责管理所有与持久化相关的(CRUD)操作。

Session中的常用方法:

save() 用于执行添加对象操作
update() 用于执行修改对象操作
saveOrUpdate() 用于执行添加或修改对象操作
delete() 用于执行删除对象操作
get() 根据主键查询数据
load() 根据主键查询数据
createQuery() 用于数据库操作对象
createSQLQuery() 用于数据库操作对象
  • Transaction接口

    用于对事务的相关操作,如:事务提交、回滚等。

  • Query接口

    用于对数据库的查询操作。其中,面向对象查询语言HQL通过此接口实现。

  • Criteria接口

    用于对数据的查询操作。为Hibernate的QBC查询方式提供了方法。

2.hibernate实例状态

  • 瞬时态(Transient)
  • 持久态(Persistent)
  • 托管态(Detached)

3.hibernate配置


Hibernate主要通过:

  • 持久化类(*.java)

  • Hibernate映射文件(*.hbm.xml)

  • Hibernate配置文件(*.cfg.xml)

与数据库进行交互。

3.1、持久化类

持久化类是操作对象,用于描述数据表的结构。

package model;
/**
 * 学生持久化类
 */
public class Student {
	private Integer id;			//学号
	private String name;		//姓名
	private Integer age;		//年龄
	private boolean sex;		//性别
	private String description;	//描述信息
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public boolean isSex() {
		return sex;
	}
	public void setSex(boolean sex) {
		this.sex = sex;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
}
3.2、映射文件

映射文件指持久化类与数据表之间的映射关系。

<?xml version="1.0"?>
<!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="model.Student" table="tb_student_update">
		<id name="id">
			<generator class="native"/>
		</id>
		<property name="name" length="50" not-null="true"/>
		<property name="age"/>
		<property name="sex">
			<column name="sex" sql-type="int"/>
		</property>
		<property name="description" type="text"/>
	</class>
</hibernate-mapping>
3.3、配置文件

配置文件用于指定Hibernate的属性信息,如:数据库的连接信息等。

<?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="connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<!-- 数据库连接的URL -->
	<property name="connection.url">
		jdbc:mysql://localhost:3306/db_database13
	</property>
	<!-- 数据库连接用户名 -->
	<property name="connection.username">root</property>
	<!-- 数据库连接密码 -->
	<property name="connection.password"></property>
	<!-- Hibernate方言 -->
	<property name="dialect">
		org.hibernate.dialect.MySQLDialect
	</property>
	<!-- 打印SQL语句 -->
	<property name="show_sql">true</property>
	<property name="format_sql">false</property>
	
	<!-- 对映射文件中指定的各表自动建表结构。update:当数据表存在且与映射文件匹配时不建表,否则重新建表 -->
	<property name="hibernate.hbm2ddl.auto">update</property>
	
	<!-- 开启二级缓存 -->
	<property name="hibernate.cache.use_second_level_cache">
		true
	</property>
	<!-- 指定缓存产品提供商 -->
	<property name="hibernate.cache.region.factory_class">
		org.hibernate.cache.ehcache.EhCacheRegionFactory
	</property>

	<!-- 映射文件  -->
	<mapping resource="employee/Employee.hbm.xml" />
	<mapping resource="model/Medicine.hbm.xml" />
	<mapping resource="model/Customer.hbm.xml" />
	<mapping resource="model/Student.hbm.xml" />

	<!-- 指定二级缓存应用到的实体对象 -->
	<class-cache class="model.Medicine" usage="read-write" />

</session-factory>
</hibernate-configuration>
3.4、hibernate初始化
  1. 调用Configuration对象的configure()方法,加载hibernate配置信息。
  2. 调用Configuration对象的buildSessionFactory()方法,创建SessionFactory对象。
  3. 调用SessionFactory对象的openSession()方法,获取Session对象。
  4. 调用Session对象的close()方法,关闭Session。
package util;
/*
 * 初始化类,用于创建SessionFactory对象,该对象的创建比较耗时,一般只创建一次
 * */
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	private static SessionFactory sessionFactory = null; // SessionFactory对象
	// 静态块
	static {
		try {
			Configuration cfg = new Configuration().configure(); // 加载Hibernate配置文件
			sessionFactory = cfg
					.buildSessionFactory(new ServiceRegistryBuilder().applySettings(cfg.getProperties())
							.buildServiceRegistry());
		} catch (Exception e) {
			System.err.println("创建会话工厂失败");
			e.printStackTrace();
		}
	}

	/**
	 * 获取Session
	 * 
	 * @return Session
	 * @throws HibernateException
	 */
	public static Session getSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}
		return session;
	}

	/**
	 * 重建会话工厂
	 */
	public static void rebuildSessionFactory() {
		try {
			Configuration cfg = new Configuration().configure(); // 加载Hibernate配置文件
			sessionFactory = cfg
					.buildSessionFactory(new ServiceRegistryBuilder().applySettings(cfg.getProperties())
							.buildServiceRegistry());
		} catch (Exception e) {
			System.err.println("创建会话工厂失败");
			e.printStackTrace();
		}
	}

	/**
	 * 获取SessionFactory对象
	 * 
	 * @return SessionFactory对象
	 */
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * 关闭Session
	 * 
	 * @throws HibernateException
	 */
	public static void closeSession() throws HibernateException {
		Session session = (Session) threadLocal.get();
		threadLocal.set(null);
		if (session != null) {
			session.close(); // 关闭Session
		}
	}
}

4.hibernate持久化


4.1、添加数据
  • save()方法,返回生成的标识。

public Serializable save(Object object)throws HibernateException

4.2、查询数据
  • get()方法,返回实际对象。
  • load()方法,返回对象的代理,只有在被调用时,hibernate才发出SQL语句查询对象。

public Object get(Class class,Serializable id)throws HibernateException
public Object load(Class class,Serializable id)throws HibernateException

4.3、删除数据
  • delete()方法。如要删除的对象不在Session管理中,先加载对象,使其处于持久态,然后再删除对象。

public void delete(Object object)throws HibernateException

4.4、修改数据
  • 自动更新:
  • 手动更新:update()方法。

public void update(Object object)throws HibernateException

5.hibernate事务管理


try{
    //获取Session
    session = Hibernate.getSession();
    //开启事务
    session.beginTransaction();
    ...
    /*持久化操作*/
    ...
    //提交事务
    session.getTransaction().commit();
}catch(Exception e){
    e.printStackTrace();
    //事务回滚
    session.getTransaction().rollback();
}finally{
    //关闭session
    session.close();
}

6.HQL基本语法


HQL是面向对象查询语言,HQL语句对大小写敏感。

select "属性名" from "对象"
where "条件"
group by "属性名" having "条件"
order by "属性名" desc/asc

例:select * from User u where u.id>5 order by u.id asc


6.1、实体对象查询
  • 实体对象查询

    • Query query=session.createQuery("from User");
      
  • 条件查询及别名使用

    • Query query=session.createQuery("from User u where u.id = 1");
      
6.1、HQL语句动态赋值查询
  • 按参数位置查询

在HQL语句中使用"?"定义参数位置,通过Query对象的setXxx()方法进行赋值。

String hql="from User u where u.name=?"
Query query=session.createQuery(hql);
query.setString(0,"haha");
list=query.list();
  • 按参数名称查询

在HQL语句中定义参数名称(参数名称由:和自定义参数名组合),通过Query对象的setParameter()方法进行赋值。

String hql="from User u where u.name=:name"
Query query=session.createQuery(hql);
query.setParameter("name","haha");
list=query.list();
6.2、HQL语句动态实例查询
  • 投影查询:只对需要的属性查询
String hql="select id,name from User"
  • 动态实例查询:投影查询返回的是Object类型数组,失去了对象状态,破坏了数据的封装性。将检索出的数据重新封装到一个实体的实例中,就是动态实例查询。
String hql="select new User(id,name) from User"
6.3、分页查询

Query接口中,提供了两个方法

  • setFirstResult(int firstResult)
    • 设定从哪个对象开始查询,参数firstResult表示对象在查询结果中的索引(索引从0开始)。
  • setMaxResult(int maxResult)
    • 设定一次返回多少个对象。通常与setFirstResult(int firstResult)方法结合使用。默认返回结果中的所有对象。

更新中。。。

posted @ 2021-01-09 15:51  jt_coder  阅读(48)  评论(0)    收藏  举报