文章目录
Session
对象hql
语句session.createQuery(String hql)
创建Query
对象session.setXX(index,Object)
设置占位符的值query.list()
获取实体对象即可package cn.tedu.hibernate.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="husband")
public class Husband implements Serializable{
private static final long serialVersionUID = 7403209578400736239L;
private Integer id;
private String name;
private int age;
private Wife wife;
@Id
@GeneratedValue //主键自增长
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length=10)
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;
}
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name="wife_id") //设置外键名称为wife_id
public Wife getWife() {
return wife;
}
public void setWife(Wife wife) {
this.wife = wife;
}
@Override
public String toString() {
return "Husband [id=" + id + ", name=" + name + ", age=" + age
+ ", wife=" + wife + "]";
}
}
Wife
的实体类import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="wife")
public class Wife implements Serializable {
private static final long serialVersionUID = -7203920255946679244L;
private Integer id;
private String name;
private int age;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length=10)
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;
}
@Override
public String toString() {
return "Wife [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
Session
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static Configuration configuration;
private static SessionFactory sessionFactory;
/*
* 静态语句块中的内容只是在类加载的时候只创建一次,因此这里的大大减少了资源的消耗
*/
static {
// 加载核心配置文件hibernate.cfg.xml
configuration = new Configuration();
configuration.configure();
// 创建SessionFactotry对象
sessionFactory = configuration.buildSessionFactory();
}
//创建session对象,在测试类中可以使用这个静态方法获取session
public static Session getSession() {
return sessionFactory.openSession();
}
}
List<>
的集合。其中的泛型为实体类
sql
语句中的select * from husband;
hql
语句是from Husband where id=?
,这里还可以和sql
语句一样使用别名来获取其中的值,比如: from Husband h where h.id=?
from Husband where id=?
,其中的Husband
是实体类的名字,而不是表的名称,后面的属性实体类中的属性名称
,而不是表中字段的名称,区分大小写
where
子句中只要是sql
语句被能够满足的都是可以写的,比如=, , <, >, <=, >=, between, not between, in ,not in, is, like
,同时也是可以写算术表达式
FROM User user WHERE user.age<20
FROM User user WHERE user.name IS null
FROM User user WHERE user.name LIKE 'Er%'
FROM User user WHERE (user.age % 2 = 1)
FROM User user WHERE (user.age<20) AND (user.name LIKE '%Er')
husband
这张表,其中对应的实体类是Husband
@Test
public void test1() {
Session session = null;
Transaction transaction = null;
try {
// 创建session
session = HibernateUtil.getSession();
// 开始事务
transaction = session.beginTransaction();
//编写hql语句
String hql="from Husband where id=?";
//String hql="from Husband h where h.id=?";
//创建Query
Query query=session.createQuery(hql);
//设置占位符的值,这里的用法和PreparedStatement一样的用法
query.setInteger(0,1);
List<Husband> husbands=query.list(); //执行查询语句,返回的是list集合
for (Husband husband : husbands) {
System.out.println(husband);
}
// 提交事务
transaction.commit();
} catch (Exception exception) {
transaction.rollback(); // 事务回滚
} finally {
if (session != null) {
session.close();
}
}
}
实体对象的查询
返回的是一个实体对象的List<>
集合,我们这里需要查询的是表中的执行字段,而不是全部的字段select 实体类属性名 from 实体类名字 where 条件语句
id=1
的所有的husband
中的name和age
sql
语句:select name,age from husband where id=1
hql
语句: select name,age from Husband h where h.id=?
,此时的占位符id
的值为1List
是一个Object[]
,其中的元素是name
,age
,并且是按照hql
的语句的查询顺序存储的//编写hql语句,只查询name和age属性字段
String hql="select name,age from Husband where id=?";
//创建Query
Query query=session.createQuery(hql);
//设置占位符的值,这里的用法和PreparedStatement一样的用法
query.setInteger(0,1);
//这里返回的是一个List集合,但是其中的每一个元素都是一个Object数组
List<Object[]> lists=query.list();
//遍历List集合
for (Object objects : lists) {
//遍历数组,[0]的元素是name,[1]的元素是age
for(int i=0;i<objects.length;i++){
System.out.println(objects[i]);
}
}
List
中存放的是Object[]
,但是如果我们查询的只有一个字段,那么返回的结果List
中存放的是Object
,这个值是你查询的字段的值对象方式
的关联查询HQL
所特有的,因为这个需要用到对象之间的关系join
方式关联select
子句关联wife
的id
值为1的husband
表中指定的字段,我们除了使用多表联合查询
,我们也可以使用关联查询,因为在Husband
的实体类中有Wife
这个对象hql
语句: select name,age from Husband h where h.wife.id=?
//编写hql语句,where字句中的条件是wife的id
String hql="select h.name,w.name from Husband h,Wife w where h.wife.id=? ";
//创建Query
Query query=session.createQuery(hql);
//设置占位符的值,这里的用法和PreparedStatement一样的用法
query.setInteger(0,1);
List<Object> lists=query.list();
//遍历查询结果
for (Object object : lists) {
Object[] objects=(Object[])object;
for (int i = 0; i < objects.length; i++) {
System.out.println(objects[i]);
}
}
sql
语句:select * from husband h left join wife w on h.wife_id=w.id
,查询丈夫的所有数据并且和其对应妻子的信息,其中husband
和wife
这两张表是通过wife_id
这个外键关联的hql
语句: select h.name,h.age,w.name,w.age from Husband h left join h.wife w
,这条语句和上面的sql
语句是一样的功能select 实体类属性 from 实体类名 [as] 别名 left join 别名.关联对象名 [as] 别名
as
可以省略别名
可以省略left join
后面跟的是实体类的关联对象
,比如Husband
中的Wife
对象h.wife
,这里就相当sql
中的on h.wife_id=w.id
hql
: from Husband h left join h.wife
,虽然这里的使用的是实体查询
的方式,但是返回的却是Object[]
,其中的第一个元素是Husband
对象,第二个是Wife
对象//编写hql语句
String hql="from Husband h left join h.wife";
//创建Query
Query query=session.createQuery(hql);
//执行查询,这里返回的是一个Object数组,其中数组的第一个元素是husband的数据,第二个是wife的数据
List<Object[]> list=query.list();
for (Object[] objects : list) {
Husband husband=(Husband) objects[0]; //获取Husband对象
Wife wife=(Wife)objects[1]; //获取Wife对象
}
//编写hql语句
String hql="select h,w from Husband h left join h.wife w";
//创建Query
Query query=session.createQuery(hql);
List<Object[]> list=query.list();
for (Object[] objects : list) {
Husband husband=(Husband) objects[0]; //获取Husband对象
Wife wife=(Wife)objects[1]; //获取Wife对象
}
name
,age
和其对应的妻子的的name
,age
信息//编写hql语句
String hql="select h.name,h.age,w.name,w.age from Husband h left join h.wife w";
//创建Query
Query query=session.createQuery(hql);
List<Object> list=query.list();
for (Object object : list) {
Object[] objects=(Object[])object;
for (int i = 0; i < objects.length; i++) {
System.out.print(objects[i]+"\t");
}
System.out.println();
}
select 实体类属性 from 实体类名 [as] 别名 right join 别名.关联对象名 [as] 别名
as
可以省略别名
可以省略right join
后面跟的是实体类的关联对象
,比如Husband
中的Wife
对象h.wife
,这里就相当sql
中的on h.wife_id=w.id
select h,w from Husband h right join h.wife w
select 对象.属性名,.... from 类名
对象
是实体类
中的对象属性,比如Husband
类中的Wife
对象select h.wife.name,h.wife.age,h.name from Husband h
//编写hql语句,where字句中的条件是wife的id
String hql="select h.wife.name,h.wife.age,h.name from Husband h";
//创建Query
Query query=session.createQuery(hql);
//设置占位符的值,这里的用法和PreparedStatement一样的用法
List<Object> lists=query.list();
//遍历查询结果
for (Object object : lists) {
Object[] objects=(Object[])object;
for (int i = 0; i < objects.length; i++) {
System.out.println(objects[i]);
}
}
sql
语句一样,使用distinct
即可select distinct name,age from Husband where id=?
hql
语句和sql
一样,都是可以使用聚集函数查询select count(*) from Husband where id=?
根据id
查询出对应的人数count(*)
: 计算数量select count(*) from Husband where id=?
sum()
:求和select sum(age) from Husband h where h.wife.id=?
AVG()
: 求平均值select avg(age) from Husband where age>10
MAX()
: 求最大值select max(age) from Husband where age>10 and age<90
MIN()
: 求最小值select min(age) from Husband where age>10 and age<100
from Husband where id=? order by name desc,age asc
按照姓名将序排列,年龄升序排列hql
中也是可以使用group by
子句进行分组的,比如select count(*),sum(age),max(age) from Husband h where h.age>? group by h.name
having子句
进行聚合函数的条件过滤,比如select count(*),sum(age),max(age) from Husband h where h.age>? group by h.name having count(*)>?
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有