Hibernate4详解

Hibernate4 环境搭建:

 

导入必须的Hibernate4  JAR包
${hibernate_home}\hibernate-release-4.0.0.Final\lib\required\*

 

数据库驱动包(Oracle)
ojdbc14.jar

 

缓存(可选)

${hibernate_home}\hibernate-release-4.0.0.Final\lib\optional\ehcache\*
${hibernate_home}\hibernate-distribution-3.6.0.Final\lib\required\slf4j-api-1.6.1.jar

 

C3P0连接池(可选)

${hibernate_home\hibernate-release-4.0.0.Final\lib\optional\c3p0\*

 

 

编写hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>

		<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
		<property name="hibernate.connection.username">scott</property>
		<property name="hibernate.connection.password">tiger</property>

		<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>

		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.format_sql">true</property>

		<property name="hibernate.hbm2ddl.auto">none</property>

		<property name="hibernate.jdbc.fetch_size">100</property>
		<property name="hibernate.jdbc.batch_size">30</property>

		<!-- 配置二级缓存 -->
	 	<property name="hibernate.cache.use_second_level_cache">true</property>
	 	<property name="hibernate.cache.use_query_cache">true</property>
		<!-- Hibernate4 这里和Hibernate3不一样 要特别注意!!!-->
	 	<property name="hibernate.cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</property>
		
		<!-- Hibernate3 -->
		<!-- <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> -->
		
		<!-- 配置C3P0 -->
		<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
		<property name="hibernate.c3p0.max_size">10</property>
		<property name="hibernate.c3p0.min_size">1</property>
		<property name="hibernate.c3p0.max_statements">3</property>
		<property name="hibernate.c3p0.timeout">30</property>
		<property name="hibernate.c3p0.acquire_increment">1</property>
		<property name="hibernate.c3p0.idle_test_periodt">10</property>
		 
		<mapping resource="org/springfuncs/domain/Customer.hbm.xml" />
		<mapping resource="org/springfuncs/domain/Order.hbm.xml" />
		<mapping resource="org/springfuncs/domain/Emp.hbm.xml" />
		
	</session-factory>
</hibernate-configuration>

实体类和映射文件(没用注解...)

package org.springfuncs.domain;

import java.io.Serializable;
import java.util.Date;

/** 雇员 */
public class Emp implements Serializable {

	private static final long serialVersionUID = 2127136225587213245L;

	private Integer empno; // 雇员编号
	private String ename; // 雇员姓名
	private String job; // 工作
	private Integer mgr; // 上级雇员的编号
	private Date hiredate; // 入职日期
	private Double sal; // 薪水
	private Double comm; // 奖金
	private Integer deptno; // 部门编号

	public Emp() {
	}

	public Emp(Integer empno, String ename, Date hiredate, Double sal) {
		this.empno = empno;
		this.ename = ename;
		this.hiredate = hiredate;
		this.sal = sal;
	}

	// getter and setter

	public String toString() {
		return "Emp [empno=" + empno + ", ename=" + ename + ", job=" + job
				+ ", mgr=" + mgr + ", hiredate=" + hiredate + ", sal=" + sal
				+ ", comm=" + comm + ", deptno=" + deptno + "]";
	}

}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.springfuncs.domain">
	<class name="Emp" table="EMP">
		<cache usage="read-write" /> <!-- 缓存 -->
		<id name="empno" column="EMPNO" length="4" type="integer">
			<generator class="assigned" />
		</id>
		<property name="ename" column="ENAME" length="10" type="string" />
		<property name="job" column="JOB" length="9" type="string" />
		<property name="mgr" column="MGR" length="4" type="integer" />
		<property name="hiredate" column="HIREDATE" type="date" />
		<property name="sal" column="SAL" type="double" />
		<property name="comm" column="COMM" type="double" />
		<property name="deptno" column="DEPTNO" length="2" type="integer" />
	</class>
</hibernate-mapping>

package org.springfuncs.domain;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/** 客户 */
public class Customer implements Serializable {

	private static final long serialVersionUID = -6514738924858633212L;

	private Integer id; //id
	private String name; //姓名
	private Set<Order> orders = new HashSet<Order>(); //其下订单

	public Customer() {
	}

	// getter and setter

	@Override
	public String toString() {
		return "Customer [id=" + id + ", name=" + name + "]";
	}

}

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.springfuncs.domain">
	<class name="Customer" table="CUSTOMERS">
		<cache usage="read-write" /> <!-- 缓存 -->
		<id name="id" column="id" type="integer">
			<generator class="increment" />
		</id>
		<property name="name" column="NAME" length="255" type="string" />
		<set name="orders" inverse="true" cascade="save-update,delete">
			<cache usage="read-write" /> <!-- 缓存 -->
			<key column="CUSTOMER_ID" />
			<one-to-many class="Order" />
		</set>
	</class>
</hibernate-mapping>

package org.springfuncs.domain;

import java.io.Serializable;

/** 订单 */
public class Order implements Serializable {

	private static final long serialVersionUID = -5409386658105657900L;

	private Integer id; // id
	private String orderNumber; // 订单号
	private Customer customer; // 所属客户

	public Order() {
	}

	//getter and setter
	
	@Override
	public String toString() {
		return "Order [id=" + id + ", orderNumber=" + orderNumber + "]";
	}

}

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.springfuncs.domain">
	<class name="Order" table="ORDERS">
		<cache usage="read-write" /> <!-- 缓存 -->
		<id name="id" column="id" type="integer">
			<generator class="increment" />
		</id>
		<property name="orderNumber" column="ORDERNUMBER" length="255" type="string" />
		<many-to-one name="customer" class="Customer" column="CUSTOMER_ID" />
	</class>
</hibernate-mapping>

HibernateUtil.java

package org.springfuncs.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public final class HibernateUtil {

	private static SessionFactory sessionFactory;

	private HibernateUtil() {
	}

	static {
		try {
				
			/** 此方法在Hibernate4中被标记为过时 */
			// sessionFactory = new Configuration().configure().buildSessionFactory();

			/**Hibernate4取得SessionFactory的方法 */
			Configuration cfg = new Configuration().configure();
			ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
			sessionFactory = cfg.buildSessionFactory(serviceRegistry);

		} catch (Throwable e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

HQL

package org.springfuncs.hql;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.springfuncs.domain.Emp;
import org.springfuncs.util.HibernateUtil;

public class TestHql {

	/** 查询全部 (推荐) */
	@Test
	public void test_list() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "from Emp";
		Query query = session.createQuery(hql);
		query.setCacheable(true); // 设置缓存
		List<Emp> list = query.list();
		show(list);
		session.close();
	}

	/** 查询全部 */
	@Test
	public void test_iterator() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "from Emp";
		Query query = session.createQuery(hql);
		Iterator<Emp> it = query.iterate();
		while (it.hasNext()) {
			Emp emp = it.next();
			System.out.println(emp);
		}
		session.close();
	}

	/** 分页查询 */
	// select * from
	// ( select e.*, rownum rn from ( select * from emp ) e where rownum <= 10 )
	// where rn > 1
	@Test
	public void test_pagination() {
		int pageNo = 1; // 当前页数
		int pageSize = 5; // 每页显示条数

		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "from Emp";
		Query query = session.createQuery(hql);
		query.setFirstResult((pageNo - 1) * pageSize);
		query.setMaxResults(pageSize);
		query.setCacheable(true); // 设置缓存
		List<Emp> list = query.list();
		show(list);
		session.close();
	}

	/** 查询结果是唯一值 */
	@Test
	public void test_uniqueResult() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "from Emp where empno=7369";
		Query query = session.createQuery(hql);
		Emp emp = (Emp) query.uniqueResult();
		System.out.println(emp);
		session.close();
	}

	/** 投影查询 */
	@Test
	public void test_projection1() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select empno from Emp"; // 查询单值
		Query query = session.createQuery(hql);
		List<Integer> list = query.list();
		for (Integer empno : list) {
			System.out.println(empno);
		}
		session.close();
	}

	/** 投影查询 */
	@Test
	public void test_projection2() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select empno,ename,hiredate,sal from Emp"; // 查询多值
		Query query = session.createQuery(hql);
		List<Object[]> list = query.list();
		for (Object[] arr : list) {
			System.out.println(arr[0] + "\t" + arr[1] + "\t" + arr[2] + "\t" + arr[3]);
		}
		session.close();
	}

	/** 投影查询 */
	@Test
	public void test_projection3() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select new Emp(empno,ename,hiredate,sal) from Emp"; // 查询多值 封装在一个对象中
		Query query = session.createQuery(hql);
		List<Emp> list = query.list();
		for (Emp emp : list) {
			System.out.println(emp.getEmpno() + "\t" + emp.getEname() + "\t" + emp.getHiredate() + "\t" + emp.getSal());
		}
		session.close();
	}

	/** 投影查询 */
	@Test
	public void test_projection4() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select new Map(empno,ename,hiredate,sal) from Emp"; // map 大小都都可以, 查询多值 封装在一个Map中
		Query query = session.createQuery(hql);
		List<Map> list = query.list();
		for (Map map : list) {
			System.out.println(map.get("0") + "\t" + map.get("1") + "\t" + map.get("2") + "\t" + map.get("3"));
		}
		session.close();
	}

	/** 投影查询 (使用别名) */
	@Test
	public void test_projection5() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select new Map(e.empno as empno ,e.ename as ename ,e.hiredate as hiredate ,e.sal as sal) from Emp as e";
		Query query = session.createQuery(hql);
		List<Map> list = query.list();
		for (Map map : list) {
			System.out.println(map.get("empno") + "\t" + map.get("ename") + "\t" + map.get("hiredate") + "\t" + map.get("sal"));
		}
		session.close();
	}

	/** 去掉重复值 */
	@Test
	public void test_distinct() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select distinct job from Emp";
		Query query = session.createQuery(hql);
		List<String> list = query.list();
		for (String job : list) {
			System.out.println(job);
		}
		session.close();
	}

	/** 条件查询 */
	@Test
	public void test_where1() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();

		// String hql = "from Emp where empno=7369 and ename='SMITH'";
		// String hql = "from Emp where empno=7369 or ename='ALLEN'";
		// String hql = "from Emp where not (ename='SMITH')"; // () 可以不写

		// String hql = "from Emp where sal between 3000 and 5000)";
		// String hql = "from Emp where sal not between 3000 and 5000)";

		// String hql = "from Emp where empno in(7369,7900,7654)";
		// String hql = "from Emp where empno not in(7369,7900,7654)";

		// String hql = "from Emp where ename like 'S%'";
		// String hql = "from Emp where ename not like 'S%'";

		// String hql="from Emp where comm is null";
		// String hql="from Emp where comm is not null";

		// String hql = "from Emp where sal >= 3000 and sal<= 5000)";
		// String hql="from Emp where sal <>3000";
		String hql = "from Emp where sal !=3000";

		Query query = session.createQuery(hql);
		List<Emp> list = query.list();
		show(list);
		session.close();
	}

	/** 条件查询 */
	@Test
	public void test_where2() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();

		String hql = "from Emp where  ename like ?";
		Query query = session.createQuery(hql);
		query.setString(0, "J%");

		// String hql = "from Emp where  ename like :ename";
		// Query query = session.createQuery(hql);
		// query.setString("ename", "J%");

		List<Emp> list = query.list();
		show(list);
		session.close();
	}

	/** 统计函数 */
	@Test
	public void test_statistics1() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select count(*),min(sal),max(sal),avg(sal),sum(sal) from Emp";
		Query query = session.createQuery(hql);
		Object[] values = (Object[]) query.uniqueResult();
		System.out.println("总数:" + values[0]);
		System.out.println("最小值:" + values[1]);
		System.out.println("最大值:" + values[2]);
		System.out.println("平均值:" + values[3]);
		System.out.println("合计:" + values[4]);
		session.close();
	}

	/** 统计函数 */
	@Test
	public void test_statistics2() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select deptno,avg(sal)  from Emp group by deptno having avg(sal)>2000 order by deptno";
		Query query = session.createQuery(hql);
		List<Object[]> list = query.list();
		for (Object[] arr : list) {
			System.out.println("部门编号:" + arr[0] + "\t" + "平均薪资:" + arr[1]);
		}
		session.close();
	}

	/** 使用函数(和底层数据库有关) */
	@Test
	public void test_function() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select to_char(hiredate,'yyyy-mm-dd') from Emp";
		Query query = session.createQuery(hql);
		List<String> list = query.list();
		for (String ename : list) {
			System.out.println(ename);
		}
		session.close();
	}

	/** 排序 */
	@Test
	public void test_orderby() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "from Emp order by job,sal desc";
		Query query = session.createQuery(hql);
		List<Emp> list = query.list();
		show(list);
		session.close();
	}

	// 遍历集合
	private void show(List<Emp> list) {
		for (Emp emp : list) {
			System.out.println(emp);
		}
	}
}

