------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------
本篇博客会讲解Hibernate中的参数绑定,就是相当于sql语句中的where后面的条件
一,讲解概述:
1.通过下标的方式绑定参数
2.通过自定义参数名的方式绑定参数(多用于多表操作)
3.通过传入自定义对象的方式绑定参数(多用于单表操作)
4.通过类似智能标签的方式绑定参数(多用于带条件的多表操作)
二,通过下标的方式绑定参数
@Test /*通过下标的方式指定参数*/ public void t01Parameterbyunderid(){ /*模拟前台输入参数*/ Teacher teacher=new Teacher("a",400.00); /*hql语句*/ String hql="from Teacher where address=? and sal>?"; Query query = session.createQuery(hql); /*赋值*/ query.setParameter(0,teacher.getAddress()); query.setParameter(1,teacher.getSal()); /*查询*/ List list = query.list(); /*遍历*/ for (Object t:list) { System.out.println(t); } }
三,通过自定义参数名的方式绑定参数(多用于多表操作)
@Test /*通过自定义参数名的方式指定参数*/ public void t02Parameterbymyselfkey(){ /*模拟前台输入参数*/ Teacher teacher=new Teacher("a",400.00); /*hql语句*/ String hql="from Teacher where address=:teaAdd and sal>:teasal"; Query query = session.createQuery(hql); /*赋值*/ query.setParameter("teaAdd",teacher.getAddress()); query.setParameter("teasal",teacher.getSal()); /*查询*/ List list = query.list(); /*遍历*/ for (Object t:list) { System.out.println(t); } }
四,通过传入自定义对象的方式绑定参数(多用于单表操作)
@Test /*通过自定义对象的方式指定参数*/ /*适合单表操作*/ public void t03ParameterbymyselfObject(){ /*模拟前台输入参数*/ Teacher teacher=new Teacher("a",400.00); /*hql语句*/ String hql="from Teacher where address=:address and sal>:sal"; Query query = session.createQuery(hql); /*赋值*/ query.setProperties(teacher); /*查询*/ List list = query.list(); /*遍历*/ for (Object t:list) { System.out.println(t); } }
五,通过类似智能标签的方式绑定参数(多用于带条件的多表操作)
@Test /*通过自定义参数名的方式指定动态参数*/ /*适合多表操作*/ public void t04ParameterbyDongtai(){ /*模拟前台输入参数*/ Teacher teacher=new Teacher("a",400.00); /*hql语句*/ StringBuffer hql=new StringBuffer("from Teacher where 1=1 "); if(teacher.getAddress()!=null){ hql.append("and address=:teaAdd "); } if(teacher.getSal()>0){ hql.append("and sal>:teasal "); } Query query = session.createQuery(hql.toString()); /*赋值*/ query.setParameter("teaAdd",teacher.getAddress()); query.setParameter("teasal",teacher.getSal()); /*查询*/ List list = query.list(); /*遍历*/ for (Object t:list) { System.out.println(t); } }