//查询
public List<Student> getAllStudent() {
String hql = "from Student";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.list();
}
//带参查询
public boolean delStudent(String id) {
String hql = "delete Student u where u.id = ?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString(0, id);
return (query.executeUpdate() > 0);
}
//模糊查询
public List<Student> getPartlyStudent(String key) {
String hql = "from Student u where u.id like ?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString(0, key+"%");
return query.list();
}
//多表查询 & 部分字段查询
public List<Student> getPassed() {
String hql = "select stu.name,gr.grade from Student as stu,Grades as gr where stu.id=gr.id and gr.grade>60";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.list();
}
//排序 & 分组
from User user order by user.name asc,user.age desc ;
select count(user),user.age from User user group by user.age having count(user)>10 ;
//分页查询
public List<Student> getByPage(int pageSize, int pageNow) {
String hql = "from Student";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setFirstResult((pageNow-1)*pageSize); query.setMaxResults(pageSize);
return query.list();
}setFirstResult
Query setFirstResult(int firstResult)Set the first row to retrieve.
- Parameters:
firstResult
- a row number, numbered from 0- Returns:
this
, for method chaining- See Also:
getFirstResult()
//插入
public void addStudent(Student user) {
sessionFactory.getCurrentSession().save(user);
}
//删除
public boolean delStudent(String id) {
String hql = "delete Student u where u.id = ?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString(0, id);
return (query.executeUpdate() > 0);
}
//更新
public boolean updateStudent(Student student) {
String hql = "update Student u set u.userName = ?,u.age=? where u.id = ?";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setString(0, student.getName());
query.setString(1, student.getAddress());
query.setString(2, student.getId());
return (query.executeUpdate() > 0);
}