Hibernate(六)
三套查询之HQL查询
hql语句(面向):类 对象 属性
package com.rong.entity.hql; public class User { public User(int id, String name) {
super();
this.id = id;
this.name = name;
}
public User() {
super();
}
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.rong.entity.hql; import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id; @Entity
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package com.rong.entity.hql; import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
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;
//hql语句(面向):类 对象 属性
public class TestHQL {
SessionFactory sessionFactory;
Session session;
Transaction transaction;
@Before
public void init() {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory=configuration.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
transaction = session.beginTransaction(); }
//插入数据
@Test
public void addData(){
Student student=null;
for(int i=1;i<=100;i++){
student=new Student();
student.setAge(i);
student.setName("先生"+i);
session.save(student);
}
}
//查询所有的学生 (所有列)
@Test
public void test1(){
Query query = session.createQuery("from Student");//Student是类名
List<Student> list = query.list();
System.out.println(list.size());
for (Student student : list) {
System.out.println(student.getAge()+student.getName());
}
}
//查询所有的学生当中的某一列
@Test
public void test2(){
//Student是类名,name是Student类的成员变量名
Query query = session.createQuery("select s.name from Student s");
List<Student> list = query.list();
System.out.println(list);
}
//查询所有学生中的多列
@Test
public void test3(){
Query query = session.createQuery("select s.name,s.age from Student s");
//Query query = session.createQuery("select name,age from Student s");
List<Object[]> list = query.list();
//list集合的每一个元素都是数组,而每一个数组都是由name和age构成
for (Object[] objects : list) {
for (Object object : objects) {
System.out.print(object);
}
System.out.println();
}
}
//分页查询
@Test
public void test4(){
//Query query = session.createQuery("select s from Student s");
Query query = session.createQuery("from Student");
query.setFirstResult(0);//设置从哪里开始
query.setMaxResults(3);//分页的条目
List<Student> list = query.list();
for (Student student : list) {
System.out.println(student.getAge()+student.getName());
}
}
//查询所有的学生的某些字段 返回值是map类型,即获取List<Map<String,Object>>结果
@Test
public void test5(){
//这个是没有别名的
//Query query = session.createQuery("select new map(s.name,s.age) from Student s");
//这个有别名的(修改key的值 就需要增加别名)
Query query = session.createQuery("select new map(s.name as name,s.age as age) from Student s");
List<Map<String,Object>> list = query.list();
//结果 key是 从0 开始的
//System.out.println(list);//[{0=先生1, 1=1}, {0=先生2, 1=2}, {0=先生3, 1=3}......]
System.out.println(list);//[{name=先生1, age=1}, {name=先生2, age=2}......]
for (Map<String, Object> map : list) {
Set<Entry<String, Object>> set = map.entrySet();
Iterator<Entry<String, Object>> iterator = set.iterator();
while(iterator.hasNext()){
Entry<String, Object> entry = iterator.next();
System.out.println(entry.getKey()+entry.getValue());
}
}
}
//查询所有的学生的某些字段,返回值是list类型,即获取List<List<Object>>结果
@Test
public void test6(){
Query query = session.createQuery("select new list(s.name,s.age) from Student s");
List<List<Object>> list = query.list();
for (List<Object> li : list) {
for (Object object : li) {
System.out.print(object);
}
System.out.println();
}
}
//查询student表,返回值是User,User类必须要有public User(int id, String name)的构造方法!!!
@Test
public void test7(){
Query query = session.createQuery("select new com.rong.entity.hql.User(s.id,s.name) from Student s");
List<User> list = query.list();
for (User user : list) {
System.out.println(user.getId()+user.getName());
}
} @After
public void destroy(){
transaction.commit();
session.close();
sessionFactory.close();
}
}
关联(持久化类)与连接(数据库表)
package com.rong.entity.myhql; import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne; @Entity
public class Teacher {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int tid;
private String tname;
@OneToOne(targetEntity=Student.class,fetch=FetchType.LAZY,mappedBy="teacher")
private Student student;
public int getTid() {
return tid;
}
public void setTid(int tid) {
this.tid = tid;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
}
package com.rong.entity.myhql; 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.OneToOne; @Entity
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
private int age;
@OneToOne(targetEntity=Teacher.class,fetch=FetchType.LAZY)
@JoinColumn(name="t_id",referencedColumnName="tid",unique=true)
private Teacher teacher;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}
package com.rong.entity.myhql; import java.util.List; import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
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;
//hql语句(面向):类 对象 属性
public class TestHQL {
SessionFactory sessionFactory;
Session session;
Transaction transaction;
@Before
public void init() {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory=configuration.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
transaction = session.beginTransaction(); }
//插入数据
@Test
public void addData(){
Student student=null;
Teacher teacher=null;
for(int i=1;i<=20;i++){
teacher=new Teacher();
teacher.setTname("老师"+i);
student=new Student();
student.setAge(i);
student.setName("学生"+i);
student.setTeacher(teacher);
session.save(teacher);
session.save(student);
}
}
//1.隐式关联(不需要写join语句)
//查询时,关联的属性是一个持久化类. @ManyToOne、@OneToOne
@Test
public void test1(){
Query query = session.createQuery("select s from Student s where s.teacher.tid=?");
query.setParameter(0, 3);
List<Student> list = query.list();
for(int i=0;i<list.size();i++){
Student student = list.get(i);
//3学生333老师3
System.out.println(student.getId()+student.getName()+student.getAge()
+student.getTeacher().getTid()+student.getTeacher().getTname());
} }
//2.显示关联(需要写join语句)
//注意:若使用@OneToMany、@ManyToMany查询时,关联的属性是一个Set集合. 这里使用@OneToOne
@Test
public void test2(){
//注意: inner join 后边的类 要写 属性 inner join s.teacher
Query query = session.createQuery("select s from Student s inner join s.teacher t where t.tid=?");
query.setParameter(0, 18);
Object uniqueResult = query.uniqueResult();
Student student=(Student)uniqueResult;
//18学生1818老师18
System.out.println(student.getId()+student.getName()+student.getAge()
+student.getTeacher().getTname());
}
//3.抓取连接(查询延迟的属性)
//查询时,关联的属性配置了延迟加载的,但本次查询要查询出来.join fetch 关联的属性
@Test
public void test3(){
//查两次,要配置延迟加载
//这里肯定是把Student查出来了。但是Student中的teacher属性还没有查数据库
//因为Student的teacher属性配置了懒加载fetch=FetchType.LAZY
Query query = session.createQuery("select s from Student s");
List<Student> list = query.list();
Student student = list.get(0);
//要真正使用Teacher了。所以要去查数据库。
System.out.println(student.getTeacher().getTname()); System.out.println("=======================================");
//查一次,要配置延迟加载
//就是teacher属性虽然是懒加载的,但是我们通过join fetch直接把懒加载的属性全部查出来。
Query query2 = session.createQuery("select s from Student s join fetch s.teacher");
List<Student> list2 = query2.list();
Student student2 = list.get(0);
System.out.println(student2.getTeacher().getTname());//这里不会再发sql了。
}
@After
public void destroy(){
transaction.commit();
session.close();
sessionFactory.close();
}
}
排序order by
分组group by
package com.rong.entity.group; import java.util.HashSet;
import java.util.Set; import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany; @Entity
public class Teacher {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int tid;
private String tname;
@OneToMany(targetEntity=Student.class,fetch=FetchType.LAZY,mappedBy="teacher")
private Set<Student> students=new HashSet<Student>();
public int getTid() {
return tid;
}
public void setTid(int tid) {
this.tid = tid;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
}
package com.rong.entity.group; 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; @Entity
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
private int math;
private int java;
@ManyToOne(targetEntity=Teacher.class,fetch=FetchType.LAZY)
@JoinColumn(name="t_id",referencedColumnName="tid")
private Teacher teacher;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getJava() {
return java;
}
public void setJava(int java) {
this.java = java;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}
package com.rong.entity.group; import java.util.List;
import java.util.Random; import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
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;
//hql语句(面向):类 对象 属性
public class TestHQL {
SessionFactory sessionFactory;
Session session;
Transaction transaction;
@Before
public void init() {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory=configuration.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
transaction = session.beginTransaction();
}
//随机生成名字
public String randomName(){
String string="abcdefghijklmnopqrstuvwxyz";
StringBuilder stringBuilder=new StringBuilder();
Random random=new Random();
for(int i=0;i<4;i++){
int index = random.nextInt(string.length());
char charAt = string.charAt(index);
stringBuilder.append(charAt);
}
return stringBuilder.toString();
}
//插入数据
@Test
public void addData(){
Teacher teacher1=new Teacher();
teacher1.setTname("龙老师");
session.save(teacher1);
Teacher teacher2=new Teacher();
teacher2.setTname("高老师");
session.save(teacher2);
Random random=new Random();
for(int i=1;i<=100;i++){
Student student=new Student();
student.setName(randomName());
student.setJava(random.nextInt(100)+1);
student.setMath(random.nextInt(100)+1);
if(random.nextInt(2)==0){
student.setTeacher(teacher1);
}else{
student.setTeacher(teacher2);
}
session.save(student);
}
}
//1.根据老师分组统计学生数量(统计每位老师的学生数量)
@Test
public void test1(){
Query query = session.createQuery("select count(s),s.teacher.tname from Student s group by s.teacher.tname");
List<Object[]> list = query.list();
//46高老师
//54龙老师
for (Object[] objects : list) {
for (Object object : objects) {
System.out.print(object);
}
System.out.println();
}
}
//2.根据老师分组统计学生平均分,总分数
@Test
public void test2(){
Query query = session.createQuery("select sum(s.java+s.math),avg(s.java+s.math),s.teacher.tname from Student s group by s.teacher.tname");
List<Object[]> list = query.list();
//4659 101.2826 高老师
//5256 97.3333 龙老师
for (Object[] objects : list) {
for (Object object : objects) {
System.out.print(object+" ");
}
System.out.println();
}
} @After
public void destroy(){
transaction.commit();
session.close();
sessionFactory.close();
}
}
分组过滤having
//根据老师分组统计学生平均分,总分数,并且把老师为1的过滤出来
@Test
public void test3(){
Query query = session.createQuery("select avg(s.java+s.math),sum(s.java+s.math),s.teacher.tname,s.teacher.tid from Student s group by s.teacher.tname having s.teacher.tid=?");
query.setParameter(0, 1);
List<Object[]> list = query.list();
//97.3333 5256 龙老师 1
for (Object[] objects : list) {
for (Object object : objects) {
System.out.print(object+" ");
}
System.out.println();
}
}
聚集函数(统计函数)
//聚集函数(统计函数) count max min avg sum
@Test
public void test4(){
Long count=(Long) session.createQuery("select count(*) from Student").uniqueResult();
System.out.println("学生总人数:"+count);
int max=(int) session.createQuery("select max(s.java) from Student s").uniqueResult();
System.out.println("java最高成绩:"+max);
int min=(int) session.createQuery("select min(s.math) from Student s").uniqueResult();
System.out.println("math最低成绩:"+min);
double avg = (double) session.createQuery("select avg(s.java+s.math) from Student s").uniqueResult();
System.out.println("每位学生的平均总成绩:"+avg);
Long sum = (Long) session.createQuery("select sum(s.java+s.math) from Student s").uniqueResult();
System.out.println("所有学生的总成绩之和:"+sum);
}
Hibernate(六)的更多相关文章
- Hibernate(六)一对多映射(多对一)
一.Hinbernate中持久化类的关联关系 在数据库中,表表之间是通过外键关联的,在程序中是要转化为持久化类也就是(JAVA Bean)来实例的. 但在Hibernater中持久化的之间的映射关系, ...
- hibernate(六) cascade(级联)和inverse关系详解
序言 写这篇文章之前,自己也查了很多的资料来搞清楚这两者的关系和各自所做的事情,但是百度一搜,大多数博文感觉说的云里雾里,可能博主自己清楚是怎么一回事,但是给一个不懂的人或者一知半解的人看的话,别人也 ...
- Hibernate(六)__对象的三种状态
瞬时(transient):数据库中没有数据与之对应,超过作用域会被JVM垃圾回收器回收,一般是new出来且与session没有关联的对象. 持久(persistent):数据库中有数据与之对应,当前 ...
- Hibernate(六)
================================缓存============================定义:介于应用程序和永久性数据存储源之间,可以复制数据存储源中的数据. 工作 ...
- Hibernate(六)--缓存策略
缓存: 缓存就是数据库数据在内存中的临时容器,包括数据库数据在内存中的临时拷贝,它位于数据库与数据库访问中间层,ORM在查询数据时,首先会根据自身的缓存管理策略,在缓存中查找相关数据,如果发现所需的数 ...
- Hibernate常用接口
Hibernate的接口类型 在了解了Hibernate的基本配置,映射文件后,道路已经铺平了.我们继续往前走.接下来,我们应该做的是了解Hibernate常用的接口,对Hibernate的工作方式进 ...
- 22Java之JDBCTemplate总结
写在前面:这里总结4种方式来操作数据库(SE阶段) 一.JDBC JDBC有关的类:都在java.sql 和 javax.sql 包下. 1.数据准备 ...
- 攻城狮在路上(壹) Hibernate(十六)--- Hibernate声明数据库事务
一.数据库事务的概念: 数据库的ACID特征:Atomic.Consistency.Isolation.Durability.原子性.一致性.隔离性.持久性.不同的隔离级别引发的不同问题. 事务的AC ...
- 攻城狮在路上(壹) Hibernate(六)--- 通过Hibernate操纵对象(上)
一.Hibernate缓存简介: Session接口是Hibernate向应用程序提供的操纵数据接口的最主要接口,它提供了基本的保存.更新.删除和加载Java对象的方法. Session具有一个缓存, ...
- HIbernate学习笔记(六) 关系映射之多对多
六.多对多 - 单向 Ø 一般的设计中,多对多关联映射,需要一个中间表 Ø Hibernate会自动生成中间表 Ø Hibernate使用many-to-ma ...
随机推荐
- 【 C 】字符串常量
当一个字符串常量出现在表达式中时,它的值是个指针常量.编译器把这些指定字符的一份拷贝存储在内存的某个位置,并存储一个指向第一个字符的指针.但是,当数组名用于表达式中时,它们的值也是个指针常量.我们可以 ...
- 消除运行MATLAB生成独立可执行程序的DOS黑屏
基于Matlab生成独立可执行文件后,每次运行都存在DOS黑屏问题,可通过以下方法解决: 在Matlab命令窗口中输入: cd(prefdir) edit compopts.bat 在打开的文件最后添 ...
- websocket简单入门
今天说起及时通信的时候,突然被问到时用推的方式,还是定时接受的方式,由于之前页面都是用传统的ajax处理,可能对ajax的定时获取根深蒂固了,所以一时之间没有相同怎么会出现推的方式呢?当被提及webs ...
- m2eclipse安装遇到的问题——备忘
手贱把m2eclipse给卸载了,结果重新安装的时候,发现原来的网址不好用了,去官网查了发现改成了http://download.eclipse.org/technology/m2e/releases ...
- VBA_常用VBA代码
'批量替换字符 Sub Test() Dim i As Integer ).Value = "已激活" Then Cells(i, ).Value = "Active&q ...
- js中对象转化成字符串、数字或布尔值的转化规则
js中对象可以转化成 字符串.数字.布尔值 一.对象转化成字符串: 规则: 1.如果对象有toString方法,则调用该方法,并返回相应的结果:(代码通常会执行到这,因为在所有对象中都有toStrin ...
- ffmpeg 踩坑实录 近期使用总结(三)
一.背景介绍 将ffmpeg运用到项目上已经有一段时间了,趁现在有空赶紧记下来. 二.技术点总结 2.1 实现方式 项目里面主要运用的形式是,在java端,调用操作系统的方法,并执行切片命令. ...
- oracle 查看锁表及解锁的语句
解锁语句: alter system kill session 'sid, serial#'; alter system kill session '23, 1647'; 查询那些对象被锁: sele ...
- selenium自动化之处理浏览器警告弹窗
有的网站会弹出类似如下图的警告弹窗,你会发现这种弹窗在html源码中怎么也定位不到,接下来将介绍这种弹窗的处理方式. 其实这种弹窗是不属于html的元素的,他是属于浏览器自带的弹窗,所以用定位元素的方 ...
- 怎样安装Scrapy
Windows怎样安装Scrapy? pip install scrapy会报错 访问https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted 下载并放到 ...