TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
1,属性查询
@Test
public void test2(){
Session session = HibernateSessionFactory.getSession();
String hql = "select fw.date,fw.title from Zfxx fw";
Query query = session.createQuery(hql);
List list = query.list(); //查询结果还是保存在List中
Iterator it = list.iterator();
while(it.hasNext()){
//每条数据封装为一个Object数据组
Object[] arr = (Object[])it.next();
System.out.println(arr[0]+"\t"+arr[1]);;
}
}
2,参数查询
@Test
public void test3(){
Session session = HibernateSessionFactory.getSession();
String hql = "from Zfxx fw where fw.title like ?";
Query query = session.createQuery(hql);
query.setString(0, "%健翔桥%");
List list = query.list();
printFwxxList(list);
}
3,关联查询
@Test
public void test4(){
Session session = HibernateSessionFactory.getSession();
String hql = "select jd "+
" from Jd jd ,Zfxx fw "+
" where fw.jdid=jd.id and fw.lxr = '伊先生'";
Query query = session.createQuery(hql);
List list = query.list();
printJdList(list);
session.close();
}
private void printJdList(List list){
Iterator it = list.iterator();
while(it.hasNext()){
Jd item = (Jd)it.next();
System.out.println(item.getJd());
}
}
4,分页查询
@Test
public void test5(){
List list = search(1,10);
Iterator it = list.iterator();
while(it.hasNext()){
Zfxx fx = (Zfxx)it.next();
System.out.println(fx.getDate()+"\t"+fx.getFwxx());
}
}
public List search(int pageNo,int pageSize){
Session session = HibernateSessionFactory.getSession();
String hql ="from Zfxx fw order by fw.fwid asc";
Query query = session.createQuery(hql);
int firstResultIndex = pageSize*(pageNo-1);
query.setFirstResult(firstResultIndex);
query.setMaxResults(pageSize);
return query.list();
}
5,统计查询
@Test
public void test6(){
Session session = HibernateSessionFactory.getSession();
String hql = "select count(fw) from Zfxx fw";
Query query = session.createQuery(hql);
int count = (Integer)query.uniqueResult();
System.out.println("总的数据条数:"+count);
}
6,模糊查询
@Test
public void test7(){
Zfxx condition = new Zfxx();
condition.setTitle("出租");
List list = search(condition);
Iterator it = list.iterator();
while(it.hasNext()){
Zfxx fw = (Zfxx)it.next();
System.out.println("["+fw.getTitle()+"]\t"+fw.getDate()+"\t"+fw.getFwxx());
}
}
public List search(Zfxx condition){
Session session = HibernateSessionFactory.getSession();
String hql = "select fw from Zfxx fw where 1=1 ";
if(null != condition){
if(condition.getTitle() != null && !condition.getTitle().equals("")){
hql += " and fw.title like '%"+
condition.getTitle() + "%'";
}
}
Query query = session.createQuery(hql);
List ret = query.list();
return ret;
}
|
|