Hibernate OID、导航图、HQL、SQL、QBC查询方式示例

Hibernate OID、导航图、HQL、SQL、QBC查询方法示例

本案例使用的hibernate版本为  hibernate-release-5.2.10.Final 

为了测试,本案例在mysql数据库中创建了一个db数据库。

示例描述一个案例,在网上购物系统中一个用户可以有多个订单,所以用户和订单属于一对多关系,在cn.sz.pojo包下面是他们的实体并用注解进行了映射配置。cn.sz.pojo包下面的User.java和User.hbm.xml用于HQL查询时利用查询名称实现查询时使用。

创建一个java项目:项目的结构如下:(lib文件夹用于存放jar包)

Hibernate OID、导航图、HQL、SQL、QBC查询方式示例_第1张图片

lib目录下则是hibernate5需要的jar包(注需要将jar加载到项目中:选中jar包右键 --》BuildPath--》Add to Build Path)
Hibernate OID、导航图、HQL、SQL、QBC查询方式示例_第2张图片
log4j.properties为日志配置文件(需要加载配置junit),此项目可以不需要日志,使用日志只是为了观察方便。
注:junit配置可以参考 http://blog.csdn.net/benxiaohai888/article/details/78231911

由于在主配置文件配置了字段创建数据表的配置,所以第一次加载时就会自动创建数据表

配置的代码:


update


接下来是示例代码:

1、主配置文件 hibernate.cfg.xml copy




	
		
		
		com.mysql.jdbc.Driver
		
		jdbc:mysql://localhost:3306/db?characterEncoding=utf8
		
		root
		
		

		
		org.hibernate.dialect.MySQL5Dialect

		

		

		
		true
		
		true
		
		update
		
		thread
		
		4

		
		
		
		
		
	

	



2、工具类(获取Session)HibernateUtil.java

[java] view plain copy
  1. package cn.sz.utils;  
  2.   
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.hibernate.cfg.Configuration;  
  6.   
  7. public class HibernateUtil {  
  8.     public static Session getSession() {  
  9.         Session session = null;  
  10.         // 创建一个读取主配置文件的对象  
  11.         Configuration cfg = new Configuration();  
  12.         // 读取主配置文件  
  13.         cfg.configure();  
  14.         // 创建Session工厂  
  15.         SessionFactory factory = cfg.buildSessionFactory();  
  16.         // 打开Session  
  17.         // session = factory.openSession();  
  18.         // 如果在主配置文件将session绑定到线程中,所以可以从线程中取出session  
  19.         session = factory.getCurrentSession();  
  20.         return session;  
  21.     }  
  22. }  

3、日志文件 log4j.properties

[plain] view plain copy
  1. log4j.rootLogger=DEBUG,console,FILE  
  2. log4j.appender.console=org.apache.log4j.ConsoleAppender  
  3. log4j.appender.console.threshold=INFO  
  4. log4j.appender.console.layout=org.apache.log4j.PatternLayout  
  5. log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%5p] - %c -%F(%L) -%m%n  
  6. log4j.appender.FILE=org.apache.log4j.RollingFileAppender  
  7. log4j.appender.FILE.maxBackupIndex=100  
  8. ##log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender   
  9. log4j.appender.FILE.Append=true  
  10. log4j.appender.FILE.File=c:/error1.log  
  11. log4j.appender.FILE.Threshold=INFO  
  12. log4j.appender.FILE.layout=org.apache.log4j.PatternLayout  
  13. log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%5p] - %c -%F(%L) -%m%n  
  14. log4j.appender.FILE.MaxFileSize=1MB  
4、实体类User.java(sn.sz.pojo包下面)

package cn.sz.pojo;

import java.util.Date;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "h_user")
public class User {
	// 基于外键的方式时,使用的配置(一对一关系)

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer userId;

	private String userName;
	private Date birthday;