QBC

package org.springfuncs.qbc;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;
import org.springfuncs.domain.Emp;
import org.springfuncs.util.HibernateUtil;

public class TestQBC {

	/** 查询全部 */
	@Test
	public void test_list() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(Emp.class);
		criteria.setCacheable(true); // 设置缓存
		List<Emp> list = criteria.list();
		show(list);
		session.close();
	}

	/** 查询全部 */
	@Test
	public void test_iterator() {
		// 没有iterator
	}

	/** 分页查询 */
	// select * from
	// ( select e.*, rownum rn from ( select * from emp ) e where rownum <= 10 )
	// where rn > 1
	@Test
	public void test_pagination() {
		int pageNo = 1; // 当前页数
		int pageSize = 5; // 每页显示条数

		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(Emp.class);
		criteria.setFirstResult((pageNo - 1) * pageSize);
		criteria.setMaxResults(pageSize);
		criteria.setCacheable(true); // 设置缓存
		List<Emp> list = criteria.list();
		show(list);
		session.close();
	}

	/** 查询结果是唯一值 */
	@Test
	public void test_uniqueResult() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(Emp.class);
		criteria.add(Restrictions.eq("empno", 7369));
		Emp emp = (Emp) criteria.uniqueResult();
		System.out.println(emp);
		session.close();
	}

	/** 投影查询 */
	@Test
	public void test_projection1() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(Emp.class);
		criteria.setProjection(Projections.property("empno"));
		List<Integer> list = criteria.list();
		for (Integer empno : list) {
			System.out.println(empno);
		}
		session.close();
	}

	/** 投影查询 */
	@Test
	public void test_projection2() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(Emp.class);
		ProjectionList projectionList = Projections.projectionList();
		projectionList.add(Projections.property("empno"));
		projectionList.add(Projections.property("ename"));
		projectionList.add(Projections.property("hiredate"));
		projectionList.add(Projections.property("sal"));
		criteria.setProjection(projectionList);
		List<Object[]> list = criteria.list();
		for (Object[] arr : list) {
			System.out.println(arr[0] + "\t" + arr[1] + "\t" + arr[2] + "\t" + arr[3]);
		}
		session.close();
	}

	/** 去掉重复值 */
	@Test
	public void test_distinct() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(Emp.class);
		criteria.setProjection(Projections.distinct(Projections.property("job")));
		List<String> list = criteria.list();
		for (String job : list) {
			System.out.println(job);
		}
		session.close();
	}

	/** 条件查询 */
	@Test
	public void test_where() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(Emp.class);

		// criteria.add(Restrictions.and(Restrictions.eq("empno", 7369), Restrictions.eq("ename", "SMITH")));
		// criteria.add(Restrictions.or(Restrictions.eq("empno", 7369), Restrictions.eq("ename", "ALLEN")));
		// criteria.add(Restrictions.not(Restrictions.eq("ename", "SMITH")));

		// criteria.add(Restrictions.between("sal", 3000.0, 5000.0));
		// criteria.add(Restrictions.not(Restrictions.between("sal", 3000.0, 5000.0)));

		// criteria.add(Restrictions.in("empno", new Object[] { 7369, 7900, 7654 }));
		// criteria.add(Restrictions.not(Restrictions.in("empno", new Object[] { 7369, 7900, 7654 })));

		// criteria.add(Restrictions.like("ename", "S%", MatchMode.START));
		// criteria.add(Restrictions.not(Restrictions.like("ename", "S%", MatchMode.START)));

		// criteria.add(Restrictions.isNull("comm"));
		// criteria.add(Restrictions.not(Restrictions.isNull("comm")));

		// criteria.add(Restrictions.and(Restrictions.ge("sal", 3000.0), Restrictions.le("sal", 5000.0)));
		criteria.add(Restrictions.ne("sal", 3000.0));
		List<Emp> list = criteria.list();
		show(list);
		session.close();
	}

	/** 统计函数 */
	@Test
	public void test_statistics1() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(Emp.class);
		ProjectionList projectionList = Projections.projectionList();
		projectionList.add(Projections.rowCount());
		projectionList.add(Projections.min("sal"));
		projectionList.add(Projections.max("sal"));
		projectionList.add(Projections.avg("sal"));
		projectionList.add(Projections.sum("sal"));
		criteria.setProjection(projectionList);
		Object[] values = (Object[]) criteria.uniqueResult();
		System.out.println("总数:" + values[0]);
		System.out.println("最小值:" + values[1]);
		System.out.println("最大值:" + values[2]);
		System.out.println("平均值:" + values[3]);
		System.out.println("合计:" + values[4]);
		session.close();
	}

	/** 统计函数 */
	// select deptno,avg(sal) from Emp group by deptno having avg(sal)>2000 order by deptno;
	@Test
	public void test_statistics2() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(Emp.class);
		ProjectionList projectionList = Projections.projectionList();
		projectionList.add(Projections.property("deptno"));
		projectionList.add(Projections.avg("sal"));
		projectionList.add(Projections.groupProperty("deptno"));
		criteria.setProjection(projectionList);
		// TODO having 怎么表示 暂时没有找到
		criteria.addOrder(Order.asc("deptno"));
		List<Object[]> list = criteria.list();

		for (Object[] arr : list) {
			System.out.println("部门编号:" + arr[0] + "\t" + "平均薪资:" + arr[1]);
		}
		session.close();
	}

	/** 使用函数(和底层数据库有关) */
	@Test
	public void test_function() {
		// TODO
	}

	/** 排序 */
	@Test
	public void test_orderby() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(Emp.class);
		criteria.addOrder(Order.asc("job"));
		criteria.addOrder(Order.desc("sal"));
		List<Emp> list = criteria.list();
		show(list);
		session.close();
	}

	// 遍历集合
	private void show(List<Emp> list) {
		for (Emp emp : list) {
			System.out.println(emp);
		}
	}
}

