前提:所有sql语句中的表名统统在hql中换成实体类名!
一、HQL
//1.查询所有(格式与sql差别):
from Student
//2.部分查询:
select name,age from Student
//3.条件查询(别名):
from Student a where a.city = '上海'
select a.name,a.age from Student a where a.name like '%王%'
//4.插入(格式与sql差别):
session.save()
//5.条件删除(格式与sql差别):
delete Student a where a.city = '上海'
//6.条件更新:
update Student a set a.age=25 where a.city = '上海'
二、增删查改核心代码:
1.添加:
/*省略了获取session等操作*/
Student student = new Student();
student.setStuNo("5");
student.setStuName("lisi");
session.save(Studnet);
/*省略了关闭session等操作*/
2.查询:
/*省略了获取session等操作*/
String hql = "from Student"; //全部查询
//String hql = "select name,age from Student"; //部分查询
Query query = session.createQuery(hql); //预处理hql语句
List list = query.list(); //返回结果list
/*省略了关闭session等操作*/
3.删除:
/*省略了获取session等操作*/
String hql = "delete Student a where a.city = '上海'";
Query query = session.createQuery(hql);
query.executeUpdate();
/*省略了关闭session等操作*/
4.更新:
/*省略了获取session等操作*/
String hql = "update Student a set a.age=25 where a.city = '上海'";
Query query = session.createQuery(hql);
query.executeUpdate();
/*省略了关闭session等操作*/