package org.niit.ormlab.example5; import java.io.Serializable; import java.util.Date; import java.util.HashSet; import java.util.Set; public class Depart implements Serializable { private Integer did; private String dname; private String ddesc; private Date dcreatetime; public Depart(String dname, String ddesc, Date dcreatetime, Set<Emp> emps) { super(); this.dname = dname; this.ddesc = ddesc; this.dcreatetime = dcreatetime; this.emps = emps; } public Depart(Integer did, String dname, String ddesc, Date dcreatetime, Set<Emp> emps) { super(); this.did = did; this.dname = dname; this.ddesc = ddesc; this.dcreatetime = dcreatetime; this.emps = emps; } public Date getDcreatetime() { return dcreatetime; } public void setDcreatetime(Date dcreatetime) { this.dcreatetime = dcreatetime; } private Set<Emp> emps = new HashSet<Emp>();//为了提高程序健壮性我们实例化这个属性避免产生空指针异常 public Depart(String dname, String ddesc, Set<Emp> emps) { super(); this.dname = dname; this.ddesc = ddesc; this.emps = emps; } public Set<Emp> getEmps() { return emps; } public void setEmps(Set<Emp> emps) { this.emps = emps; } public Depart() { } public Depart(String dname, String ddesc) { super(); this.dname = dname; this.ddesc = ddesc; } public Depart(Integer did, String dname, String ddesc) { super(); this.did = did; this.dname = dname; this.ddesc = ddesc; } public Integer getDid() { return did; } public void setDid(Integer did) { this.did = did; } public String getDname() { return dname; } public void setDname(String dname) { this.dname = dname; } public String getDdesc() { return ddesc; } public void setDdesc(String ddesc) { this.ddesc = ddesc; } } package org.niit.ormlab.example5; import java.io.Serializable; import java.util.*; public class Emp implements Serializable { private int eid; private String ename; private String esex; private String eaddr; private String etel; private Depart depart;//many to one private Set<Role> roles = new HashSet<Role>();//多对多 public Emp() { // TODO Auto-generated constructor stub } public Emp(String ename, String esex, String eaddr, String etel, Depart depart, Set<Role> roles) { super(); this.ename = ename; this.esex = esex; this.eaddr = eaddr; this.etel = etel; this.depart = depart; this.roles = roles; } public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } public Emp(int eid, String ename, String esex, String eaddr, String etel, Depart depart, Set<Role> roles) { super(); this.eid = eid; this.ename = ename; this.esex = esex; this.eaddr = eaddr; this.etel = etel; this.depart = depart; this.roles = roles; } public Emp(String ename, String esex, String eaddr, String etel, Depart depart) { super(); this.ename = ename; this.esex = esex; this.eaddr = eaddr; this.etel = etel; this.depart = depart; } public Emp(int eid, String ename, String esex, String eaddr, String etel, Depart depart) { super(); this.eid = eid; this.ename = ename; this.esex = esex; this.eaddr = eaddr; this.etel = etel; this.depart = depart; } public int getEid() { return eid; } public void setEid(int eid) { this.eid = eid; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getEsex() { return esex; } public void setEsex(String esex) { this.esex = esex; } public String getEaddr() { return eaddr; } public void setEaddr(String eaddr) { this.eaddr = eaddr; } public String getEtel() { return etel; } public void setEtel(String etel) { this.etel = etel; } public Depart getDepart() { return depart; } public void setDepart(Depart depart) { this.depart = depart; } } package org.niit.ormlab.example5; import java.io.Serializable; import java.util.*; public class Role implements Serializable { private int rid; private String rname; private String rdesc; private Set<Emp> emps = new HashSet<Emp>();//many to many public Role(String rname, String rdesc) { super(); this.rname = rname; this.rdesc = rdesc; } public Role(String rname, String rdesc, Set<Emp> emps) { super(); this.rname = rname; this.rdesc = rdesc; this.emps = emps; } public Role() { super(); } public Role(int rid, String rname, String rdesc, Set<Emp> emps) { super(); this.rid = rid; this.rname = rname; this.rdesc = rdesc; this.emps = emps; } public int getRid() { return rid; } public void setRid(int rid) { this.rid = rid; } public String getRname() { return rname; } public void setRname(String rname) { this.rname = rname; } public String getRdesc() { return rdesc; } public void setRdesc(String rdesc) { this.rdesc = rdesc; } public Set<Emp> getEmps() { return emps; } public void setEmps(Set<Emp> emps) { this.emps = emps; } } <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > <hibernate-mapping package="org.niit.ormlab.example5"> <!-- 多对一的【一方】 --> <class name="Depart" table="`Depart`"> <id name="did" column="did" type="integer"> <generator class="identity" /> </id> <property name="dname" column="dname" type="string" /> <property name="ddesc" column="ddesc" type="string" /> <property name="dcreatetime" column="dcreatetime" type="date"></property> <!-- 级联保存更新 --> <set name="emps" table="`Emp`" cascade="save-update,delete" lazy="false"> <!-- 外键信息 --> <key column="did"></key> <!-- 属性对应的类信息 --> <one-to-many class="Emp"/> </set> </class> </hibernate-mapping> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="org.niit.ormlab.example5"> <!-- 多对一的【多方】 --> <class name="Emp" table="`Emp`"> <id column="eid" name="eid" type="integer"> <generator class="identity"/> </id> <property column="ename" generated="never" lazy="false" name="ename" type="string"/> <property column="esex" generated="never" lazy="false" name="esex" type="string"/> <property column="`etel`" generated="never" lazy="false" name="etel" type="string"/> <property column="eaddr" generated="never" lazy="false" name="eaddr" type="string"/> <!-- many-to-one建立depart属性和外键did之间的映射 name=待映射的持久化类的属性名【Emp类的depart属性】 class=持久化类名 cascade=级联行为 not-null=是否允许为空,影响Hibernate的保存时行为 --> <many-to-one cascade="save-update" class="Depart" column="did" name="depart" not-null="true"/> <set cascade="save-update" inverse="true" lazy="true" name="roles" sort="unsorted" table="`roleemp`"> <key column="eid" not-null="true"/> <many-to-many class="Role" column="rid" unique="false"/> </set> </class> <query name="getEmpsByNameAndAddr"> <!--[CDATA[from Emp as e where e.ename like :ename and e.eaddr=:eaddr]]> </query> <sql-query name="findDepartByName"> <![CDATA[select {d.*} from Depart as d where d.dname like :dname]]--> <return alias="d" class="Depart"></return> </sql-query> </hibernate-mapping> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > <hibernate-mapping package="org.niit.ormlab.example5"> <!-- 多对一的【多方】 --> <class name="Role" table="`Role`"> <id name="rid" column="rid" type="integer"> <generator class="identity" /> </id> <property name="rname"></property> <property name="rdesc"></property> <set name="emps" cascade="save-update" lazy="true" table="roleemp" > <key column="rid" not-null="true"></key> <many-to-many class="Emp" column="eid" /> </set> </class> </hibernate-mapping> 测试一: package org.niit.ormlab.example5; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hibernate.Hibernate; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import org.niit.ormlab.example5.pagination.Operation; import org.niit.ormlab.example5.pagination.PCondition; import org.niit.ormlab.example5.pagination.PDirect; import org.niit.ormlab.example5.pagination.POrder; import org.niit.ormlab.example5.pagination.PageInfo; /** * Hibernate的检索方式-HQL检索方式 * */ public class Client1 { /**带参数查询[按参数名绑定,同名参数可以出现多次,优先考虑这种方式]*/ public void getEmps1(){ Session session = SessionFactory.getSession(); try { List<Emp> emps = session .createQuery("from Emp as e where e.ename like :ename and e.eaddr=:eaddr") .setString("ename", "%王%") .setString("eaddr","成都市武侯区") .list(); for (Emp emp : emps) { System.out.println(emp.getEid()+"/t"+emp.getEname()); } } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } } /**带参数查询[按参数位置绑定]*/ public void getEmps2(){ Session session = SessionFactory.getSession(); try { List<Emp> emps = session .createQuery("from Emp as e where e.ename like ? and e.eaddr=?") .setString(0, "%王%") .setString(1,"成都市武侯区") .list(); for (Emp emp : emps) { System.out.println(emp.getEid()+"/t"+emp.getEname()); } } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } } /**带参数查询[按参数名绑定,同名参数可以出现多次,优先考虑这种方式]*/ public void getEmps3(){ Session session = SessionFactory.getSession(); try { List<Emp> emps = session .createQuery("from Emp as e where e.ename like :ename and e.eaddr=:eaddr") .setParameter("ename", "%王%",Hibernate.STRING) .setParameter("eaddr","成都市武侯区",Hibernate.STRING) .list(); for (Emp emp : emps) { System.out.println(emp.getEid()+"/t"+emp.getEname()); } } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } } /**带参数查询[按参数名绑定,同名参数可以出现多次,优先考虑这种方式],日期的特殊处理方式*/ public void getDepart1(){ Session session = SessionFactory.getSession(); try { List<Depart> departs = session .createQuery("from Depart as d where d.dcreatetime>=:dcreatetime") .setParameter("dcreatetime",Calendar.getInstance().getTime(),Hibernate.DATE) .list(); for (Depart depart : departs) { System.out.println(depart.getDid()+"/t"+depart.getDname()+"/t/t"+depart.getDcreatetime()); } } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } } /**带参数查询[按参数名绑定,同名参数可以出现多次,优先考虑这种方式],使用setProperties把命名参数同一个对象的属性绑定*/ public void getDepart2(){ Session session = SessionFactory.getSession(); try { Depart exampleDepart = new Depart(); exampleDepart.setDcreatetime(Calendar.getInstance().getTime()); exampleDepart.setDname("%技术%"); List<Depart> departs = session .createQuery("from Depart as d where d.dcreatetime>=:dcreatetime and d.dname like :dname") .setProperties(exampleDepart) .list(); for (Depart depart : departs) { System.out.println(depart.getDid()+"/t"+depart.getDname()+"/t/t"+depart.getDcreatetime()); } } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } } /** * @param d */ public void getEmpsByDepart(Depart d){ Session session = SessionFactory.getSession(); try { // List<Emp> emps = // session // .createQuery("from Emp as e where e.depart=:depart") // .setEntity("depart", d) // .list(); List<Emp> emps = session .createQuery("from Emp as e where e.depart=:depart") .setParameter("depart", d,Hibernate.entity(Depart.class)) .list(); for (Emp emp : emps) { System.out.println(emp.getEid()+"/t"+emp.getEname()); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally{ session.close(); } } /** * 预处理条件 * */ private Object[] prepareCondtion(String aliaName,PageInfo pi){ if (aliaName==null || pi==null || pi.getPconditionList()==null || pi.getPconditionList().size()==0){ return null; } Object[] results = new Object[2]; Map<String,Object> pcdMap = new HashMap<String, Object>();//存放条件值的键值对 StringBuilder conditionBuilder = new StringBuilder(" where ");//存放条件语句的Builder for (PCondition pcd : pi.getPconditionList()) { pcdMap.put(pcd.getPropertyName(), pcd.getPropertyValue()); conditionBuilder.append(aliaName+"."+pcd.getPropertyName()); switch (pcd.getOpt()) { case PEQ: conditionBuilder.append("=:"+pcd.getPropertyName()); break; case PGT: conditionBuilder.append(">:"+pcd.getPropertyName()); break; case PLT: conditionBuilder.append("<:"+pcd.getPropertyName()); break; case PGE: conditionBuilder.append(">=:"+pcd.getPropertyName()); break; case PLE: conditionBuilder.append("<=:"+pcd.getPropertyName()); break; case PNE: conditionBuilder.append("<>:"+pcd.getPropertyName()); break; case PLIKE: conditionBuilder.append(" like :"+pcd.getPropertyName()); pcdMap.put(pcd.getPropertyName(),"%"+pcd.getPropertyValue().toString()+"%"); break; default: break; } conditionBuilder.append(" and "); } //remove the " and "; if (conditionBuilder.length()>1){ conditionBuilder.delete(conditionBuilder.length()-" and ".length(), conditionBuilder.length()); } results[0] = conditionBuilder.toString(); results[1] = pcdMap; return results; } /**预处理排序*/ private String prepareOrder(String aliaName,PageInfo pi){ if(aliaName==null || pi==null || pi.getPorderLlist()==null || pi.getPorderLlist().size()==0){ return null; } StringBuilder result = new StringBuilder(" order by "); for (POrder pf : pi.getPorderLlist()) { switch (pf.getPdirect()) { case ASC: result.append(aliaName+"."+pf.getPropertyName()+" asc"); break; case DESC: result.append(aliaName+"."+pf.getPropertyName()+" desc"); break; default: break; } result.append(","); } if (result.length()>1){ result.delete(result.length()-1,result.length()); } return result.toString(); } public void Pager(PageInfo pi){ Session session = SessionFactory.getSession(); String HQL_ROW_COUNT = "select count(d) from Depart as d "; String HQL_PAGER = "from Depart as d "; try { //总条数 Object[] pcdResult = prepareCondtion("d", pi); String order = prepareOrder("d", pi); HQL_ROW_COUNT+=pcdResult[0].toString(); HQL_PAGER+=pcdResult[0].toString(); HQL_PAGER+=" "+order; Map<String,Object> conditionMap = (Map<String,Object>)pcdResult[1]; Query query = session.createQuery(HQL_ROW_COUNT); for (String propertyName : conditionMap.keySet()) { query.setParameter(propertyName,conditionMap.get(propertyName)); } pi.setRecordCount(Integer.parseInt(query.uniqueResult().toString())); //总页数 pi.setPageCount( pi.getRecordCount() % pi.getPageSize() ==0? pi.getRecordCount()/pi.getPageSize(): pi.getRecordCount()/pi.getPageSize()+1 ); //分页 Query queryPager = session.createQuery(HQL_PAGER); for (String propertyName : conditionMap.keySet()) { queryPager.setParameter(propertyName,conditionMap.get(propertyName)); } pi.setResult( queryPager .setFirstResult((pi.getPageIndex()-1)*pi.getPageSize()) .setMaxResults(pi.getPageSize()) .list() ); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { session.close(); } } public static void main(String[] args) { Client1 c = new Client1(); //c.getEmps2(); // Depart d = new Depart(); // d.setDid(18); // c.getEmpsByDepart(d); //c.getDepart1(); c.getDepart2(); //分页测试 // PageInfo pi = new PageInfo(); // pi.setClazz(Depart.class); // pi.getPconditionList().add(new PCondition("dname", Operation.PLIKE, "技术")); // pi.getPconditionList().add(new PCondition("did", Operation.PGE, 20)); // pi.getPorderLlist().add(new POrder("did", PDirect.ASC)); // pi.getPorderLlist().add(new POrder("dname", PDirect.ASC)); // c.Pager(pi); // // System.out.printf("共%d条%d页 当前第%d页/n",pi.getRecordCount(),pi.getPageCount(),pi.getPageIndex()); // for(Depart d: (List<Depart>)pi.getResult()){ // System.out.println("/t"+d.getDid()+"/t"+d.getDname()+"/t"+d.getDdesc()); // } } } 测试二: package org.niit.ormlab.example5; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Expression; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.niit.ormlab.example5.pagination.PCondition; import org.niit.ormlab.example5.pagination.POrder; import org.niit.ormlab.example5.pagination.PageInfo; /** * Hibernate的检索方式-QBC检索方式 * */ public class Client2 { /**带参数查询*/ public void getEmps1(){ Session session = SessionFactory.getSession(); try { List<Emp> emps = session .createCriteria(Emp.class) .add(Expression.like("ename", "%王%")) .add(Restrictions.eq("eaddr", "成都市武侯区")) .list(); for (Emp emp : emps) { System.out.println(emp.getEid()+"/t"+emp.getEname()); } } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } } /** * 预处理条件 * */ private void prepareCondition(Criteria qbc,PageInfo pi){ if (pi.getPconditionList()!=null && pi.getPconditionList().size()>0){ for (PCondition pcd : pi.getPconditionList()) { switch (pcd.getOpt()) { case PEQ: qbc.add(Restrictions.eq(pcd.getPropertyName(),pcd.getPropertyValue())); break; case PGT: qbc.add(Restrictions.gt(pcd.getPropertyName(),pcd.getPropertyValue())); break; case PNE: qbc.add(Restrictions.ne(pcd.getPropertyName(),pcd.getPropertyValue())); break; case PLT: qbc.add(Restrictions.lt(pcd.getPropertyName(),pcd.getPropertyValue())); break; case PLE: qbc.add(Restrictions.le(pcd.getPropertyName(),pcd.getPropertyValue())); break; case PLIKE: qbc.add(Restrictions.like(pcd.getPropertyName(),pcd.getPropertyValue()==null?"":pcd.getPropertyValue().toString(),MatchMode.ANYWHERE)); break; default: break; } } } } /** * 预处理排序 * */ private void PrepareOrderField(Criteria qbc,PageInfo pi){ if (qbc==null || pi==null || pi.getPorderLlist()==null || pi.getPorderLlist().size()==0){ return; } for (POrder orderfield : pi.getPorderLlist()) { switch (orderfield.getPdirect()) { case ASC: qbc.addOrder(Order.asc(orderfield.getPropertyName())); break; case DESC: qbc.addOrder(Order.desc(orderfield.getPropertyName())); break; default: break; } } } public void pager(PageInfo pi){ Session session = SessionFactory.getSession(); try { Criteria qbc = session.createCriteria(Emp.class); qbc.setProjection(Projections.rowCount());//设置投影【查询总条数】 prepareCondition(qbc, pi);//处理条件 pi.setRecordCount(Integer.parseInt(qbc.uniqueResult().toString()));//得到总条数 pi.setPageCount( pi.getRecordCount()%pi.getPageSize()==0? pi.getRecordCount()/pi.getPageSize(): pi.getRecordCount()/pi.getPageSize()+1 );//计算总页数 qbc.setProjection(null);//清空投影设置 //开始分页 PrepareOrderField(qbc, pi);//处理排序 qbc.setFirstResult((pi.getPageIndex()-1)*pi.getPageSize());//设置第一条索引 qbc.setMaxResults(pi.getPageSize());//设置要显示的条数 pi.setResult(qbc.list()); } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } } public static void main(String[] args) { Client2 c = new Client2(); c.getEmps1(); } } 测试三: package org.niit.ormlab.example5; import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Expression; import org.hibernate.criterion.Restrictions; /** * Hibernate的检索方式-SQL检索方式 * */ public class Client3 { /**带参数查询*/ public void getEmps1(){ Session session = SessionFactory.getSession(); try { List<Emp> emps = session .createSQLQuery("select {e.*} from Emp e where e.ename like :ename and e.eaddr=:eaddr") .addEntity("e",Emp.class) .setString("ename", "%王%") .setString("eaddr", "成都市武侯区") .list(); for (Emp emp : emps) { System.out.println(emp.getEid()+"/t"+emp.getEname()); } } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } } public void getEmps2(){ } public static void main(String[] args) { Client3 c = new Client3(); c.getEmps1(); } } 测试四: package org.niit.ormlab.example5; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hibernate.Hibernate; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import org.niit.ormlab.example5.pagination.Operation; import org.niit.ormlab.example5.pagination.PCondition; import org.niit.ormlab.example5.pagination.PDirect; import org.niit.ormlab.example5.pagination.POrder; import org.niit.ormlab.example5.pagination.PageInfo; /** * Hibernate的检索方式-HQL检索方式 * */ public class Client4 { /**带参数查询-命名Hql查询[按参数名绑定,同名参数可以出现多次,优先考虑这种方式]*/ public void getEmps1(){ Session session = SessionFactory.getSession(); try { List<Emp> emps = session .getNamedQuery("getEmpsByNameAndAddr") .setString("ename", "%王%") .setString("eaddr","成都市武侯区") .list(); for (Emp emp : emps) { System.out.println(emp.getEid()+"/t"+emp.getEname()); } } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } } /**带参数查询-命名Sql查询[按参数名绑定,同名参数可以出现多次,优先考虑这种方式]*/ public void getDepart1(){ Session session = SessionFactory.getSession(); try { List<Depart> departs = session .getNamedQuery("findDepartByName") .setParameter("dname", "%技术%",Hibernate.STRING) .list(); for (Depart depart : departs) { System.out.println(depart.getDid()+"/t"+depart.getDname()); } } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } } public static void main(String[] args) { Client4 c = new Client4(); //c.getEmps1(); c.getDepart1(); } }