QBE

package org.springfuncs.qbe;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.junit.Test;
import org.springfuncs.domain.Emp;
import org.springfuncs.util.HibernateUtil;

public class TestQBE {

	/** QBE查询 适合条件检索 */
	@Test
	public void test_qbe() {
		Emp emp = new Emp();
		emp.setDeptno(10);
		emp.setJob("MANAGER");

		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(Emp.class);
		criteria.add(Example.create(emp));// 注意
		List<Emp> list = criteria.list();
		show(list);
		session.close();
	}

	// 遍历集合
	private void show(List<Emp> list) {
		for (Emp emp : list) {
			System.out.println(emp);
		}
	}
}

Native SQL

package org.springfuncs.sql;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.hibernate.type.StandardBasicTypes;
import org.junit.Test;
import org.springfuncs.domain.Emp;
import org.springfuncs.util.HibernateUtil;

public class TestSql {

	/** 查询全部 */
	@Test
	public void test_sql1() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String sql = "select * from emp";
		SQLQuery query = session.createSQLQuery(sql);
		List<Object[]> list = query.list();
		for (Object[] arr : list) {
			System.out.println(arr[0] + "\t" + arr[1] + "\t" + arr[2] + "\t" + arr[3] + "\t" + arr[4] + "\t" + arr[5] + "\t" + arr[6] + "\t" + arr[7]);
		}
		session.close();
	}

	/** 查询全部 */
	@Test
	public void test_sql2() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String sql = "select * from emp";
		SQLQuery query = session.createSQLQuery(sql);
		query.addScalar("empno", StandardBasicTypes.INTEGER);
		query.addScalar("ename", StandardBasicTypes.STRING);
		query.addScalar("job", StandardBasicTypes.STRING);
		query.addScalar("mgr", StandardBasicTypes.INTEGER);
		query.addScalar("hiredate", StandardBasicTypes.DATE);
		query.addScalar("sal", StandardBasicTypes.DOUBLE);
		query.addScalar("comm", StandardBasicTypes.DOUBLE);
		query.addScalar("deptno", StandardBasicTypes.INTEGER);
		List<Object[]> list = query.list();
		for (Object[] arr : list) {
			System.out.println(arr[0] + "\t" + arr[1] + "\t" + arr[2] + "\t" + arr[3] + "\t" + arr[4] + "\t" + arr[5] + "\t" + arr[6] + "\t" + arr[7]);
		}
		session.close();
	}

	/** 查询全部 */
	@Test
	public void test_sql3() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String sql = "select * from emp";
		SQLQuery query = session.createSQLQuery(sql);
		query.addScalar("empno", StandardBasicTypes.INTEGER);
		query.addScalar("ename", StandardBasicTypes.STRING);
		query.addScalar("job", StandardBasicTypes.STRING);
		query.addScalar("mgr", StandardBasicTypes.INTEGER);
		query.addScalar("hiredate", StandardBasicTypes.DATE);
		query.addScalar("sal", StandardBasicTypes.DOUBLE);
		query.addScalar("comm", StandardBasicTypes.DOUBLE);
		query.addScalar("deptno", StandardBasicTypes.INTEGER);
		query.setResultTransformer(Transformers.aliasToBean(Emp.class));
		List<Emp> list = query.list();
		show(list);
		session.close();
	}

	/** 查询全部 (推荐) */
	@Test
	public void test_sql4() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();

		String sql = "select * from emp";
		SQLQuery query = session.createSQLQuery(sql);
		query.addEntity(Emp.class);

		// String sql = "select {e.*} from emp e";
		// SQLQuery query = session.createSQLQuery(sql);
		// query.addEntity("e", Emp.class);
		query.setCacheable(true); // 设置缓存
		List<Emp> list = query.list();
		show(list);
		session.close();
	}

	/** 条件查询 */
	@Test
	public void test_where() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();

		String sql = "select * from emp where  ename like ?";
		SQLQuery query = session.createSQLQuery(sql);
		query.addEntity(Emp.class);
		query.setString(0, "J%");

		// String sql = "select * from emp where  ename like :ename";
		// SQLQuery query = session.createSQLQuery(sql);
		// query.addEntity(Emp.class);
		// query.setString("ename", "J%");

		List<Emp> list = query.list();
		show(list);
		session.close();
	}

	// 遍历集合
	private void show(List<Emp> list) {
		for (Emp emp : list) {
			System.out.println(emp);
		}
	}
}

