一:模糊查询,(不要导错包)
package Test;
import java.text.SimpleDateFormat;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import Util.HibernateUtil;
import entity.Student;
public class TestQueryAll {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
Session session = HibernateUtil.currentSesion();
// 使用hql语句查询语句
// hql模糊查询
String searchKey = "小";
Student us = new Student();
us.setNickName("%" + searchKey + "%");
String hql = "from Student where nickName like :nickName";//注意这里写的都是Student类里面的
Query query = session.createQuery(hql);
query.setProperties(us);
List<Student> userList = query.list();
for (Student u : userList) {
System.out.println(u.getNickName() + "," + u.getAge() + ","
+ sdf.format(u.getBirthday()));
}
}
}
二:分页查询
package Test;
import java.text.SimpleDateFormat;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import Util.HibernateUtil;
import entity.Student;
public class TestQueryAll {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Session session = HibernateUtil.currentSesion();
int pageSize = 3;// 设置每页显示三条
// 查询总共有多少条数据
String counHql = "select count(*) from Student";
int count = ((Long) session.createQuery(counHql).uniqueResult())
.intValue();
// 总条数除以每页显示条数,求出总页数
int totalpages = (count % pageSize == 0) ? (count / pageSize)
: (count /pageSize) + 1;
System.out.println(totalpages);
// hql分页查询
String hql = "from Student";
Query query = session.createQuery(hql);
int pageIndex = 1;
// 设置从第几条开始
query.setFirstResult((pageIndex - 1) * pageSize);
// 设置读取最大记录数
query.setMaxResults(pageSize);
List<Student> userList = query.list();
for (Student u : userList) {
System.out.println(u.getNickName() + "," + u.getAge() + ","
+ sdf.format(u.getBirthday()));
}
}
}