
文章目录
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 + "]";
}
}Sessionimport 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和agesql语句:select name,age from husband where id=1hql语句: 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.idhql: 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.idselect 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>10MAX(): 求最大值select max(age) from Husband where age>10 and age<90MIN(): 求最小值select min(age) from Husband where age>10 and age<100from 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.namehaving子句进行聚合函数的条件过滤,比如select count(*),sum(age),max(age) from Husband h where h.age>? group by h.name having count(*)>?