CRUD

package org.springfuncs.crud;

import java.io.Serializable;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;
import org.springfuncs.domain.Customer;
import org.springfuncs.util.HibernateUtil;

public class TestCRUD {

	// 添加
	@Test
	public void test_save() {

		Customer customer = new Customer();
		customer.setName("monday");

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		Transaction tx = session.beginTransaction();
		Serializable id = session.save(customer); // 返回OID
		tx.commit();
		session.close();
		System.out.println("id=" + id);
	}

	// 添加
	@Test
	public void test_persist() {
		Customer customer = new Customer();
		customer.setName("monday");

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		Transaction tx = session.beginTransaction();
		session.persist(customer); // 无返回值
		tx.commit();
		session.close();
	}

	// 添加
	@Test
	public void test_saveOrUpdate1() {
		Customer customer = new Customer();
		customer.setName("monday");

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(customer); // OID 为空 执行save操作
		tx.commit();
		session.close();
	}

	// 修改
	@Test
	public void test_saveOrUpdate2() {
		Customer customer = new Customer();
		customer.setName("monday_update");
		customer.setId(5);

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(customer); // OID 为不空 执行update操作
		tx.commit();
		session.close();
	}

	// 修改
	@Test
	public void test_update() {
		Customer customer = new Customer();
		customer.setName("monday_update2");
		customer.setId(5);

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		Transaction tx = session.beginTransaction();
		session.update(customer);
		tx.commit();
		session.close();
	}

