Hibernate基础查询总结

以学生班级为例:学生班级使用多对一关系

1.学生实体类:

package com.xintoucloud.hibernate_query;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
//外置命名查询NamedQuery注解
@NamedQuery(name="queryAll",query="from Student")
@Entity@Table(name="t_student")
public class Student {
	@Id@GeneratedValue(strategy=GenerationType.IDENTITY)
//学生ID
	private int sid;
//学生名字
	private String sname;
//学生邮箱
	private String email;
//学生成绩
	private int grade;
//学生年龄
	private int age;
	
	@ManyToOne(fetch=FetchType.LAZY)
	@Cascade(CascadeType.SAVE_UPDATE)
	private Clazz clazz;
	public Student() {}
	public Student(int sid,int grade) {
		this.sid=sid;
		this.grade=grade;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public int getGrade() {
		return grade;
	}
	public void setGrade(int grade) {
		this.grade = grade;
	}
	public Clazz getClazz() {
		return clazz;
	}
	public void setClazz(Clazz clazz) {
		this.clazz = clazz;
	}
	public int getSid() {
		return sid;
	}
	public void setSid(int sid) {
		this.sid = sid;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
}

2.班级实体类:Clazz

package com.xintoucloud.hibernate_query;

import java.util.Set;

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="t_clazz")
public class Clazz {
	@Id@GeneratedValue(strategy=GenerationType.IDENTITY)
//班级ID
	private int cid;
//班级名字
	private String cname;
	@OneToMany(mappedBy="clazz")
	private Set students;
	public int getCid() {
		return cid;
	}
	public void setCid(int cid) {
		this.cid = cid;
	}
	public String getCname() {
		return cname;
	}
	public void setCname(String cname) {
		this.cname = cname;
	}
	public Set getStudents() {
		return students;
	}
	public void setStudents(Set students) {
		this.students = students;
	}
	
}

3.tablecreate:

package com.xintoucloud.hibernate_query;
	import java.util.EnumSet;
	import org.hibernate.boot.Metadata;
	import org.hibernate.boot.MetadataSources;
	import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
	import org.hibernate.service.ServiceRegistry;
	import org.hibernate.tool.hbm2ddl.SchemaExport;
	import org.hibernate.tool.schema.TargetType;

	public class TableCreate { 