	// 一对多关系(用户和订单),添加cascade配置并不能实现一的一方维护关系
	@OneToMany(targetEntity = Orders.class, mappedBy = "user", cascade = CascadeType.ALL)
	private Set orderss;

	public User() {
	}

	public User(String userName, Date birthday) {
		this.userName = userName;
		this.birthday = birthday;
	}

	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public Set getOrderss() {
		return orderss;
	}

	public void setOrderss(Set orderss) {
		this.orderss = orderss;
	}

	@Override
	public String toString() {
		return "User [userId=" + userId + ", userName=" + userName + ", birthday=" + birthday + "]";
	}

}

5、实体类 Orders.java

package cn.sz.pojo;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "h_orders")
public class Orders {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer ordersId;
	private String ordersName;

	// 一对多关系(用户和订单)
	@ManyToOne(cascade = CascadeType.ALL)
	@JoinColumn(name = "userId")
	@Basic(fetch = FetchType.LAZY) //// 添加此项配置并不能实现一的一方维护关系
	private User user;

	public Integer getOrdersId() {
		return ordersId;
	}

	public void setOrdersId(Integer ordersId) {
		this.ordersId = ordersId;
	}

	public String getOrdersName() {
		return ordersName;
	}

	public void setOrdersName(String ordersName) {
		this.ordersName = ordersName;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@Override
	public String toString() {
		return "Orders [ordersId=" + ordersId + ", ordersName=" + ordersName + "]";
	}

}

6、实体类User.java(sn.sz.vo下面)


package cn.sz.vo;

import java.util.Date;

public class User {
	private Integer userId;
	private String userName;
	private Date birthday;

	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

}
7、映射文件 User.hbm.xml




	
	
		
		
			
			
		
		
		
		
	

	
	
	

	
	
	


测试类:

OID查询、导航图查询、HQL、测试类:

package cn.sz.test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;

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

import com.mysql.fabric.xmlrpc.base.Array;

import cn.sz.pojo.Orders;
import cn.sz.pojo.User;
import cn.sz.utils.HibernateUtil;

public class QueryTest {

	@Test
	// 添加测试数据
	public void testSave() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		// 创建一个用户
		User u = new User();
		u.setUserName("张三");
		u.setBirthday(new Date());

		Orders orders1 = new Orders();
		orders1.setOrdersName("衣服");
		orders1.setUser(u);

		Orders orders2 = new Orders();
		orders2.setOrdersName("武器");
		orders2.setUser(u);

		// 继续创建一个用户
		User u2 = new User();
		u2.setUserName("李四");
		u2.setBirthday(new Date());

		Orders orders3 = new Orders();
		orders3.setOrdersName("水果");
		orders3.setUser(u2);

		Orders orders4 = new Orders();
		orders4.setOrdersName("鞋子");
		orders4.setUser(u2);

		// 继续创建一个用户
		User u3 = new User();
		u3.setUserName("王五");
		u3.setBirthday(new Date());

		Orders orders5 = new Orders();
		orders5.setOrdersName("水果");
		orders5.setUser(u3);

		session.save(orders1);
		session.save(orders2);
		session.save(orders3);
		session.save(orders4);
		session.save(orders5);
		session.save(u);
		session.save(u2);
		session.save(u3);
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// OID查询方式 get()方法和load() 方法
	public void testOIDQuery() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		User u1 = session.get(User.class, 1);
		System.out.println(u1.toString());

		User u2 = session.load(User.class, 1);
		System.out.println(u2.toString());