	// 修改
	@Test
	public void test_update_hql() {
		String hql = "update Customer set name=? where id=?";
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		Transaction tx = session.beginTransaction();
		Query query = session.createQuery(hql);
		query.setParameter(0, "springfuncs");
		query.setParameter(1, 5);
		query.executeUpdate();
		tx.commit();
		session.close();
	}

	// 删除
	@Test
	public void test_delete() {
		Customer customer = new Customer();
		customer.setId(5);

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		Transaction tx = session.beginTransaction();
		session.delete(customer);
		tx.commit();
		session.close();
	}

	// 删除
	@Test
	public void test_delete_hql() {
		String hql = "delete from Customer where id=?";
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		Transaction tx = session.beginTransaction();
		Query query = session.createQuery(hql);
		query.setParameter(0, 6);
		query.executeUpdate();
		tx.commit();
		session.close();
	}

	// 查询
	@Test
	public void test_get() {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		// Transaction tx = session.beginTransaction();
		Customer customer = (Customer) session.get(Customer.class, 1);
		// tx.commit();
		session.close();
		System.out.println(customer);
	}

	// 查询
	@Test
	public void test_load() {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		// Transaction tx = session.getTransaction();
		// tx.begin();
		Customer customer = (Customer) session.load(Customer.class, 1);
		// tx.commit();

		Hibernate.initialize(customer);
		session.close();
		System.out.println(customer);

		// 或者
		// System.out.println(customer);
		// session.close();
	}
}


