动态查询
Session session;
Transaction tx;
@Before
public void mybefor() {
//1构建配置对象COnfiguration
Configuration cfg = new Configuration().configure("hibernate02.cfg.xml");
//2.构建工厂SessionFactory
SessionFactory factory = cfg.buildSessionFactory();
//3.构建回话Session
session = factory.openSession();//从连接池中随机取出连接
//4.开始事务
tx = session.beginTransaction();
}
@Test
public void RunSelectDept(){
String hql = "select new Dept(d.dno,d.dname,d.loc) from Dept d";
Query query = session.createQuery(hql);
List <Dept>list = query.list();
for (Dept dept: list) {
System.out.println(dept.getDname());
}
}
@Test
public void RunSelectDept2(){
String hql = "from Dept d where d.dname=? and d.loc=?";
Query query = session.createQuery(hql);
query.setParameter(0,"LENK");
query.setParameter(1,"CHINA");
List <Dept>list = query.list();
for (Dept dept: list) {
System.out.println(dept.getDname());
}
}
@Test
public void RunSelectDept3(){
String hql = "from Dept d where d.dname=:dname and d.loc=:loc";
Query query = session.createQuery(hql);
query.setParameter("dname","LENK");
query.setParameter("loc","CHINA");
List <Dept>list = query.list();
for (Dept dept: list) {
System.out.println(dept.getDname());
}
}
@After
public void myafter(){
tx.commit();
session.close();
}