1.简化SQL语句的编写
2.字表查询使用jion 方式关联,和标签SQL区别,条件都写在where后面;
3.查询的对象是一个数组,或者new一个对象接收;
有哪几种写法,如何赋值?
1 from 实体类 where 属性名=:参数名
query.setString(“参数名称”,实际参数);
2 from 实体类 where 属性名=:参数名
query.setString(“参数名称”,实际参数,Hibernate中的参数类型);
JAVA:String ......
3 from 实体类 where 属性名=?
query.setString(“参数位置”,实际参数);
....
package com.zgq.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import com.zgq.enity.Sclass;
import com.zgq.enity.Studentinfo;
public class BaseDaoHql {
private static SessionFactory factory=null;
static{
Configuration cfg = new Configuration().configure();
factory = cfg.buildSessionFactory();
}
@Test
public void hqlQueryStu1(){
/**
* private Integer stuNo;
private Sclass sclass;
private String stuName;
private String stuSex;
private Integer stuAge;
private String stuBirth;
*/
String hql="from Studentinfo stu where stu.stuName=:stu_name and stu.stuAge=:stu_age";
Session session = factory.openSession();
Query query = session.createQuery(hql);
query.setString("stu_name", "花木兰");
query.setString("stu_age", "21");
List<Studentinfo> list = query.list();
for (Studentinfo studentinfo : list) {
System.out.println(studentinfo.toString());
}
}
@Test
public void hqlQueryStu2(){
String hql="from Studentinfo stu where stu.stuSex=?";
Session session = factory.openSession();
Query query = session.createQuery(hql);
query.setString(0, "男");
// query.setString(1, "21");
List<Studentinfo> list = query.list();
for (Studentinfo studentinfo : list) {
System.out.println(studentinfo.toString());
}
}
@Test
public void hqlQueryStu3(){
Studentinfo stu = new Studentinfo();
stu.setStuName("花木兰");
String hql="from Studentinfo stu where stu.stuName=:stuName";
Session session = factory.openSession();
Query query = session.createQuery(hql);
query.setProperties(stu);
// query.setString(1, "21");
List<Studentinfo> list = query.list();
for (Studentinfo studentinfo : list) {
System.out.println(studentinfo.toString());
}
}
/**
*
* @Description: 分页查询
* @Author: 邹国庆(作者)
* @Create: 2019年11月12日 下午3:03:32
* @Parameters:
*/
@Test
public void hqlQueryStu4(){
String hql="from Studentinfo stu where stu.stuSex=:stuSex";
Session session = factory.openSession();
Query query = session.createQuery(hql);
query.setString("stuSex", "女");
query.setFirstResult(1);
query.setMaxResults(1);
List<Studentinfo> list = query.list();
for (Studentinfo studentinfo : list) {
System.out.println(studentinfo.toString());
}
}
}