`
周一Monday
  • 浏览: 346363 次
  • 来自: 北京
社区版块
存档分类
最新评论

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();
	}
}

 

 

 

 

 

分享到:
评论
5 楼 QMonkey 2015-08-21  
xy2401 写道
没有找到我想要的
分页查询这里
  System.out.println("不是强制转换出错吧");
        
  int totalRows =((Integer) criteria.setProjection
  (Projections.rowCount()).uniqueResult());  
 
 
  System.out.println("总查询数目:"+totalRows);

会报错,可能bibernate4改成发挥long了?



hibernate4的返回是long型。
4 楼 happylouis 2013-08-14  
哇塞,楼主真是好心人呀,总结的噶好
3 楼 周一Monday 2013-03-21  
an_it_eye_2012 写道
建议生成文档可下载


谢谢你的建议!
对于Hibernate4 自己掌握的还很少,做成文档怕误人子弟。这里写就是自己学习的一些总结,能为他人起到“友情提示”的作用,就没白写。
2 楼 an_it_eye_2012 2013-03-21  
建议生成文档可下载
1 楼 xy2401 2012-07-07  
没有找到我想要的
分页查询这里
  System.out.println("不是强制转换出错吧");
        
  int totalRows =((Integer) criteria.setProjection
  (Projections.rowCount()).uniqueResult());  
 
 
  System.out.println("总查询数目:"+totalRows);

会报错,可能bibernate4改成发挥long了?

相关推荐

    Hibernate知识点总结

    ### Hibernate知识点总结 #### 一、Hibernate概述 Hibernate是一个开源的ORM(Object Relational Mapping,对象关系映射)框架,用于Java应用与关系型数据库之间的交互。它通过使用描述对象和数据库之间映射的元...

    Hibernate4总结文档

    《Hibernate4总结文档》 Hibernate4作为一款强大的Java对象关系映射框架,简化了数据库操作,使得开发者可以更专注于业务逻辑而不是数据库层面的细节。本文将深入探讨Hibernate4的配置和使用,帮助开发者更好地理解...

    springMVC4+Hibernate4整合例子

    总结来说,"springMVC4+Hibernate4整合例子"是一个典型的Java Web项目,通过Maven管理依赖,Eclipse作为开发工具,使用SpringMVC处理请求,Hibernate进行数据操作。整个过程涉及到大量的配置和代码编写,但一旦设置...

    spring4+hibernate4整合例子

    总结来说,这个"spring4+hibernate4整合例子"涵盖了以下几个关键点: 1. Spring4的依赖注入和面向切面编程 2. Hibernate4的对象关系映射 3. Spring4对Hibernate4的事务管理支持 4. 使用JUnit进行测试驱动开发 5. ...

    Hibernate课程的总结

    **标题:“Hibernate课程的总结”** 在学习Hibernate框架的过程中,我们深入探讨了它在Java企业级应用中的核心地位。Hibernate作为一个强大的对象关系映射(ORM)工具,它简化了数据库与Java对象之间的交互,消除了...

    hibernate学习总结文档

    4. **删除(Delete)**:`delete()` 方法用于从数据库中移除对象。 **查询机制** - **HQL(Hibernate Query Language)**:类似于 SQL,但面向对象,支持更高级的查询功能,如连接、子查询和聚合函数。 - **...

    Hibernate4 必备包

    总结来说,"Hibernate4 必备包"包含了运行和开发基于Hibernate4的应用程序所需的基本组件。这些组件涵盖了ORM核心、数据查询、事务管理、关联映射等多个方面,为开发者提供了强大且灵活的数据库操作工具。通过合理...

    hibernate文档总结,技术汇总,PDF版的,hibernate简明参考文档

    以下是关于Hibernate的一些关键知识点: 1. **JDBC对比Hibernate**: 传统的JDBC操作涉及手动建立和管理数据库连接,而Hibernate通过提供更高层次的抽象,自动处理这些细节,使得开发人员可以更专注于业务逻辑。 2....

    hibernate关联关系总结

    4. **多对多关联(ManyToMany)** 多对多关联表示两个实体之间可能存在多个匹配,例如学生可以选择多门课程,课程也可以被多个学生选择。这种关系需要一个中间表来存储双方的映射关系。在Hibernate中,使用@...

    Hibernate学习笔记与总结

    **Hibernate学习笔记与总结** Hibernate 是一款开源的对象关系映射(ORM)框架,它为Java开发者提供了一种在关系数据库上操作对象数据的便捷方式。本文将深入探讨Hibernate的核心概念、配置、实体类、映射文件、...

    hibernate4.x jar

    3. **references_single**: 这可能是Hibernate的一些参考文档或指南,帮助开发者理解和使用Hibernate4.x,对于学习和解决问题非常有帮助。 三、实战应用: 在实际开发中,Hibernate4.x常用于企业级应用,例如电子...

    hibernate知识点总结

    4. **实体类和映射**: - **实体类**:是业务逻辑中的对象,通过@Entity注解标识,@Id表示主键字段。 - **映射文件**:描述了实体类与数据库表的对应关系,包括属性映射、关联映射等。 - **注解映射**:使用Java...

    Hibernate 经典总结

    4. 市场占有率高:Hibernate 在 Java 开发领域占有相当大的市场份额,是许多企业级应用的首选持久层框架。 【Hibernate 3.2 文件结构】 1. doc:包含 Hibernate 3.2 的 API 文档和相关说明。 2. eg:官方提供的...

    hibernate技术研究对比总结

    **HIBERNATE技术总结** Hibernate 是一个流行的 Java 应用程序框架,它提供了一种对象关系映射(ORM)解决方案,将数据库操作转化为面向对象的编程。此文档旨在研究和对比 Hibernate 技术的不同方面,帮助开发者更...

    hibernate4 所有jar包

    Hibernate 4 是一款广泛使用的Java持久化...总结,这个压缩包包含了使用Hibernate 4所需的所有jar包,覆盖了ORM的各个方面。开发者可以基于这些库快速搭建和扩展数据持久化层,高效地管理数据库操作,提升开发效率。

    hibernate面试题总结

    - **SQL**:可以直接执行SQL查询,但失去了Hibernate的一些优势,如自动类型转换和对象化结果集。 - **Criteria(QBC - Query By Criteria)**:基于对象的查询方式,提供了动态构建查询的能力,更加灵活,但可能...

    hibernate4框架学习笔记

    总结来说,Hibernate4是一个强大的ORM框架,它简化了Java应用与数据库之间的交互,通过对象持久化和映射机制,使得开发者可以专注于业务逻辑的实现,而不是底层的数据库操作。理解并熟练运用Hibernate,将极大提升...

Global site tag (gtag.js) - Google Analytics