		Set orderss = u2.getOrderss();// 导航图查询方式
		for (Orders orders : orderss) {
			System.out.println(orders.toString());
		}

		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery1() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		// HQL 查询user表的所有记录
		String hql = "FROM User u";
		Query query = session.createQuery(hql);
		List list = query.list();
		for (Object o : list) {
			System.out.println(o.toString());
		}

		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery2() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		// HQL 查询user表的编号大于1的记录
		String hql = "FROM User u WHERE u.userId > 1";
		Query query = session.createQuery(hql);
		List list = query.list();
		for (Object o : list) {
			System.out.println(o.toString());
		}

		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery3() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		String c = "李";
		// HQL 查询user表的姓名中有李记录
		String hql = "FROM User u WHERE u.userName like '%" + c + "%'";
		Query query = session.createQuery(hql);
		List list = query.list();
		for (Object o : list) {
			System.out.println(o.toString());
		}

		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery4() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		String c = "李";
		// HQL 查询user表的id为1的记录(只有一个)
		String hql = "FROM User u WHERE u.userId=1";
		Query query = session.createQuery(hql);
		Object result = query.uniqueResult();
		System.out.println(result);
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery5() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL 查询user表的id为1在1-2范围,姓名为李四的记录
		String hql = "FROM User u WHERE u.userId in(1,2) AND u.userName='李四'";
		Query query = session.createQuery(hql);
		List list = query.list();
		for (Object o : list) {
			System.out.println(o.toString());
		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery6() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL 查询user表的所有记录,按姓名降序排序
		String hql = "FROM User u ORDER BY u.userName DESC";
		Query query = session.createQuery(hql);
		List list = query.list();
		for (Object o : list) {
			System.out.println(o.toString());
		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery7() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL 统计user表的记录总数
		String hql = "SELECT COUNT(*) FROM User u";
		Query query = session.createQuery(hql);
		Object result = query.uniqueResult();
		System.out.println(result.toString());

		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery8() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL查询不同用户的订单数目
		String hql = "SELECT COUNT(*) FROM Orders o GROUP BY o.user";
		Query query = session.createQuery(hql);
		List list = query.list();
		for (Object o : list) {
			System.out.println(o.toString());
		}

		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery9() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL查询--查询user的姓名
		String hql = "SELECT u.userName FROM User u";
		Query query = session.createQuery(hql);
		List list = query.list();
		for (Object o : list) {
			System.out.println(o.toString());
		}

		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery10() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL查询--查询user的姓名和生日
		String hql = "SELECT u.userName,u.birthday FROM User u";
		Query query = session.createQuery(hql);
		List list = query.list();
		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery11() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL查询--查询user的姓名和生日
		String hql = "SELECT new User(u.userName,u.birthday) FROM User u";
		Query query = session.createQuery(hql);
		List list = query.list();
		for (Object o : list) {

			System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery12() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL查询--查询user的姓名和生日,实现分页
		String hql = "SELECT new User(u.userName,u.birthday) FROM User u";
		Query query = session.createQuery(hql);
		// 设置分页
		query.setFirstResult(0);
		query.setMaxResults(2);

		List list = query.list();
		for (Object o : list) {

			System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery13() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL查询--设置查询条件,采用占位符的方案(占位符从0开始)
		String hql = "SELECT u.userName,u.birthday FROM User u WHERE u.userName=?";
		Query query = session.createQuery(hql);
		query.setParameter(0, "李四");

		List list = query.list();
		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery14() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL查询--设置查询条件,采用占位符的方案(占位符从0开始)
		String hql = "SELECT u.userName,u.birthday FROM User u WHERE u.userName like ?";
		Query query = session.createQuery(hql);
		// query.setParameter(0, "%李%");
		String c = "李";
		query.setParameter(0, "%" + c + "%");

		List list = query.list();
		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery15() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL查询--设置查询条件,采用占位符的方案(占位符从0开始)
		String hql = "SELECT u.userName,u.birthday FROM User u WHERE u.userId IN(?,?)";
		Query query = session.createQuery(hql);
		query.setParameter(0, 1);
		query.setParameter(1, 2);

		List list = query.list();
		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery16() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL查询--设置查询条件,采用查询变量方案
		String hql = "SELECT u.userName,u.birthday FROM User u WHERE u.userName=:name";
		Query query = session.createQuery(hql);
		query.setParameter("name", "王五");

		List list = query.list();
		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery17() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL查询--设置查询条件,采用查询变量方案
		String hql = "SELECT u.userName,u.birthday FROM User u WHERE u.userId BETWEEN :start AND :end";
		Query query = session.createQuery(hql);
		query.setParameter("start", 1);
		query.setParameter("end", 3);

		List list = query.list();
		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery18() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL查询--设置查询条件,采用查询变量方案
		String hql = "SELECT u.userName,u.birthday FROM User u WHERE u.userId BETWEEN :start AND :end";
		Query query = session.createQuery(hql);
		query.setParameter("start", 1);
		query.setParameter("end", 3);

		List list = query.list();
		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery19() throws ParseException {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL查询--设置查询条件,采用查询变量方案
		String hql = "SELECT u.userName,u.birthday FROM User u WHERE u.birthday BETWEEN :start AND :end";
		Query query = session.createQuery(hql);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date d1 = sdf.parse("2017-10-23 0:0:0");
		Date d2 = sdf.parse("2017-10-25 0:0:0");
		query.setParameter("start", d1);
		query.setParameter("end", d2);

		List list = query.list();
		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery20() throws ParseException {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL查询--设置查询条件,采用查询变量方案
		/*
		 * 在HQL中,占位符的个数不能确定,换句话说假设从页面传入的同一个条件值, 在不同请求时所传值的个数不同,导致占位符的个数不能确定
		 */
		String hql = "SELECT u.userName,u.birthday FROM User u WHERE u.userId in(:ids)";
		Query query = session.createQuery(hql);

		query.setParameterList("ids", new Object[] { 1, 2 });

		List list = query.list();
		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式(连接查询)
	public void testHQlQuery21() throws ParseException {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL查询--连接查询
		String hql = "SELECT u.userName,u.birthday FROM User u,Orders o WHERE u.userId =o.user";
		Query query = session.createQuery(hql);

		List list = query.list();
		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery22() throws ParseException {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// HQL查询--连接查询
		// String hql = "SELECT u.userName,u.birthday,o.ordersId,o.ordersName
		// FROM User u JOIN Orders o
		// ON u.userId =o.user";
		// String hql = "SELECT u.userName,u.birthday,o.ordersId,o.ordersName
		// FROM Orders o JOIN o.user
		// u";
		String hql = "SELECT o.user.userName,o.user.birthday,o.ordersId,o.ordersName FROM Orders o";
		Query query = session.createQuery(hql);

		List list = query.list();
		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery23() throws ParseException {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// 连接查询---内连接查询,迫切内连接查询,fetch作用是实现迫切连接查询
		// 迫切查询和非迫切查询区别是非迫切的查询结果是数组形式,迫切查询结果是对象形式
		// String hql = "SELECT u.userId,u.userName,o.ordersId,o.ordersName FROM
		// User u INNER JOIN FETCH Orders o ON u.userId=o.user";
		String hql = "select u.userId,u.username,o.ordersId,o.ordersName from Orders o join fetch o.user u";
		Query query = session.createQuery(hql);

		List list = query.list();
		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	// HQL查询方式
	public void testHQlQuery24() throws ParseException {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// 连接查询---内连接查询,迫切内连接查询,fetch作用是实现迫切连接查询
		// 迫切查询和非迫切查询区别是非迫切的查询结果是数组形式,迫切查询结果是对象形式
		// 迫切查询只有迫切内连接查询和迫切左外连接查询
		// String hql = "SELECT u.userId,u.userName,o.ordersId,o.ordersName FROM
		// User u left fetch Orders o ON u.userId=o.user";
		String hql = "SELECT u.userId,u.username,o.ordersId,o.ordersName FROM User u right join Orders o on u.userId=o.user";
		Query query = session.createQuery(hql);

		List list = query.list();
		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	public void test25() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		// 利用查询名称实现查询
		Query query = session.createNamedQuery("queryUser");
		List list = query.list();
		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();

	}

	@Test
	public void test26() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		// 利用查询名称实现查询
		Query query = session.createNamedQuery("queryUser2");
		List list = query.list();
		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);

		}
		session.getTransaction().commit();
		session.close();

	}

}


QBC查询测试类:

package cn.sz.test;

import java.util.Arrays;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

import cn.sz.pojo.User;
import cn.sz.utils.HibernateUtil;

public class CriteriaTest {
	@Test
	public void test1() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		// 认识QBC查询
		Criteria criteria = session.createCriteria(User.class);
		List list = criteria.list();
		for (Object object : list) {
			System.out.println(object);
		}

		session.getTransaction().commit();
		session.close();
	}

	@Test
	public void test2() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		// 认识QBC查询--查询一个结果
		Criteria criteria = session.createCriteria(User.class);

		criteria.add(Restrictions.eqOrIsNull("userId", 1));
		Object o = criteria.uniqueResult();
		System.out.println(o);
		session.getTransaction().commit();
		session.close();
	}

	@Test
	public void test3() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		// 认识QBC查询--查询一个结果
		Criteria criteria = session.createCriteria(User.class);
		// 分页操作
		criteria.setFirstResult(0);
		criteria.setMaxResults(2);

		List list = criteria.list();
		for (Object object : list) {
			if (object.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) object));
			else
				System.out.println(object);
		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	public void test4() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		// 离线查询--创建一个离线查询对象
		DetachedCriteria dCriteria = DetachedCriteria.forClass(User.class);
		Criteria criteria = dCriteria.getExecutableCriteria(session);
		criteria.add(Restrictions.in("userId", 1, 2, 3));
		List list = criteria.list();

		for (Object object : list) {
			if (object.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) object));
			else
				System.out.println(object);
		}
		session.getTransaction().commit();
		session.close();
	}
}

SQL查询测试类:

package cn.sz.test;

import java.util.Arrays;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.junit.Test;

import cn.sz.utils.HibernateUtil;

public class SQLTest {
	@Test
	@SuppressWarnings("rawtypes") // 去除警告提示
	public void test1() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// 查询所有的用户
		String sql = "select * from h_user";
		SQLQuery query = session.createSQLQuery(sql);