		public static void main(String[] args){  
			ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
		    Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
	          
	        //工具类  
	        SchemaExport export=new SchemaExport();  
	        //打到控制台,输出到数据库  
	        //第一个参数 输出DDL到控制台
	        //第二个参数 执行DDL语言创建表
	        export.create(EnumSet.of(TargetType.DATABASE), metadata); 
	    }  

	}


4.配置hibernate.cfg.xml







    

        
        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/hibernate-query
        root
        123456

        
        5

        
        org.hibernate.dialect.MySQL55Dialect

        
        true

        
        

    

5.hibernateTest测试类:

package com.xintoucloud.hibernate_query;

import java.util.List;
import java.util.Random;

import javax.persistence.NamedQuery;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.xintoucloud.hibernate_query.Clazz;


public class hibernateTest {
	public SessionFactory sessionFactory;
	@Before
	public void setUp() throws Exception {
		// A SessionFactory is set up once for an application!
		final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
				.configure() // configures settings from hibernate.cfg.xml
				.build();
		try {
			sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
		}
		catch (Exception e) {
			// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
			// so destroy it manually.
			StandardServiceRegistryBuilder.destroy( registry );
		}
	}
	@After
	public void tearDown() throws Exception {
		if ( sessionFactory != null ) {
			sessionFactory.close();
		}
	}
	@Test
	//批量添加测试数据,5个班级,每个班级20个学生
	public void save() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			for(int i=1;i<6;i++) {
				Clazz clazz=new Clazz();
				clazz.setCname("计科"+i+"班");
				session.save(clazz);
				for(int j=1;j<21;j++) {
					Student student=new Student();
					student.setSname("班级"+clazz.getCname()+"的"+"学生"+j);
					student.setEmail("班级"+clazz.getCname()+"的"+"学生"+j+"的邮箱");
					student.setClazz(clazz);
					student.setAge(new Random().nextInt(25)+10);
					student.setGrade(new Random().nextInt(90)+10);
					session.save(student);
				}
			}
			session.getTransaction().commit();
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//1.通过id查询(get方法)
	public void query1() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
		Student student=session.get(Student.class, 88);
		System.out.println("学生姓名:"+student.getSname()+",学生班级:"+student.getClazz().getCname()+",学生成绩:"+student.getGrade()+""+",学生年龄:"+student.getAge()+",学生邮箱:"+student.getEmail());
		
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//2.通过id查询(load方法)
	public void query2() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			Student student=session.load(Student.class, 88);
			System.out.println("学生姓名:"+student.getSname()+",学生班级:"+student.getClazz().getCname()+",学生成绩:"+student.getGrade()+""+",学生年龄:"+student.getAge()+",学生邮箱:"+student.getEmail());
			
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//3.通过HQL查询(createquery方法)
	public void query3() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			@SuppressWarnings("unchecked")
			List students=session.createQuery("from Student").list();
			for (Student student2 : students) {
				System.out.println("学生姓名:"+student2.getSname()+",学生班级:"+student2.getClazz().getCname()+",学生成绩:"+student2.getGrade()+""+",学生年龄:"+student2.getAge()+",学生邮箱:"+student2.getEmail());
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	
	@Test
	//4.查询部分属性(返回一个object数组,而不是Student集合)
	public void query4() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			@SuppressWarnings("unchecked")
			List students=session.createQuery("select sname,grade from Student").list();
			for (Object[] objects : students) {
				String sanme=(String) objects [0];
				int grade=(int) objects [1];
				System.out.println("学生姓名:"+sanme+",学生分数:"+grade);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//5.查询部分属性(返回一个Student集合)
	public void query5() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			@SuppressWarnings("unchecked")
			List students=session.createQuery("select new Student(sid,grade) from Student").list();
			for (Student stu : students) {
				System.out.println("学生姓名:"+stu.getSid()+",学生分数:"+stu.getGrade());
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//6.参数绑定(一个参数)
	public void query6() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			Student stu=(Student) session.createQuery("from Student where id=?0").setParameter(0, 56).getSingleResult();
				System.out.println("学生姓名:"+stu.getSname()+",学生分数:"+stu.getGrade());
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//7.参数绑定(多个参数,设置多个参数要用连续的正整数表示,起始数不限制)
	public void query7() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			@SuppressWarnings("unchecked")
			List stus=(List) session.createQuery("from Student where id > ?0 and grade > ?1").setParameter(0, 90).setParameter(1, 60).list();
			for (Student student : stus) {
				System.out.println("学生姓名:"+student.getSname()+",学生分数:"+student.getGrade()+",学生年龄:"+student.getAge());
			}	
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//8.参数绑定:名称
	public void query8() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			Object[] object=new Object[3];
			object[0]=12;
			object[1]=22;
			object[2]=32;
			@SuppressWarnings("unchecked")
			List stus=(List) session.createQuery("from Student where id in (:ids)").setParameterList("ids", object).list();
			for (Student student : stus) {
				System.out.println("学生ID"+student.getSid()+",学生姓名:"+student.getSname()+",学生分数:"+student.getGrade()+",学生年龄:"+student.getAge());
			}	
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//9.聚合函数(count()返回值为long,返回的是一条记录,所以要用uniqueResult()方法)
	public void query9() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			Long count= (Long) session.createQuery("select count(*) from Student ").uniqueResult();
				System.out.println("数量"+count);
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//10.聚合函数(sum()返回值为long,返回的是一条记录,所以要用uniqueResult()方法)
	public void query10() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			Long count= (Long) session.createQuery("select sum(grade) from Student ").uniqueResult();
			System.out.println("总分数:"+count);
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//11.聚合函数(avg()返回值为Double,返回的是一条记录,所以要用uniqueResult()方法)
	public void query11() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			//查询学号大于90同学的平均分
			Double count= (Double) session.createQuery("select avg(grade) from Student where id > ?0").setParameter(0, 90).uniqueResult();
			System.out.println("平均分:"+count);
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//12.聚合函数(max()返回值为int,返回的是一条记录,所以要用uniqueResult()方法)
	public void query12() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			//查询学号大于90同学的最大值
			Object[] object=new Object[10];
			object[0]=91;
			object[1]=92;
			object[2]=93;
			object[3]=94;
			object[4]=95;
			object[5]=96;
			object[6]=97;
			object[7]=98;
			object[8]=99;
			object[9]=100;
			Integer count= (Integer) session.createQuery("select max(grade) from Student where id in (:ids)").setParameterList("ids", object).uniqueResult();
			System.out.println("最大值为:"+count);
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//13.聚合函数(min()返回值为intger,返回的是一条记录,所以要用uniqueResult()方法)
	public void query13() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			//查询学号大于90同学的最大值
			Object[] object=new Object[10];
			object[0]=91;
			object[1]=92;
			object[2]=93;
			object[3]=94;
			object[4]=95;
			object[5]=96;
			object[6]=97;
			object[7]=98;
			object[8]=99;
			object[9]=100;
			Integer count= (Integer) session.createQuery("select min(grade) from Student where id in (:ids)").setParameterList("ids", object).uniqueResult();
			System.out.println("最小值为:"+count);
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//14.分组查询
	public void query14() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			//查询各个班级的平均分
			@SuppressWarnings("unchecked")
			List list=session.createQuery("select st.clazz.cname,avg(grade) from Student st group by st.clazz having avg(grade)<50").list();
			for (Object[] objects : list) {
				String cname=(String) objects[0];
				Double grade=(Double) objects[1];
				System.out.println("cname"+cname+"平均值为为:"+grade);
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//15.子查询
	public void query15() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			@SuppressWarnings("unchecked")
			//查询最高分的学生
			List stus=session.createQuery("from Student where grade=(select max(grade) from Student)").list();
			for (Student stu : stus) {
				System.out.println("名字:"+stu.getSname()+",分数:"+stu.getGrade());
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//16.执行批量更新操作(更新完要提交事务commit())
	public void query16() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			//将学号大于92的成绩都更新为100
			int rows=session.createQuery("update Student st set st.grade=?0 where st.sid>?1").setParameter(0, 100).setParameter(1, 92).executeUpdate();
				System.out.println(rows);
				session.getTransaction().commit();
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//17.执行批量删除操作(更新完要提交事务commit())
	public void query17() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			//将学号大于92的学生都删除
			int rows=session.createQuery("delete Student st where st.sid>?1").setParameter(1, 92).executeUpdate();
			System.out.println(rows);
			session.getTransaction().commit();
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//18.条件查询,criteria查询
	public void query18() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			//查询学号大于20小于30的学生
			@SuppressWarnings("deprecation")
			List students=session.createCriteria(Student.class).add(Restrictions.lt("sid", 30)).add(Restrictions.gt("id", 20)).list();
			for (Student student : students) {
				System.out.println(student.getSid()+","+student.getSname());
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//19.条件查询,criteria查询,结果集排序
	public void query19() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			//查询学号大于20小于30的学生,按照名字降序排列
			@SuppressWarnings("deprecation")
			List students=session.createCriteria(Student.class).add(Restrictions.lt("sid", 30)).add(Restrictions.gt("id", 20)).addOrder(Order.desc("sname")).list();
			for (Student student : students) {
				System.out.println(student.getSid()+","+student.getSname());
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//20.条件查询,criteria查询,关联
	public void query20() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			//查询学号大于20小于30的学生,成绩大于80
			@SuppressWarnings("deprecation")
			List students=session.createCriteria(Student.class).add(Restrictions.lt("sid", 30)).add(Restrictions.gt("id", 20)).addOrder(Order.desc("sname")).add(Restrictions.gt("grade", 80)).list();
			for (Student student : students) {
				System.out.println(student.getSid()+","+student.getSname()+","+student.getGrade());
			}	
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//21.本地SQL查询,返回原生实体对象
	public void query21() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			//查询
			@SuppressWarnings("unchecked")
			List students=session.createSQLQuery("select * from t_student").addEntity(Student.class).list();
			for (Student student : students) {
				System.out.println(student.getSid()+","+student.getSname()+","+student.getGrade());
			}	
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//22.外置命名查询(实体类中需添加注解@NamedQuery(name="queryAll",query="from Student"))
	public void query22() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			//查询
			@SuppressWarnings("unchecked")
			List students=session.createNamedQuery("queryAll").list();
			for (Student student : students) {
				System.out.println(student.getSid()+","+student.getSname()+","+student.getGrade());
			}	
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//批量添加测试数据,添加5个没有学生的班级
	public void save2() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			for(int i=1;i<6;i++) {
				Clazz clazz=new Clazz();
				clazz.setCname("空班级"+i);
				session.save(clazz);
			}
			session.getTransaction().commit();
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//批量添加测试数据,添加10个没有班级的学生
	public void save3() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			for(int j=1;j<11;j++) {
				Student student=new Student();
				student.setSname("游离"+"的"+"学生"+j);
				student.setEmail("学生"+j+"的邮箱");
				student.setAge(new Random().nextInt(25)+10);
				student.setGrade(new Random().nextInt(90)+10);
				session.save(student);
			}
			session.getTransaction().commit();
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	@Test
	//23.内连接(只返回符合链接条件的记录)
	public void query23() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			//查询
			@SuppressWarnings("unchecked")
			List list= (List) session.createQuery("select st.sname,st.clazz.cname from Student st inner join st.clazz").list();
			for (Object[] cbj : list) {
				String sname=(String) cbj[0];
				String cname=(String) cbj[1];
				System.out.println(sname+","+cname);
			}	
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	//24.左外连接(即返回符合条件的记录,也会返回左表中不符合连接条件的记录,右表的列值使用null填充)
	@Test
	public void query24() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			//查询
			@SuppressWarnings("unchecked")
			List list= (List) session.createQuery("select st.sname,c.cname from Student st left join st.clazz c").list();
			for (Object[] cbj : list) {
				String sname=(String) cbj[0];
				String cname=(String) cbj[1];
				System.out.println(sname+","+cname);
			}	
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	//25.右外连接(即返回符合条件的记录,也会返回右表中不符合连接条件的记录,左表的列值使用null填充)
	@Test
	public void query25() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			//查询
			@SuppressWarnings("unchecked")
			List list= (List) session.createQuery("select st.sname,c.cname from Student st right join st.clazz c").list();
			for (Object[] cbj : list) {
				String sname=(String) cbj[0];
				String cname=(String) cbj[1];
				System.out.println(sname+","+cname);
			}	
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
	//26.对象导航查询
	@Test
	public void query26() {
		Session session=sessionFactory.openSession();
		session.beginTransaction();
		try {
			//查询
			@SuppressWarnings("unchecked")
			List list= (List) session.createQuery("select st.sname,st.clazz.cname from Student st").list();
			for (Object[] cbj : list) {
				String sname=(String) cbj[0];
				String cname=(String) cbj[1];
				System.out.println(sname+","+cname);
			}	
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
	}
}

总结:

1.通过Id查询:get()方法直接全部加载,load()方法有需要再去加载,通过debug调试才可以看到区别

2.HQL查询:查询全部返回的是Student集合,查询部分属性(返回一个object数组,而不是Student集合)

3.参数绑定:(多个参数,设置多个参数要用连续的正整数表示,起始数不限制)

4.聚合函数:(count()返回值为long,sum()返回值为long,avg()返回值为Double,max()返回值为int,min()返回值为intger,这些返回的是一条记录,所以要用uniqueResult()方法)

5.分组查询:select st.clazz.cname,avg(grade) from Student st group by st.clazz having avg(grade)<50

6.子查询:from Student where grade=(select max(grade) from Student)

7.批量更新/删除操作:update/delete Student st set st.grade=?0 where st.sid>?1,最后返回值为int row,受影响行数。

8.条件查询,criteria查询:session.createCriteria(Student.class).add(Restrictions.lt("sid", 30)).add(Restrictions.gt("id", 20)).list()

9:本地SQL查询:返回原生实体对象:session.createSQLQuery("select * from t_student").addEntity(Student.class).list();

10:外置命名查询(实体类中需添加注解@NamedQuery(name="queryAll",query="from Student"))

session.createNamedQuery("queryAll").list();

11:内连接:内连接(只返回符合链接条件的记录)返回object数组

session.createQuery("select st.sname,st.clazz.cname from Student st inner join st.clazz").list();

12:左外连接:(即返回符合条件的记录,也会返回左表中不符合连接条件的记录,右表的列值使用null填充)

session.createQuery("select st.sname,c.cname from Student st left join st.clazz c").list();

13:右外连接:(即返回符合条件的记录,也会返回右表中不符合连接条件的记录,左表的列值使用null填充)

session.createQuery("select st.sname,c.cname from Student st right join st.clazz c").list();

 

 

你可能感兴趣的:(hibernate)