代码片段:
package com.shuoeasy.test; import java.util.Arrays; import java.util.List; import org.hibernate.Hibernate; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Unit test for simple App. */ public class AppTest { Session session; SessionFactory sf; @Before public void init() { Configuration conf = new Configuration().configure(); ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); sf = conf.buildSessionFactory((org.hibernate.service.ServiceRegistry) sr); session = sf.openSession(); session.beginTransaction(); System.out.println("init"); } @After public void destory() { session.getTransaction().commit(); session.close(); sf.close(); System.out.println("dectory"); } /** * 插入数据 */ @Test public void testInsert(){ User user = new User(); user.setUserName("张三"); Orders order1 = new Orders(); order1.setTitle("张三的订单1"); order1.setUser(user); Orders order2 = new Orders(); order2.setTitle("张三的订单2"); order2.setUser(user); user.getOrders().add(order1); user.getOrders().add(order2); session.save(user); session.save(order1); session.save(order2); } /** * 分页查询 */ @Test public void testGet(){ Query query = session.createQuery("FROM User"); int pageNo = 2;// 第几页 int pageSize = 3; // 每页大小 query.setFirstResult((pageNo-1)*pageSize); query.setMaxResults(pageSize); List<User> users = query.list(); for(User user : users){ System.out.println(user.getId()); } } /** * 命名查询 */ @Test public void testNameQuery(){ Query query = session.getNamedQuery("getUserList"); query.setInteger("id", 5); List<User> users = query.list(); for(User user : users){ if(user.getOrders() != null){ System.out.println(user.getOrders()); } } } /** * 投影查询,只查询需要的字段,返回数组的形式 */ @Test public void testFieldQuery(){ String hql = "SELECT u.id,u.userName FROM User u WHERE u.id>:id"; Query query = session.createQuery(hql); query.setInteger("id", 5); List<Object []> objs = query.list(); for(Object[] obj : objs){ System.out.println(Arrays.asList(obj)); } } /** * 投影查询,只查询需要的字段,返回对象形式 */ @Test public void testFieldQuery2(){ // User(u.userName) :User类要用相应的构造方法 String hql = "SELECT new User(u.userName) FROM User u WHERE u.id>:id"; Query query = session.createQuery(hql); query.setInteger("id", 5); List<User> users = query.list(); for(User user : users){ System.out.println(Arrays.asList(user)); } } /** * 报表查询,可以用group by ,having */ @Test public void testMax(){ String hql = "SELECT userName,count(userName) FROM User" + " GROUP BY userName" + " HAVING count(userName)>1"; Query query = session.createQuery(hql); List<Object []> objs = query.list(); for(Object[] obj : objs){ System.out.println(Arrays.asList(obj)); } } }