二十五 SQL和命名查询
SQL和命名查询SQL查询//根据sql语句查询static List sql(){ Session s=HibernateUtil.getSession(); Query q=s.createSQLQuery("select * from department").addEntity(Department.class); List<Department> l=q.list(); return l;}一般情况下避免使用sql查询,因为Hibernate具有很好的数据库移植性,如果写死了sql语句的话移植的时候会出现一些问题。也可以把hql查询条件写在映射配置文件中,然后java去读取语句来进行查询,称为本地命名查询。本地命名查询修改映射实体的映射文件<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="vo.util.bean"><class name="Department"><id name="id"><generator /></set><!-- class节点内配置命名查询条件 --><query name="getname1"> <![CDATA[from Department where name=:name]]> </query></class><!-- 配置命名在class节点外查询条件 --><query name="getname2"><![CDATA[from Department where name=:name]]></query></hibernate-mapping>查询测试//映射文件class节点外的配置命名查询static List namesel(String name){ Session s=HibernateUtil.getSession(); Query q=s.getNamedQuery("getname2"); q.setString("name", name); List l=q.list(); return l;}//映射文件class节点内的配置命名查询static List namese(String name){ Session s=HibernateUtil.getSession(); Query q=s.getNamedQuery("vo.util.bean.Department.getname1"); q.setString("name", name); List l=q.list(); return l;}分析比较 发现getNamedQuery的查询条件并不相同,在class节点内 查询的条件命名必须加上实体包名.实体名.查询命名 在这必须是完整的命名名称在class节点外 查询的条件命名只需要实体命名即可完整的测试package vo.util.test;import java.util.HashSet;import java.util.List;import java.util.Set;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;import vo.util.HibernateUtil;import vo.util.bean.Department;import vo.util.bean.Employee;public class SQLandNameTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubadd(); //sql();namesel("政企事业部");namese("政企事业部");}//根据sql语句查询static List sql(){Session s=HibernateUtil.getSession();Query q=s.createSQLQuery("select * from department").addEntity(Department.class);List<Department> l=q.list();return l;}//映射文件class节点外的配置命名查询static List namesel(String name){Session s=HibernateUtil.getSession();Query q=s.getNamedQuery("getname2");q.setString("name", name);List l=q.list();return l;}//映射文件class节点内的配置命名查询static List namese(String name){Session s=HibernateUtil.getSession();Query q=s.getNamedQuery("vo.util.bean.Department.getname1");q.setString("name", name);List l=q.list();return l;} static Department add(){ Session session = null; Transaction tx = null; try{ session =HibernateUtil.getSession(); tx = session.beginTransaction(); //…你的代码save,delete,update,get… Department dpart=new Department(); dpart.setName("政企事业部"); Employee em1=new Employee(); em1.setName("员工李小仙"); //em1.setDerpartment(dpart); Employee em2=new Employee(); em2.setName("员工张小三"); //em2.setDerpartment(dpart); Set<Employee> em=new HashSet<Employee>(); em.add(em1); em.add(em2); dpart.setEms(em); session.save(dpart); session.save(em1); session.save(em2); tx.commit(); return dpart; }finally{ if(session != null)session.close(); } }}完毕 end!
?