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