`
derek_z
  • 浏览: 16982 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Hibernate4.1.3

阅读更多

原文:http://1194867672-qq-com.iteye.com/blog/1522906

jar包:

jstl-1.2.jar

ojdbc14.jar

junit-4.4.jar

jboss-loggin-3.1.0.GA.jar

dom4j-1.6.1.jar

xercesImpl.jar

hibernate-c3p0-4.1.2.Final.jar

c3p0-0.9.12.jar

jta.jar

hibernate-ehcache-4.0.0.CR6.jar

ehcache-core-2.6.6.jar

log4j-1.2.15.jar

slf4-log4j12-1.7.2.jar

antlr-2.7.7.jar

hibernate-commons-annotations-4.0.1.Final.jar

hibernate-core-4.1.3.Final.jar

hibernate-jpa-2.0-api-1.0.0.Final.jar

javassist-3.15.0-GA.jar

slf4j-api-1.7.2.jar

 

 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:@10.165.8.65:1521:UTF8</property>
		<property name="hibernate.connection.username">spmsadmin</property>
		<property name="hibernate.connection.password">spmsadmin</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="hbm/User.hbm.xml" />
		<mapping resource="hbm/Class.hbm.xml" />
		
	</session-factory>
</hibernate-configuration>

 User.hbm.xml

<?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="com.base.test.entity.User" table="z_user">
		<cache usage="read-write" /> <!-- 缓存 -->
		<id name="id" column="id" length="4" type="integer">
			 <generator class="increment" />  
		</id>
		<property name="name" column="name" length="10" type="string" />
		<many-to-one name="zclass" class="com.base.test.entity.Class" column="class_id" /> 
	</class>
</hibernate-mapping>

 

Class.hbm.xml

<?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="com.base.test.entity.Class" table="z_class">
		<cache usage="read-write" /> <!-- 缓存 -->
		<id name="id" column="id" length="4" type="integer">
			<generator class="assigned" />
		</id>
		<property name="className" column="class_name" length="10" type="string" />
		<!-- <set name="users" inverse="true" cascade="save-update,delete"> -->
		<set name="users" inverse="true" cascade="save-update,delete">
            <cache usage="read-write" /> <!-- 缓存 -->  
            <key column="id" />  
           <one-to-many class="com.base.test.entity.User" />  
     	</set>  
	</class>
</hibernate-mapping>

 

HibernateUtil.java

package com.base.test.hibernate4;

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) {
			e.printStackTrace();
			throw new ExceptionInInitializerError(e);
		}
	}

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

 

HQL

package com.base.test.hibernate4.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 com.base.test.entity.User;
import com.base.test.hibernate4.HibernateUtil;

public class TestHql {

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


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

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

	/** 查询结果是唯一值 */

	public void test_uniqueResult() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "from User where id=7";
		Query query = session.createQuery(hql);
		User emp = (User) query.uniqueResult();
		System.out.println(emp);
		session.close();
	}

	/** 投影查询 */
	public void test_projection2() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select id,name,zclass.className from User"; // 查询多值
		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" );
		}
		session.close();
	}

	/** 投影查询 */
	
	public void test_projection3() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select new User(id,name) from User"; // 查询多值 封装在一个对象中
		Query query = session.createQuery(hql);
		List<User> list = query.list();
		for (User emp : list) {
			System.out.println(emp.getId() + "\t" + emp.getName() + "\t" + emp.getZclass() + "\t" );
		}
		session.close();
	}

	/** 投影查询 */
	
	public void test_projection4() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "select new Map(id,name) from User"; // 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") );
		}
		session.close();
	}

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

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

	/** 条件查询 */
	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<User> list = query.list();
		show(list);
		session.close();
	}

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

		String hql = "from User where  name like ?";
		Query query = session.createQuery(hql);
		query.setString(0, "%A%");

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

		List<User> 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(id),max(id),avg(id),sum(id) from User";
		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();
	}

	/** 统计函数 */
	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();
	}

	/** 使用函数(和底层数据库有关) */
	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();
	}

	/** 排序 */
	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<User> list = query.list();
		show(list);
		session.close();
	}

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

 

QBC

package com.base.test.hibernate4.hql;


import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
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 com.base.test.entity.User;
import com.base.test.hibernate4.HibernateUtil;

public class TestQBC {
	
	/** 查询全部 */
	@Test
	public void test_QBE() {
		User user = new User();
		user.setId(2);
		
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(User.class);
		criteria.setCacheable(true); // 设置缓存
		criteria.add(Example.create(user));
		List<User> list = criteria.list();
		show(list);
		session.close();
	}

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

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

	/** 分页查询 */
	// select * from
	// ( select e.*, rownum rn from ( select * from emp ) e where rownum <= 10 )
	// where rn > 1

	public void test_pagination() {
		int pageNo = 1; // 当前页数
		int pageSize = 5; // 每页显示条数

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

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

	/** 投影查询 */

	public void test_projection1() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(User.class);
		criteria.setProjection(Projections.property("id"));
		List<Integer> list = criteria.list();
		for (Integer empno : list) {
			System.out.println(empno);
		}
		session.close();
	}

	/** 投影查询 */

	public void test_projection2() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(User.class);
		ProjectionList projectionList = Projections.projectionList();
		projectionList.add(Projections.property("id"));
		projectionList.add(Projections.property("name"));
		criteria.setProjection(projectionList);
		List<Object[]> list = criteria.list();
		for (Object[] arr : list) {
			System.out.println(arr[0] + "\t" + arr[1] + "\t"   );
		}
		session.close();
	}

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

	/** 条件查询 */
	public void test_where() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(User.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<User> list = criteria.list();
		show(list);
		session.close();
	}

	/** 统计函数 */
	public void test_statistics1() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(User.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;
	public void test_statistics2() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(User.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();
	}

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

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

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

 

SQL

package com.base.test.hibernate4.hql;


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 com.base.test.entity.User;
import com.base.test.hibernate4.HibernateUtil;

public class TestSQL {

	/** 查询全部 */

	public void test_sql1() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String sql = "select * from z_user";
		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]);
		}
		session.close();
	}

	/** 查询全部 */
	
	public void test_sql2() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String sql = "select * from z_user";
		SQLQuery query = session.createSQLQuery(sql);
		query.addScalar("id", StandardBasicTypes.INTEGER);
		query.addScalar("name", StandardBasicTypes.STRING);
		query.addScalar("class_id", StandardBasicTypes.INTEGER);
		List<Object[]> list = query.list();
		for (Object[] arr : list) {
			System.out.println(arr[0] + "\t" + arr[1] + "\t" + arr[2] );
		}
		session.close();
	}

	/** 查询全部 */

	public void test_sql3() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String sql = "select * from z_user";
		SQLQuery query = session.createSQLQuery(sql);
		query.addScalar("id", StandardBasicTypes.INTEGER);
		query.addScalar("name", StandardBasicTypes.STRING);
		query.setResultTransformer(Transformers.aliasToBean(User.class));
		List<User> list = query.list();
		show(list);
		session.close();
	}

	/** 查询全部 (推荐) */

	public void test_sql4() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();

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

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

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

		String sql = "select * from z_user where  name like ?";
		SQLQuery query = session.createSQLQuery(sql);
		query.addEntity(User.class);
		query.setString(0, "%A%");

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

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

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

 

CRUD

package com.base.test.hibernate4.hql;


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 com.base.test.entity.User;
import com.base.test.hibernate4.HibernateUtil;

public class TestCRUD {

	// 添加

	public void test_save() {

		User customer = new User();
		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);
	}

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

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

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

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

	// 修改
	
	public void test_saveOrUpdate2() {
		User customer = new User();
		customer.setName("monday_update");
		customer.setId(10);

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

	// 修改
	public void test_update() {
		User customer = new User();
		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();
	}

	// 修改
	
	public void test_update_hql() {
		String hql = "update User 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, 11);
		query.executeUpdate();
		tx.commit();
		session.close();
	}

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

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

	// 删除
	public void test_delete_hql() {
		String hql = "delete from User 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();
	}

	// 查询
	
	public void test_get() {
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		// Transaction tx = session.beginTransaction();
		User customer = (User) session.get(User.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();
		User customer = (User) session.load(User.class, 1);
		// tx.commit();

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

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

 

关联查询

package com.base.test.hibernate4.hql;

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 com.base.test.entity.User;
import com.base.test.entity.Class;
import com.base.test.hibernate4.HibernateUtil;

public class TestAssociated {

	// 交叉连接(多表的笛卡儿积不常用)
	// select c.*,o.* from customers c, orders o

	public void test_cross_join() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		String hql = "from User c , Class 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);
			User customer = (User) obj[0];
			Class order = (Class) 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 User c inner join Class"; // inner 可省略
		Query query = session.createQuery(hql);
		List<User> 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=?
	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<User> list = query.list();
		showCustomer(list);
		session.close();
	}

	// 右连接
	// select c.*, o.* from customers c right outer join orders o on c.id=o.customer_id
	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);
			User customer = (User) obj[0];
			Class order = (Class) 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
	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<User> list = query.list();
		showCustomer(list);
		session.close();
	}

	// 迫切左外连接(推荐)
	// select c.*,o.* from customers c left outer join orders o on c.id=o.customer_id
	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<User> list = query.list();
		showCustomer(list);
		session.close();
	}

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

	// 打印Order信息
	private void showCustomer(List<User> list) {
		for (User customer : list) {
			System.out.println(customer);
			if (customer.getZclass() != null ) {
				Class c = customer.getZclass();
				System.out.println(c.getClassName());
			}
		}
	}
}

 

缓存

package com.base.test.hibernate4.hql;


import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Test;

import com.base.test.entity.User;
import com.base.test.hibernate4.HibernateUtil;

public class TestCache {

	// 测试Session缓存
	
	public void test_cache1() {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		User emp1 = (User) session.get(User.class, 1);
		User emp2 = (User) session.get(User.class, 1);
		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 User";

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

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

 

分享到:
评论

相关推荐

    hibernate 4.1.3

    hibernate 4.1.3 hibernate 最新版

    Hibernate-release-4.1.3

    《Hibernate 4.1.3:企业级持久化框架的里程碑》 Hibernate 4.1.3 是一个关键版本的Java对象关系映射(ORM)框架,它在Java开发领域中占据着重要的地位。这个版本的发布标志着Hibernate的又一次重大改进,为开发者...

    hibernate开发jar包集合

    Hibernate是一款强大的Java持久化框架,它为Java开发者提供了一种对象关系映射工具,使得开发者可以使用面向对象的方式来操作数据库,极大地简化了数据库操作。在Java应用开发中,特别是企业级应用开发,Hibernate被...

    整合struts2.3.4+spring3.1.1+hibernae4.1.3+JPA

    标题 "整合struts2.3.4+spring3.1.1+hibernate4.1.3+JPA" 暗示了一个常见的企业级Java应用开发集成框架的搭建过程。这个集成环境将Struts2作为MVC框架,Spring作为服务层管理和依赖注入容器,Hibernate作为持久层...

    ProxoolConnectionProvider.java

    解决hibernate4.1.3 中直接使用proxool会出现 url cannot be null的错误,用来替代 hibernate-proxool.jar文件中的同名类,可以修改包名和类名到自己的包下使用。

    整合Struts2.3.20 Spring4.1.3 Hibernate4.3.7 所需jar包

    以上就是关于整合Struts2.3.20、Spring4.1.3和Hibernate4.3.7所需jar包的详细说明。通过这些组件的组合,你可以构建出一个高效、可维护的Java Web应用程序。记得在实际项目中,根据具体需求可能还需要添加其他的库或...

    Postman_v4.1.3.rar

    这可能意味着Postman v4.1.3对Java开发者有优化的特性,比如支持Java相关的API框架,如Spring、Hibernate等,或者是对Java开发环境的集成有特殊照顾。 【压缩包子文件的文件名称列表】中的"123"并没有给出实际的...

    spring-framework-4.1.3.RELEASE

    3. **数据访问集成**:Spring Data模块支持多种数据存取技术,如JPA、Hibernate、MyBatis等。4.1.3.RELEASE增强了对这些框架的整合,提供了更丰富的查询方法和更好的异常处理。 4. **Web MVC**:Spring MVC是构建...

    spring framework 4.1.3

    6. **Data Access/Integration模块**:JDBC、ORM(Object-Relational Mapping)和OXM(Object-XML Mapping)都有所增强,比如与各种持久化技术(如Hibernate、JPA、MyBatis等)的集成更加紧密。 7. **测试支持**:...

    spring4.1.3All.jar

    此外,Spring的数据访问层包括了对JDBC、ORM(Object-Relational Mapping)框架如Hibernate、MyBatis的支持。4.1.3版本加强了数据访问的事务管理,提供了更好的数据源抽象和多数据源支持。 标签“最新spring”表明...

    Struts2.5.5+Spring4.1.3+Hibernate4.3.11+Mysql5.1.40

    网上找了很多的Struts2+spring4+hibernate4+myql5.1的代码,但是总是找不到,为了更好地理解和学习,手动搞一个,同时上传出来发给大家下载!绝对亲测! 该部分的代码示例,简单的描述了一个基本的框架搭建过程,...

    Spring Framework 4.1.3 Reference Manual 参考介绍手册chm版

    4. **数据访问**:Spring提供了多种数据访问技术的集成,如JDBC、ORM(Hibernate、MyBatis)和NoSQL数据库,简化了数据层的开发。 5. **Spring Boot**:虽然不在4.1.3版本中,但它是Spring的重要扩展,它简化了...

    hibernate-c3p0-4.1.3.Final.jar

    hibernate-c3p0.jar 各个版本,免费下载 C3PO JDBC 连接池工具

    hibernate_reference使用指南全

    - **4.1.3 优先使用非 final 类(可选)** 非 final 类可以方便地实现继承和覆盖,这有助于实现更复杂的映射逻辑。 - **4.1.4 声明持久化字段的 getter 和 setter 方法(可选)** 尽管 Hibernate 支持字段访问...

    hibernate 3.2中文手册 中文文档

    - **4.1.3 使用非final的类(可选)** - 解释为什么持久化类不建议使用final关键字修饰。 - **4.1.4 为持久化字段声明访问器(accessors)和是否可变的标志(mutators)(可选)** - 指出为了方便Hibernate操作,持久化...

    Spring4.1.3

    Spring4.1.3 对 JPA、Hibernate、MyBatis 等ORM框架提供了支持,简化了数据库操作。同时,其事务管理功能允许开发者声明性地控制事务边界,确保数据的一致性。 4. **Web MVC** Spring Web MVC 框架在4.1.3版本中...

    Hibernate Annotations 中文文档

    4.1.3. 错误信息 4.1.4. 编写你自己的约束 4.1.5. 注解你的领域模型 4.2. 使用验证器框架 4.2.1. 数据库schema层次验证 4.2.2. Hibernate基于事件的验证 4.2.3. 程序级验证 4.2.4. 验证信息 5. Hibernate与...

    Spring Framework 4.1.3 API Documentation参考文档CHM版

    4. **数据访问**:Spring提供了JDBC抽象层,简化了数据库操作,同时支持ORM(Object-Relational Mapping)框架,如Hibernate和JPA,方便进行对象持久化。 5. **事务管理**:Spring的事务管理支持编程式和声明式两种...

    hibernate annotation 中文文档

    - **4.1.3 错误信息**:可以通过 `@Constraint` 注解的 `message` 属性来定义约束违反时的错误消息。 - **4.1.4 编写你自己的约束**:可以自定义约束注解并实现相应的验证逻辑。 - **4.1.5 注解你的领域模型**:...

    Hibernate+中文文档

    4.1.3. 使用非final的类 (可选) 4.1.4. 为持久化字段声明访问器(accessors)和是否可变的标志(mutators)(可选) 4.2. 实现继承(Inheritance) 4.3. 实现equals()和hashCode() 4.4. 动态模型(Dynamic models) 4.5...

Global site tag (gtag.js) - Google Analytics