HQL(Hibernate Query Language)
1. NativeSQL > HQL > EJB QL(JP QL 1.0) > QBC(Query By Criteria) > QBE(Query By Example)
2. 总结:QL应该和导航关系结合,共同为查询提供服务。
以下图为例:
Category:
package com.bjsxt.hibernate; import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id; @Entity
public class Category { private Integer id; private String name; @Id
@GeneratedValue
public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}
Topic:
package com.bjsxt.hibernate; import java.util.Date; import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne; @Entity
public class Topic { private Integer id; private String title; private Category category; private Date createDate; @Id
@GeneratedValue
public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
} @ManyToOne(fetch=FetchType.LAZY)
public Category getCategory() {
return category;
} public void setCategory(Category category) {
this.category = category;
} public Date getCreateDate() {
return createDate;
} public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
Msg:
package com.bjsxt.hibernate; import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne; @Entity
public class Msg { private Integer id; private String cont; private Topic topic; @Id
@GeneratedValue
public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getCont() {
return cont;
} public void setCont(String cont) {
this.cont = cont;
} @ManyToOne
public Topic getTopic() {
return topic;
} public void setTopic(Topic topic) {
this.topic = topic;
}
}
MsgInfo:
package com.bjsxt.hibernate; //VO(Value Object) DTO(Data Transfer Object)
public class MsgInfo { private Integer id; private String cont; private String topicName; private String categoryName; public MsgInfo(Integer id,String cont,String topicName,String categoryName){
this.id = id;
this.cont = cont;
this.topicName = topicName;
this.categoryName = categoryName;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getCont() {
return cont;
} public void setCont(String cont) {
this.cont = cont;
} public String getTopicName() {
return topicName;
} public void setTopicName(String topicName) {
this.topicName = topicName;
} public String getCategoryName() {
return categoryName;
} public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
}
HibernateQLTest1:
package com.bjsxt.hibernate; import java.util.Date;
import java.util.List; import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; public class HibernateQLTest {
private static SessionFactory sf = null; @Before
public void beforeClass(){
// new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
sf = new AnnotationConfiguration().configure().buildSessionFactory();
} @After
public void afterClass(){
if(sf != null){
sf.close();
}
} @Test
public void testSave(){ Session session = sf.getCurrentSession();
session.beginTransaction(); for(int i=0; i<10; i++){
Category c = new Category();
c.setName("c" + i);
session.save(c);
} for(int i=0; i<10; i++){
Category c = new Category();
c.setId(1);
Topic t = new Topic();
t.setCategory(c);
t.setCreateDate(new Date());
t.setTitle("t"+i);
session.save(t);
} for(int i=0; i<10; i++){
Topic t = new Topic();
t.setId(1);
Msg m = new Msg();
m.setTopic(t);
m.setCont("m" + i);
session.save(m);
} session.getTransaction().commit();
} @Test
public void testHQL_01(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = (Query) session.createQuery("from Category");
List<Category> categories = (List<Category>)q.list();
for(Category c : categories){
System.out.println(c.getName());
}
session.getTransaction().commit();
} @Test
public void testHQL_02(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = (Query) session.createQuery("from Category c where c.name > 'c5'");
List<Category> categories = (List<Category>)q.list();
for(Category c : categories){
System.out.println(c.getName());
}
session.getTransaction().commit();
} @Test
public void testHQL_03(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = (Query) session.createQuery("from Category c order by name desc");
List<Category> categories = (List<Category>)q.list();
for(Category c : categories){
System.out.println(c.getName());
}
session.getTransaction().commit();
} @Test
public void testHQL_04(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = (Query) session.createQuery(
"select distinct c from Category c order by name desc");//主键不同
List<Category> categories = (List<Category>)q.list();
for(Category c : categories){
System.out.println(c.getName());
}
session.getTransaction().commit();
} @Test
public void testHQL_05(){
Session session = sf.getCurrentSession();
session.beginTransaction();
/*Query q = (Query) session.createQuery(
"from Category c where c.id > :min and c.id < :max");//主键不同
// q.setParameter("min", 2);
// q.setParameter("max", 8);
q.setInteger("min", 2);
q.setInteger("max", 8);*/ Query q = (Query) session.createQuery("from Category c where c.id > :min and c.id < :max")
.setInteger("min", 2)
.setInteger("max", 8);
List<Category> categories = (List<Category>)q.list();
for(Category c : categories){
System.out.println(c.getId() + "-" +c.getName());
}
session.getTransaction().commit();
} /**
* 链式编程
*/
@Test
public void testHQL_06(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = (Query) session.createQuery("from Category c where c.id > ? and c.id < ?")
.setInteger(0, 2)//索引从0开始
.setInteger(1, 8);
List<Category> categories = (List<Category>)q.list();
for(Category c : categories){
System.out.println(c.getId() + "-" +c.getName());
}
session.getTransaction().commit();
} /**
* 分页
*/
@Test
public void testHQL_07(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = (Query) session.createQuery("from Category c order by name desc");
q.setMaxResults(4);//每页4条
q.setFirstResult(2);//从第二行开始
List<Category> categories = (List<Category>)q.list();
for(Category c : categories){
System.out.println(c.getId() + "-" +c.getName());
}
session.getTransaction().commit();
} /**
* 分页(换一种获取方式)
*/
@Test
public void testHQL_08(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = (Query) session.createQuery("select c.id,c.name from Category c order by name desc");
q.setMaxResults(4);//每页4条
q.setFirstResult(2);//从第二行开始
List<Object[]> categories = (List<Object[]>)q.list();
for(Object[] c : categories){
System.out.println(c[0] + "-" +c[1]);
}
session.getTransaction().commit();
} /**
* 设定 fetch type 为 lazy 后将不会有第二条sql语句
*/
@Test
public void testHQL_09(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.category.id = 1");
List<Topic> topics = (List<Topic>)q.list();
for(Topic t : topics){
System.out.println(t.getId() + "-" + t.getTitle());
// System.out.println(t.getCategory().getName());
}
session.getTransaction().commit();
} /**
* 设定 fetch type 为 lazy 后将不会有第二条sql语句
*/
@Test
public void testHQL_10(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.category.id = 1");
List<Topic> topics = (List<Topic>)q.list();
for(Topic t : topics){
System.out.println(t.getId() + "-" + t.getTitle());
// System.out.println(t.getCategory().getName());
}
session.getTransaction().commit();
} @Test
public void testHQL_11(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("from Msg m where m.topic.category.id = 1");
for(Object o : q.list()){
Msg m = (Msg)o;
System.out.println(m.getCont());
}
session.getTransaction().commit();
} /**
* VO(Value Object)
* DTO(Data Transfer Object)
*/
@Test
public void testHQL_12(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("select new com.bjsxt.hibernate.MsgInfo(m.id, m.cont, m.topic.title, m.topic.category.name) from Msg m");
for(Object o : q.list()){
MsgInfo m = (MsgInfo)o;
System.out.println(m.getCont());
}
session.getTransaction().commit();
} //动手测试left right join
//为什么不能直接写 Category 名,而必须写 t.category
//因为有可能存在多个成员变量(同一个类),需要指明哪一个成员变量的连接条件来做连接
@Test
public void testHQL_13(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("select t.title,c.name from Topic t join t.category c");
List<Object[]> list = q.list();
for(Object[] o : list){
System.out.println(o[0] + "-" + o[1]);
}
session.getTransaction().commit();
} //学习使用 uniqueResult
@Test
public void testHQL_14(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("from Msg m where m = :MsgToSearch");//不重要
Msg m = new Msg();
m.setId(1);
q.setParameter("MsgToSearch", m); Msg mResult = (Msg)q.uniqueResult();
System.out.println(mResult.getCont()); session.getTransaction().commit();
} @Test
public void testHQL_15(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("select count(*) from Msg m"); long count = (Long)q.uniqueResult();
System.out.println(count);
session.getTransaction().commit();
} @Test
public void testHQL_16(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("select max(m.id), min(m.id), avg(m.id), sum(m.id) from Msg m"); Object[] o = (Object[])q.uniqueResult();
System.out.println(o[0] + "-" + o[1] + "-" + o[2] + "-" + o[3]); session.getTransaction().commit();
} @Test
public void testHQL_17(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("from Msg m where m.id between 3 and 5"); for(Object o : q.list()){
Msg m = (Msg)o;
System.out.println(m.getId() + "-" +m.getCont());
} session.getTransaction().commit();
} @Test
public void testHQL_18(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("from Msg m where m.id in(3,4,5)"); for(Object o : q.list()){
Msg m = (Msg)o;
System.out.println(m.getId() + "-" +m.getCont());
} session.getTransaction().commit();
} @Test
public void testHQL_19(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("from Msg m where m.cont is not null"); for(Object o : q.list()){
Msg m = (Msg)o;
System.out.println(m.getId() + "-" +m.getCont());
} session.getTransaction().commit();
} @Test
public void testSchemaExport(){
new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
} public static void main(String[] args) {
// new HibernatTreeTest().testSave();
new HibernateQLTest().beforeClass();
} }
HibernateQLTest2:
package com.bjsxt.hibernate; import java.util.Date;
import java.util.List; import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; public class HibernateQLTest {
private static SessionFactory sf = null; @Before
public void beforeClass(){
// new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
sf = new AnnotationConfiguration().configure().buildSessionFactory();
} @After
public void afterClass(){
if(sf != null){
sf.close();
}
} @Test
public void testSave(){ Session session = sf.getCurrentSession();
session.beginTransaction(); for(int i=0; i<10; i++){
Category c = new Category();
c.setName("c" + i);
session.save(c);
} for(int i=0; i<10; i++){
Category c = new Category();
c.setId(1);
Topic t = new Topic();
t.setCategory(c);
t.setCreateDate(new Date());
t.setTitle("t"+i);
session.save(t);
} for(int i=0; i<10; i++){
Topic t = new Topic();
t.setId(1);
Msg m = new Msg();
m.setTopic(t);
m.setCont("m" + i);
session.save(m);
} session.getTransaction().commit();
} //is empty and is not empty
@Test
public void testHQL_20(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.msgs is empty"); for(Object o : q.list()){
Topic t = (Topic)o;
System.out.println(t.getId() + "-" +t.getTitle());
} session.getTransaction().commit();
} @Test
public void testHQL_21(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.title like '%5'"); for(Object o : q.list()){
Topic t = (Topic)o;
System.out.println(t.getId() + "-" +t.getTitle());
} session.getTransaction().commit();
} @Test
public void testHQL_22(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.title like '_5'"); for(Object o : q.list()){
Topic t = (Topic)o;
System.out.println(t.getId() + "-" +t.getTitle());
} session.getTransaction().commit();
} //不重要
@Test
public void testHQL_23(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("select lower(t.title),"
+ "upper(t.title),"
+ "trim(t.title),"
+ "concat(t.title,'***'),"
+ "length(t.title) "
+ "from Topic t"); for(Object o : q.list()){
Object[] arr = (Object[])o;
System.out.println(arr[0] + "-" + arr[1] + "-" + arr[2] + "-" + arr[3] + "-" + arr[4]);
} session.getTransaction().commit();
} @Test
public void testHQL_24(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("select abs(t.id),"
+ "sqrt(t.id),"
+ "mod(t.id,2) "
+ "from Topic t"); for(Object o : q.list()){
Object[] arr = (Object[])o;
System.out.println(arr[0] + "-" + arr[1] + "-" + arr[2]);
} session.getTransaction().commit();
} @Test
public void testHQL_25(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("select current_date,current_time,current_timestamp,t.id from Topic t"); for(Object o : q.list()){
Object[] arr = (Object[])o;
System.out.println(arr[0] + "|" + arr[1] + "|" + arr[2] + "|" + arr[3]);
} session.getTransaction().commit();
} @Test
public void testHQL_26(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.createDate < :date");
q.setParameter("date", new Date()); for(Object o : q.list()){
Topic t = (Topic)o;
System.out.println(t.getTitle());
} session.getTransaction().commit();
} @Test
public void testHQL_27(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("select t.title, count(*) from Topic t group by t.title"); for(Object o : q.list()){
Object[] arr = (Object[])o;
System.out.println(arr[0] + "|" + arr[1]);
} session.getTransaction().commit();
} @Test
public void testHQL_28(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("select t.title, count(*) from Topic t group by t.title having count(*) > 0"); for(Object o : q.list()){
Object[] arr = (Object[])o;
System.out.println(arr[0] + "|" + arr[1]);
} session.getTransaction().commit();
} @Test
public void testHQL_29(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.id < (select avg(t.id) from Topic t)"); for(Object o : q.list()){
Topic t = (Topic)o;
System.out.println(t.getTitle());
} session.getTransaction().commit();
} @Test
public void testHQL_30(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.id < ALL (select t.id from Topic t where mod(t.id,2) = 0)"); for(Object o : q.list()){
Topic t = (Topic)o;
System.out.println(t.getTitle());
} session.getTransaction().commit();
} //用in可以实现 exists 的功能
//但是 exists 执行效率高
@Test
public void testHQL_31(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where not exists (select m.id from Msg m where m.topic.id = t.id)");//就是沒有回帖的topic for(Object o : q.list()){
Topic t = (Topic)o;
System.out.println(t.getTitle());
} session.getTransaction().commit();
} @Test
public void testHQL_32(){
Session session = sf.getCurrentSession();
session.beginTransaction(); Query q = session.createQuery("update Topic t set t.title = upper(t.title)");
q.executeUpdate();
q = session.createQuery("from Topic");
for(Object o : q.list()){
Topic t = (Topic)o;
System.out.println(t.getTitle());
} q = session.createQuery("update Topic t set t.title = lower(t.title)");
q.executeUpdate(); session.getTransaction().commit();
} //不重要
@Test
public void testHQL_33(){
Session session = sf.getCurrentSession();
session.beginTransaction(); Query q = session.getNamedQuery("topic.selectCertainTopic");
q.setParameter("id", 5);
Topic t = (Topic)q.uniqueResult();
System.out.println(t.getTitle()); session.getTransaction().commit();
} //Native(不太重要)
@Test
public void testHQL_34(){
Session session = sf.getCurrentSession();
session.beginTransaction(); SQLQuery q = session.createSQLQuery("select * from category limit 2,4").addEntity(Category.class);
List<Category> categories = (List<Category>)q.list();
for(Category c : categories){
System.out.println(c.getName());
} session.getTransaction().commit();
} @Test
public void testSchemaExport(){
new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
} public static void main(String[] args) {
// new HibernatTreeTest().testSave();
new HibernateQLTest().beforeClass();
} }
jar包链接: https://pan.baidu.com/s/1slvwzbn 密码: hwef
代码链接1: https://pan.baidu.com/s/1skCHfU9 密码: ka73
代码链接2: https://pan.baidu.com/s/1qYruCUC 密码: v4eb
HQL(Hibernate Query Language)的更多相关文章
- Hibernate hql(hibernate query language)基础查询
在开发过程中,数据库的操作我们其实更多的用到的是查询功能,今天开始学习hql的查询. 1.加入必要的工具 2.Hibernate配备的一种非常强大的查询语言,这种查询语言看上去很像sql.但是不要被语 ...
- HQL(Hibernate Query language)语言
现在有两张表:student(学生表),classroom(教室表). //对象 Student 对应 student 表中有四个字段,分别是:id,name,age,classroom; publi ...
- HQL: The Hibernate Query Language
Chapter 14. HQL: The Hibernate Query Language 14.1. Case Sensitivity 14.2. The from clause 14.3. Ass ...
- Hibernate查询(HQL——Hibernate Query Language)
HQL查询 HQL提供了是十分强大的功能,它是针对持久化对象,用取得对象,而不进行update,delete和insert等操作.而且HQL是面向对象的,具备继承,多态和关联等特性. from子句: ...
- 数据查询语句:DQL(Data Query Language)
一.基础查询 1.语法:select 查询列表 from 表名; 2.特点:1.通过select查询完的结果,是一个虚拟的表格,不是真实存在 2.查询列表可以是:字段.表达式.常量.函数等 3 ...
- 数据库系统概述(Data Model、DBMS、DBS、RDBS、Structured Query Language)
数据Data 描述事物的符号记录成为数据. 数据是数据库中存储的基本对象. 除了基本的数字之外.像图书的名称.价格.作者都可以称为数据. 将多种数据记录列成一张表.通过数据表管理数据. 每一行的数 ...
- hql(Hibernate Query Language)
1.Criteria查询对查询条件进行了面向对象封装,符合编程人员的思维方式,不过HQL(Hibernate Query Language)查询提供了更加丰富的和灵活的查询特性,因此Hibernate ...
- 数据库原理及应用-用户接口及SQL查询语言(Query Language)
2018-02-07 20:41:39 一.DBMS的用户接口 查询语言 访问DBMS的访问工具(GUI) API 相关类库 二.SQL语言 SQL语言可以细分为四种: 1.Data Definiti ...
- Hibernate Query Language查询:
Hibernate Query Language查询: Criteria查询对查询条件进行了面向对象封装,符合编程人员的思维方式,不过HQL(Hibernate Query Language)查询提供 ...
随机推荐
- yum国内镜像配置
yum默认链接的还是国外的镜像,速度相对不理想,配置成国内的镜像会快很多,这里以阿里镜像为例进行配置: CentOS系统更换软件安装源 #base源#第一步:备份你的原镜像文件,以免出错后可以恢复.m ...
- 【算法笔记】B1002 写出这个数
1002 写出这个数 (20 分)读入一个正整数 n,计算其各位数字之和,用汉语拼音写出和的每一位数字. 输入格式:每个测试输入包含 1 个测试用例,即给出自然数 n 的值.这里保证 n 小于 101 ...
- LightOJ - 1032 数位DP
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #i ...
- 关于es6 import export的学习随笔
记得之前的一次面试中,有个面试官问了我关于es6导入和导出的一些知识点,可惜当时对这方面没在意,只知道每次机械的import和export,也不知道为啥要这样用,现在静下心来,好好的把这块看了下,顺便 ...
- 1093 字符串A+B (20 分)
给定两个字符串 A 和 B,本题要求你输出 A+B,即两个字符串的并集.要求先输出 A,再输出 B,但重复的字符必须被剔除. 输入格式: 输入在两行中分别给出 A 和 B,均为长度不超过 106 ...
- 1.nginx安装和配置
1.安装 1.1安装编译工具及库文件 yum -y install make zlib zlib-devel gcc-c++ libtool openssl openssl-devel wget 1. ...
- MVC参数自动装配
在拿到一个类型的所有属性以及字段的描述信息后,就可以通过循环的方式,根据这些数据成员的名字去QueryString,Form,Session,Cookie读取所需的数据了. 就是遍历参数,然后用反射遍 ...
- linux文件夹权限问题
linux下 ls 某文件夹需要文件夹有 r 读权限. cd 某文件夹 需要文件夹有 x 运行权限 参考: http://www.linuxidc.com/Linux/2016-11/136959.h ...
- java中的各种修饰符作用范围
访问修饰符: private 缺省 protected public 作用范围: 访问修饰符\作用范围 所在类 同一包内其他类 其他包内子类 其他包内非子类 private 可以访问 不可以 不可以 ...
- console命令详解:(转载学习)
Console命令详解,让调试js代码变得更简单 Firebug是网页开发的利器,能够极大地提升工作效率. 但是,它不太容易上手.我曾经翻译过一篇<Firebug入门指南>,介绍了一些 ...