标签:des io ar os java for strong on art
package qau.edu.search;
import qau.edu.search.Employee;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class SearchTest {
private Session session ;
private Transaction tr ;
@Before
public void init(){
// 打开Session ;
session = new Configuration().configure().buildSessionFactory().openSession();
// 开启事务;
tr = session.beginTransaction();
}
@After
public void destroy(){
// 提交事务;
tr.commit();
// 关闭会话;
session.close();
}
// “位置绑定”查询;
@Test
public void testHQL() {
// 创建Query对象;
String hql = "from Employee e where e.name like ? and e.sal > ? ";
Query query = session.createQuery(hql);
// 绑定参数;
// 这里的数字0和1表示的含义要知道,表示的是占位符,从这里能体会到“位置绑定”的含义;
query.setString(0, "%%")
.setFloat(1, 5000);
// 打印输出;
List<Employee> emps = query.list();
System.out.println(emps.size());
}
// “命名参数”的查询;
@Test
public void testHQL2() {
// 创建Query对象;
// 注意的是:在进行编写查询条件的时候,:是紧紧跟着后面的命名的,不允许出现空格。
String hql = "from Employee e where e.name like :name and e.sal > :sal ";
Query query = session.createQuery(hql);
// 绑定参数;
query.setString("name", "%%")
.setFloat("sal", 5000);
// 打印输出;
List<Employee> emps = query.list();
System.out.println(emps.size());
}
// 实体绑定;
@Test
public void testHQL3() {
// 创建Query对象;
// 注意的是:在进行编写查询条件的时候,:是紧紧跟着后面的命名的,不允许出现空格。
String hql = "from Employee e where e.name like :name and e.sal > :sal and dept = :dept";
Query query = session.createQuery(hql);
// 绑定参数;
Department dept = (Department)session.get(Department.class, 80);
query.setString("name", "%%")
.setFloat("sal", 5000)
.setEntity("dept", dept);
// 打印输出;
List<Employee> emps = query.list();
System.out.println(emps.size());
}
}
标签:des io ar os java for strong on art
原文地址:http://www.cnblogs.com/shiguangshuo/p/4104727.html