关联查询

package org.springfuncs.associated;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.springfuncs.domain.Customer;
import org.springfuncs.domain.Order;
import org.springfuncs.util.HibernateUtil;

public class TestAssociated {

	// 交叉连接(多表的笛卡儿积不常用)
	// select c.*,o.* from customers c, orders o
	@Test
	public void test_cross_join() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "from Customer c , Order o";
		Query query = session.createQuery(hql);
		List<Object[]> list = query.list();
		for (int i = 0; i < list.size(); i++) {
			Object[] obj = (Object[]) list.get(i);
			Customer customer = (Customer) obj[0];
			Order order = (Order) obj[1];
			System.out.println((i + 1) + "---" + customer);
			System.out.println((i + 1) + "---" + order);
		}
		session.close();
	}

	// 内链接
	// select c.* from customers c inner join orders o on c.id=o.customer_id
	// select o.* from orders o where o.customer_id=?
	@Test
	public void test_inner_join() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select c from Customer c inner join c.orders"; // inner 可省略
		Query query = session.createQuery(hql);
		List<Customer> list = query.list();
		showCustomer(list);
		session.close();
	}

	// 左外连接
	// select c.* from customers c left outer join orders o on c.id=o.customer_id
	// select o.* from orders o where o.customer_id=?
	@Test
	public void test_left_outer_join() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select c from Customer c left outer join c.orders"; // outer 可省略
		Query query = session.createQuery(hql);
		List<Customer> list = query.list();
		showCustomer(list);
		session.close();
	}

	// 右连接
	// select c.*, o.* from customers c right outer join orders o on c.id=o.customer_id
	@Test
	public void test_right_outer_join() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "from Customer c right outer join c.orders"; // outer 可省略
		Query query = session.createQuery(hql);
		List<Object[]> list = query.list();
		for (int i = 0; list != null && i < list.size(); i++) {
			Object[] obj = list.get(i);
			Customer customer = (Customer) obj[0];
			Order order = (Order) obj[1];
			System.out.println((i + 1) + "---" + customer);
			System.out.println((i + 1) + "---" + order);
		}
		session.close();
	}

	// 迫切内连接(推荐)
	// select c.*,o.* from customers c inner join orders o on c.id=o.customer_id
	@Test
	public void test_inner_join_fetch() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select c from Customer c inner join fetch c.orders"; // inner 可省略
		Query query = session.createQuery(hql);
		query.setCacheable(true); // 设置缓存
		List<Customer> list = query.list();
		showCustomer(list);
		session.close();
	}

	// 迫切左外连接(推荐)
	// select c.*,o.* from customers c left outer join orders o on c.id=o.customer_id
	@Test
	public void test_left_outer_join_fetch() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select c from Customer c left outer join fetch c.orders"; // outer可省略
		Query query = session.createQuery(hql);
		query.setCacheable(true); // 设置缓存
		List<Customer> list = query.list();
		showCustomer(list);
		session.close();
	}

	// 迫切左外连接(推荐)
	// select c.*, o.* from customers c left outer join orders o on c.id=o.customer_id
	@Test
	public void test_left_outer_join_fetch_QBC() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(Customer.class).setFetchMode("orders", FetchMode.JOIN);
		criteria.setCacheable(true); // 设置缓存
		List<Customer> list = criteria.list();
		showCustomer(list);
		session.close();
	}

	// 打印Order信息
	private void showCustomer(List<Customer> list) {
		for (Customer customer : list) {
			System.out.println(customer);
			if (customer.getOrders() != null && customer.getOrders().size() > 0) {
				Set<Order> orders = customer.getOrders();
				for (Iterator<Order> it = orders.iterator(); it.hasNext();) {
					Order order = it.next();
					System.out.println(order);
				}
			}
		}
	}
}

缓存

package org.springfuncs.cache;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.springfuncs.domain.Emp;
import org.springfuncs.util.HibernateUtil;

public class TestCache {

	// 测试Session缓存
	@Test
	public void test_cache1() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Emp emp1 = (Emp) session.get(Emp.class, 7369);
		Emp emp2 = (Emp) session.get(Emp.class, 7369);
		System.out.println(emp1 == emp2);
	}

	// 测试 EHCache缓存
	// 配置缓存的话,会执行一条SQL,否则是2条SQL
	@Test
	public void test_cache2() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "from Emp";

		Query query = session.createQuery(hql);
		query.setCacheable(true);
		query.list();

		query = session.createQuery(hql);
		query.setCacheable(true);
		query.list();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值