		List list = query.list();

		for (Object o : list) {
			// 如果是数组则转换为字符串打印输出
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				// 否则调用对象的toString() 方法打印输出
				System.out.println(o);
		}
		session.getTransaction().commit();
		session.close();
	}

	@Test
	@SuppressWarnings("rawtypes")
	public void test2() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();

		// 查询id为1的用户
		String sql = "select * from h_user where userid=1";
		SQLQuery sqlQuery = session.createSQLQuery(sql);
		// 结果为唯一值
		Object o = sqlQuery.uniqueResult();
		if (o.getClass().isArray())
			System.out.println(Arrays.toString((Object[]) o));
		else
			System.out.println(o);
		session.getTransaction().commit();
		session.close();
	}

	@Test
	@SuppressWarnings("rawtypes")
	public void test3() {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		// 分页查询
		String sql = "select * from h_user";
		SQLQuery sqlQuery = session.createSQLQuery(sql);
		// 设置查询起始位置
		sqlQuery.setFirstResult(0);
		// 设置查询记录数
		sqlQuery.setMaxResults(3);

		List list = sqlQuery.list();

		for (Object o : list) {
			if (o.getClass().isArray())
				System.out.println(Arrays.toString((Object[]) o));
			else
				System.out.println(o);
		}

		session.getTransaction().commit();
		session.close();
	}
}
 
  
注:我们在利用查询名称实现查询的时候需要使用cn.sz.vo下面的User实体类和User.hbmxml映射文件,还需要注释主配置中的下面代码,


 

并打开




你可能感兴趣的:(Hibernate)