AppTest.java:
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 testDistinct(){ String hql = "SELECT DISTINCT u.userName FROM User u"; Query query = session.createQuery(hql); List<String > names = query.list(); for(String name : names){ System.out.println(Arrays.asList(name)); } } /** * 左外连接查询,如果实体有关联的表,虽然查询出来了,但是不会加载到对象中, * 等用的时候重新查数据库,这样影响性能。 * 可以使用LEFT JOIN、 INNER JOIN、RIGHT JOIN */ @Test public void testJoin(){ User user = new User(); user.setId(1); user.setUserName("张三"); String hql = "SELECT o FROM Orders o LEFT JOIN o.user WHERE o.user=:user"; Query query = session.createQuery(hql); query.setEntity("user", user); List<Orders> orders = query.list(); for(Orders order : orders){ System.out.println(order.getId()); System.out.println(order.getUser()); // 虽然join时候已经重新根据用户的id查一次数据库 } } /** * 迫切左外连接查询,使用"FETCH",如果实体有关联的表,一次性加载数据。 * 可以使用LEFT JOIN、 INNER JOIN、RIGHT JOIN */ @Test public void testJoinFetch(){ User user = new User(); user.setId(1); user.setUserName("张三"); String hql = "FROM Orders o LEFT JOIN FETCH o.user WHERE o.user=:user"; Query query = session.createQuery(hql); query.setEntity("user", user); List<Orders> orders = query.list(); for(Orders order : orders){ System.out.println(order.getId()); System.out.println(order.getUser()); } } }