Hibernate的手动基本配置和DAO类增删改查方法的封装

使用所有的框架都一样,导jar包和配置相应的文件,以下就是hibernate手动配置的代码。(熟练之后可以利用MyEclipse的自带工具直接进行框架的搭建)

一、导入hibernate的基本包

二、文件的配置(hibernate.cfg.xml),配置最基本的连接数据库信息和相应的方言

  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5.   
  6. <!-- Generated by MyEclipse Hibernate Tools.                   -->  
  7. <hibernate-configuration>  
  8.   
  9.     <session-factory>  
  10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
  11.         <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:ORCL</property>  
  12.         <property name="connection.username">sa</property>  
  13.         <property name="connection.password">sa</property>  
  14.         <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>  
  15.         <property name="myeclipse.connection.profile">ora</property>  
  16.       
  17.         <mapping resource="com/bean/Teacher.hbm.xml"/>  
  18.         <mapping resource="com/bean/ClassInfo.hbm.xml"/>  
  19.         <mapping resource="com/bean/Student.hbm.xml"/>  
  20.     </session-factory>  
  21.       
  22.   
  23. </hibernate-configuration>  
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
        <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:ORCL</property>
        <property name="connection.username">sa</property>
        <property name="connection.password">sa</property>
        <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
        <property name="myeclipse.connection.profile">ora</property>
    
    	<mapping resource="com/bean/Teacher.hbm.xml"/>
    	<mapping resource="com/bean/ClassInfo.hbm.xml"/>
    	<mapping resource="com/bean/Student.hbm.xml"/>
    </session-factory>
    

</hibernate-configuration>

三、项目所有包文件截图

四、配置对应bean 的xml映射文件(com.bean报下)

   1.教师bean类

  1. package com.bean;  
  2.   
  3. import java.math.BigDecimal;  
  4.   
  5. public class Teacher {  
  6.   
  7.     private BigDecimal tid;  
  8.     private String tname;  
  9.     private BigDecimal tage;  
  10.     public BigDecimal getTid() {  
  11.         return tid;  
  12.     }  
  13.     public void setTid(BigDecimal tid) {  
  14.         this.tid = tid;  
  15.     }  
  16.     public String getTname() {  
  17.         return tname;  
  18.     }  
  19.     public void setTname(String tname) {  
  20.         this.tname = tname;  
  21.     }  
  22.     public BigDecimal getTage() {  
  23.         return tage;  
  24.     }  
  25.     public void setTage(BigDecimal tage) {  
  26.         this.tage = tage;  
  27.     }  
  28.     public Teacher(BigDecimal tid, String tname, BigDecimal tage) {  
  29.         super();  
  30.         this.tid = tid;  
  31.         this.tname = tname;  
  32.         this.tage = tage;  
  33.     }  
  34.     public Teacher() {  
  35.         // TODO Auto-generated constructor stub  
  36.     }  
  37. }  
package com.bean;

import java.math.BigDecimal;

public class Teacher {

	private BigDecimal tid;
	private String tname;
	private BigDecimal tage;
	public BigDecimal getTid() {
		return tid;
	}
	public void setTid(BigDecimal tid) {
		this.tid = tid;
	}
	public String getTname() {
		return tname;
	}
	public void setTname(String tname) {
		this.tname = tname;
	}
	public BigDecimal getTage() {
		return tage;
	}
	public void setTage(BigDecimal tage) {
		this.tage = tage;
	}
	public Teacher(BigDecimal tid, String tname, BigDecimal tage) {
		super();
		this.tid = tid;
		this.tname = tname;
		this.tage = tage;
	}
	public Teacher() {
		// TODO Auto-generated constructor stub
	}
}


       教师bean类对应的xml映射文件配置

(class中的name是bean类,table是数据库对应的表名,不要写错。id为数据表的主键,其余均为该表属性,教师表死最简单的一个表,不牵扯任何外键管理,下一张班级表就会牵扯外键关系。)

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <!--   
  5.     Mapping file autogenerated by MyEclipse Persistence Tools  
  6. -->  
  7. <hibernate-mapping>  
  8. <class name="com.bean.Teacher" table="teacher" schema="sa">  
  9. <id name="tid" column="tid" type="java.math.BigDecimal">  
<?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">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.bean.Teacher" table="teacher" schema="sa">
<id name="tid" column="tid" type="java.math.BigDecimal">
  1. <generator class="assigned"></generator>  
<generator class="assigned"></generator>
  1. </id>  
  2. <property name="tname" column="tname" type="java.lang.String"></property>  
  3. <property name="tage" column="tage" type="java.math.BigDecimal"></property>  
  4. </class>  
  5. </hibernate-mapping>  
</id>
<property name="tname" column="tname" type="java.lang.String"></property>
<property name="tage" column="tage" type="java.math.BigDecimal"></property>
</class>
</hibernate-mapping>

=============================================================================================================================
  2.班级bean类

  1. package com.bean;  
  2.   
  3. public class ClassInfo {  
  4.   
  5.     public String clid;  
  6.     public String cltitle;  
  7.     public Teacher teacher;  
  8.     public String getClid() {  
  9.         return clid;  
  10.     }  
  11.     public void setClid(String clid) {  
  12.         this.clid = clid;  
  13.     }  
  14.     public String getCltitle() {  
  15.         return cltitle;  
  16.     }  
  17.     public void setCltitle(String cltitle) {  
  18.         this.cltitle = cltitle;  
  19.     }  
  20.     public Teacher getTeacher() {  
  21.         return teacher;  
  22.     }  
  23.     public void setTeacher(Teacher teacher) {  
  24.         this.teacher = teacher;  
  25.     }  
  26.     public ClassInfo(String clid, String cltitle, Teacher teacher) {  
  27.         this.clid = clid;  
  28.         this.cltitle = cltitle;  
  29.         this.teacher = teacher;  
  30.     }  
  31.     public ClassInfo() {  
  32.     }  
  33.       
  34. }  
package com.bean;

public class ClassInfo {

	public String clid;
	public String cltitle;
	public Teacher teacher;
	public String getClid() {
		return clid;
	}
	public void setClid(String clid) {
		this.clid = clid;
	}
	public String getCltitle() {
		return cltitle;
	}
	public void setCltitle(String cltitle) {
		this.cltitle = cltitle;
	}
	public Teacher getTeacher() {
		return teacher;
	}
	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}
	public ClassInfo(String clid, String cltitle, Teacher teacher) {
		this.clid = clid;
		this.cltitle = cltitle;
		this.teacher = teacher;
	}
	public ClassInfo() {
	}
	
}

班级bena类对应的xml映射文件的配置

(因为每个班级有一个带班老师,因此牵扯到了外键。xml配置中外键用<many-to-one name="teacher" column="tid" class="com.bean.Teacher"></many-to-one>,name为班级bean类的属性名称,coloumn为对应数据库的字段名称)

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <!--  
  5.     Mapping file autogenerated by MyEclipse Persistence Tools 
  6. -->  
  7. <hibernate-mapping>  
  8. <class name="com.bean.ClassInfo" table="classinfo" schema="sa">  
  9. <id name="clid" column="clid" type="java.lang.String">  
<?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">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.bean.ClassInfo" table="classinfo" schema="sa">
<id name="clid" column="clid" type="java.lang.String">
  1. <generator class="assigned"></generator>  
<generator class="assigned"></generator>
  1. </id>  
  2. <property name="cltitle" column="cltitle" type="java.lang.String"></property>  
  3. <many-to-one name="teacher" column="tid" class="com.bean.Teacher"></many-to-one>  
  4. </class>  
  5. </hibernate-mapping>  
</id>
<property name="cltitle" column="cltitle" type="java.lang.String"></property>
<many-to-one name="teacher" column="tid" class="com.bean.Teacher"></many-to-one>
</class>
</hibernate-mapping>


=================================================================================================================================

3.角色权限中间表的配置(因为实际需求中,很可能会有中间表存在,而中间表该如何配置呢?我先给大家发完bean类再发xml配置)

权限bean类(Pop)

  1. package com.bean;  
  2.   
  3. import java.math.BigDecimal;  
  4.   
  5. public class Pop {  
  6.   
  7.     private BigDecimal pid;  
  8.     private String ptitle;  
  9.     public BigDecimal getPid() {  
  10.         return pid;  
  11.     }  
  12.     public void setPid(BigDecimal pid) {  
  13.         this.pid = pid;  
  14.     }  
  15.     public String getPtitle() {  
  16.         return ptitle;  
  17.     }  
  18.     public void setPtitle(String ptitle) {  
  19.         this.ptitle = ptitle;  
  20.     }  
  21.     public Pop(BigDecimal pid, String ptitle) {  
  22.         super();  
  23.         this.pid = pid;  
  24.         this.ptitle = ptitle;  
  25.     }  
  26.     public Pop() {  
  27.         // TODO Auto-generated constructor stub  
  28.     }  
  29. }  
package com.bean;

import java.math.BigDecimal;

public class Pop {

	private BigDecimal pid;
	private String ptitle;
	public BigDecimal getPid() {
		return pid;
	}
	public void setPid(BigDecimal pid) {
		this.pid = pid;
	}
	public String getPtitle() {
		return ptitle;
	}
	public void setPtitle(String ptitle) {
		this.ptitle = ptitle;
	}
	public Pop(BigDecimal pid, String ptitle) {
		super();
		this.pid = pid;
		this.ptitle = ptitle;
	}
	public Pop() {
		// TODO Auto-generated constructor stub
	}
}

角色bean类 (UserType)

  1. package com.bean;  
  2.   
  3. import java.math.BigDecimal;  
  4.   
  5. public class UserType {  
  6.   
  7.     private BigDecimal utid;  
  8.     private String utname;  
  9.     public BigDecimal getUtid() {  
  10.         return utid;  
  11.     }  
  12.     public void setUtid(BigDecimal utid) {  
  13.         this.utid = utid;  
  14.     }  
  15.     public String getUtname() {  
  16.         return utname;  
  17.     }  
  18.     public void setUtname(String utname) {  
  19.         this.utname = utname;  
  20.     }  
  21.     public UserType(BigDecimal utid, String utname) {  
  22.         super();  
  23.         this.utid = utid;  
  24.         this.utname = utname;  
  25.     }  
  26.     public UserType() {  
  27.         // TODO Auto-generated constructor stub  
  28.     }  
  29. }  
package com.bean;

import java.math.BigDecimal;

public class UserType {

	private BigDecimal utid;
	private String utname;
	public BigDecimal getUtid() {
		return utid;
	}
	public void setUtid(BigDecimal utid) {
		this.utid = utid;
	}
	public String getUtname() {
		return utname;
	}
	public void setUtname(String utname) {
		this.utname = utname;
	}
	public UserType(BigDecimal utid, String utname) {
		super();
		this.utid = utid;
		this.utname = utname;
	}
	public UserType() {
		// TODO Auto-generated constructor stub
	}
}

中间表UtAndPopID类(类中属性为Pop和UserType)

  1. package com.bean;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class UtAndPopID implements Serializable {  
  6.   
  7.     private UserType ut;  
  8.     private Pop p;  
  9.     public UserType getUt() {  
  10.         return ut;  
  11.     }  
  12.     public void setUt(UserType ut) {  
  13.         this.ut = ut;  
  14.     }  
  15.     public Pop getP() {  
  16.         return p;  
  17.     }  
  18.     public void setP(Pop p) {  
  19.         this.p = p;  
  20.     }  
  21.     public UtAndPopID(UserType ut, Pop p) {  
  22.         super();  
  23.         this.ut = ut;  
  24.         this.p = p;  
  25.     }  
  26.     public UtAndPopID() {  
  27.     }  
  28. }  
package com.bean;

import java.io.Serializable;

public class UtAndPopID implements Serializable {

	private UserType ut;
	private Pop p;
	public UserType getUt() {
		return ut;
	}
	public void setUt(UserType ut) {
		this.ut = ut;
	}
	public Pop getP() {
		return p;
	}
	public void setP(Pop p) {
		this.p = p;
	}
	public UtAndPopID(UserType ut, Pop p) {
		super();
		this.ut = ut;
		this.p = p;
	}
	public UtAndPopID() {
	}
}

中间表UtAndPop(属性为UtAndPopID)

  1. package com.bean;  
  2.   
  3. public class UtAndPop {  
  4.   
  5.     UtAndPopID utandpopid;  
  6.   
  7.     public UtAndPopID getUtandpopid() {  
  8.         return utandpopid;  
  9.     }  
  10.   
  11.     public void setUtandpopid(UtAndPopID utandpopid) {  
  12.         this.utandpopid = utandpopid;  
  13.     }  
  14.     public UtAndPop(UtAndPopID utandpopid) {  
  15.         this.utandpopid = utandpopid;  
  16.     }  
  17.   
  18.     public UtAndPop() {  
  19.         // TODO Auto-generated constructor stub  
  20.     }  
  21. }  
package com.bean;

public class UtAndPop {

	UtAndPopID utandpopid;

	public UtAndPopID getUtandpopid() {
		return utandpopid;
	}

	public void setUtandpopid(UtAndPopID utandpopid) {
		this.utandpopid = utandpopid;
	}
	public UtAndPop(UtAndPopID utandpopid) {
		this.utandpopid = utandpopid;
	}

	public UtAndPop() {
		// TODO Auto-generated constructor stub
	}
}

Pop和UserType的xml映射文件配置和teacher的差不多我就不发了 ,这里只发下中间表的配置

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <!--  
  5.     Mapping file autogenerated by MyEclipse Persistence Tools 
  6. -->  
  7. <hibernate-mapping>  
  8. <class name="com.bean.UtAndPop" table="ut_and_pop" schema="sa">  
  9. <composite-id name="utandpopid" class="com.bean.UtAndPopID">  
  10. <key-many-to-one name="ut" column="utid" class="com.bean.UserType"></key-many-to-one>  
  11. <key-many-to-one name="p" column="pid" class="com.bean.Pop"></key-many-to-one>  
  12. </composite-id>  
  13. </class>  
  14. </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">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.bean.UtAndPop" table="ut_and_pop" schema="sa">
<composite-id name="utandpopid" class="com.bean.UtAndPopID">
<key-many-to-one name="ut" column="utid" class="com.bean.UserType"></key-many-to-one>
<key-many-to-one name="p" column="pid" class="com.bean.Pop"></key-many-to-one>
</composite-id>
</class>
</hibernate-mapping>

*************当你配置完成之后 还需要在hibernate.cfg.xml中进行相关的配置这些映射文件才会好用(在<mapping />中加入映射文件的路径)

  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5.   
  6. <!-- Generated by MyEclipse Hibernate Tools.                   -->  
  7. <hibernate-configuration>  
  8.   
  9.     <session-factory>  
  10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
  11.         <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:ORCL</property>  
  12.         <property name="connection.username">sa</property>  
  13.         <property name="connection.password">sa</property>  
  14.         <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>  
  15.         <property name="myeclipse.connection.profile">ora</property>  
  16.       
  17.       
  18.         <mapping resource="com/bean/Teacher.hbm.xml"/>  
  19.         <mapping resource="com/bean/ClassInfo.hbm.xml"/>  
  20.         <mapping resource="com/bean/UtAndPop.hbm.xml"/>  
  21.     </session-factory>  
  22.       
  23.   
  24. </hibernate-configuration>  
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
        <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:ORCL</property>
        <property name="connection.username">sa</property>
        <property name="connection.password">sa</property>
        <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
        <property name="myeclipse.connection.profile">ora</property>
    
    
    	<mapping resource="com/bean/Teacher.hbm.xml"/>
    	<mapping resource="com/bean/ClassInfo.hbm.xml"/>
    	<mapping resource="com/bean/UtAndPop.hbm.xml"/>
    </session-factory>
    

</hibernate-configuration>


五、获得session操作数据库(com.sessionmanage包下)

MySessionFactory.java

  1. package com.sessionmanage;  
  2.   
  3. import org.hibernate.SessionFactory;  
  4. import org.hibernate.cfg.Configuration;  
  5. import org.hibernate.classic.Session;  
  6.   
  7. public class MySessionFactory {  
  8.   
  9.     public static SessionFactory sft=new Configuration().configure().buildSessionFactory();  
  10.     public static Session getSession(){  
  11.         //这里的session和之前的连接池差不多   
  12.         Session session=sft.openSession();  
  13.         return (session!=null)?session:null;  
  14.     }  
  15. }  
package com.sessionmanage;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

public class MySessionFactory {

	public static SessionFactory sft=new Configuration().configure().buildSessionFactory();
	public static Session getSession(){
		//这里的session和之前的连接池差不多
		Session session=sft.openSession();
		return (session!=null)?session:null;
	}
}

六、编写工具CriteriaPoJo,为了实现系统DAO中封装criteria方式的查询方法做准备(hibernate中有hql和criteria两种查询方式)

CriteriaPoJo.java

  1. package com.tool;  
  2.   
  3. public class CriteriaPoJo {  
  4.   
  5.     //这里只是写了几个方法,当然以后我们可以将其所有的都写出来,虽然这个类有点麻烦,但是以后子类调用时会简单很多  
  6.     public static final Integer IDEQ=1;  
  7.     public static final Integer LIKE=2;  
  8.     public static final Integer BETWEEN=3;  
  9.     public static final Integer ISNULL=4;  
  10.       
  11.       
  12.     private Integer wtd;  
  13.     private String property;  
  14.     private Object[] values;  
  15.     public Integer getWtd() {  
  16.         return wtd;  
  17.     }  
  18.     public void setWtd(Integer wtd) {  
  19.         this.wtd = wtd;  
  20.     }  
  21.     public String getProperty() {  
  22.         return property;  
  23.     }  
  24.     public void setProperty(String property) {  
  25.         this.property = property;  
  26.     }  
  27.     public Object[] getValues() {  
  28.         return values;  
  29.     }  
  30.     public void setValues(Object[] values) {  
  31.         this.values = values;  
  32.     }  
  33.     public CriteriaPoJo(Integer wtd, String property, Object[] values) {  
  34.         this.wtd = wtd;  
  35.         this.property = property;  
  36.         this.values = values;  
  37.     }  
  38.     public CriteriaPoJo() {  
  39.     }  
  40. }  
package com.tool;

public class CriteriaPoJo {

	//这里只是写了几个方法,当然以后我们可以将其所有的都写出来,虽然这个类有点麻烦,但是以后子类调用时会简单很多
	public static final Integer IDEQ=1;
	public static final Integer LIKE=2;
	public static final Integer BETWEEN=3;
	public static final Integer ISNULL=4;
	
	
	private Integer wtd;
	private String property;
	private Object[] values;
	public Integer getWtd() {
		return wtd;
	}
	public void setWtd(Integer wtd) {
		this.wtd = wtd;
	}
	public String getProperty() {
		return property;
	}
	public void setProperty(String property) {
		this.property = property;
	}
	public Object[] getValues() {
		return values;
	}
	public void setValues(Object[] values) {
		this.values = values;
	}
	public CriteriaPoJo(Integer wtd, String property, Object[] values) {
		this.wtd = wtd;
		this.property = property;
		this.values = values;
	}
	public CriteriaPoJo() {
	}
}

七、编写DAO类(com.dao包下)

SysDAO.java(抽象父类方法,供子类DAO调用)

  1. package com.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.Criteria;  
  6. import org.hibernate.Query;  
  7. import org.hibernate.Transaction;  
  8. import org.hibernate.classic.Session;  
  9. import org.hibernate.criterion.Criterion;  
  10. import org.hibernate.criterion.Restrictions;  
  11.   
  12. import com.sessionmanage.MySessionFactory;  
  13. import com.tool.CriteriaPoJo;  
  14. public abstract class SysDAO {  
  15.     public static final int ADD=1;  
  16.     public static final int DEL=2;  
  17.     public static final int UPD=3;  
  18.       
  19.     public abstract boolean insert(Object ob);  
  20.     public abstract boolean delete(Object ob);  
  21.     public abstract boolean update(Object ob);  
  22.     public abstract List findAll();  
  23.     public abstract Object findById(Object ob);  
  24.       
  25.     //封装Criterion,供Criteria查询自身调用   
  26.     private Criterion getCriterion(CriteriaPoJo cp){  
  27.         if(cp.getWtd()==cp.IDEQ){  
  28.             return Restrictions.idEq(cp.getValues()[0]);  
  29.         }  
  30.         if(cp.getWtd()==cp.LIKE){  
  31.             return Restrictions.like(cp.getProperty(), "%"+cp.getValues()[0]+"%");  
  32.         }  
  33.         if(cp.getWtd()==cp.BETWEEN){  
  34.             if(cp.getValues().length<2)  
  35.                 return null;  
  36.             return Restrictions.between(cp.getProperty(), cp.getValues()[0], cp.getValues()[1]);  
  37.         }  
  38.         return null;  
  39.     }  
  40.     //封装父类Criteria查询方法   
  41.     public List executeCriteria(Class cl,CriteriaPoJo[] cps){  
  42.         Session session=MySessionFactory.getSession();  
  43.         if(session==null){  
  44.             return null;  
  45.         }  
  46.         Criteria crt=null;  
  47.         try {  
  48.             crt=session.createCriteria(cl);  
  49.             if(cps!=null&&cps.length>0){  
  50.                 for (int i = 0; i < cps.length; i++) {  
  51.                     crt.add(getCriterion(cps[i]));  
  52.                 }  
  53.             }  
  54.             return crt.list();  
  55.         } catch (Exception e) {  
  56.             // TODO: handle exception   
  57.         }finally{  
  58.             session.close();  
  59.         }  
  60.         return null;  
  61.     }  
  62.     //封装父类模糊查询方法   
  63.     public List getInfoLikePro(String cl,String[] col,String[] colvalue){  
  64.         String hql="from "+cl+" where 0=0";  
  65.         for (int i = 0; i < col.length; i++) {  
  66.             hql+=" and "+col[i]+"like ?";  
  67.         }  
  68.         return this.executeQuery(hql, colvalue);  
  69.     }  
  70.     //封装父类根据属性多条件查询方法   
  71.     public List getInfoByPro(String cl,String[] col,String[] colvalue){  
  72.             String hql="from "+cl+" where 0=0";  
  73.             for (int i = 0; i < col.length; i++) {  
  74.                 hql+=" and "+col[i]+"=?";  
  75.             }  
  76.         return this.executeQuery(hql, colvalue);  
  77.     }  
  78.     //封装父类分页查询方法   
  79.     public List getInfoByPageSize(String hql,int rowcount,int pagesize){  
  80.         Session session=MySessionFactory.getSession();  
  81.         if(session==null){  
  82.             return null;  
  83.         }  
  84.         try {  
  85.             Query q=session.createQuery(hql);  
  86.             int size=rowcount*(pagesize-1);  
  87.             q.setFirstResult(size);  
  88.             q.setMaxResults(rowcount);  
  89.               
  90.             return q.list();  
  91.         } catch (Exception e) {  
  92.             e.printStackTrace();  
  93.         }finally{  
  94.             session.close();  
  95.         }  
  96.         return null;  
  97.     }  
  98.     //封装父类查询方法   
  99.     public List executeQuery(String hql,String[] args){  
  100.         Session session=MySessionFactory.getSession();  
  101.         if(session==null){  
  102.             return null;  
  103.         }  
  104.         try {  
  105.             Query q=session.createQuery(hql);  
  106.             if(args!=null&&args.length>0){  
  107.                 for (int i = 0; i < args.length; i++) {  
  108.                     q.setString(i,args[i]);  
  109.                 }  
  110.             }  
  111.             return q.list();  
  112.         } catch (Exception e) {  
  113.             // TODO: handle exception   
  114.         }finally{  
  115.             session.close();  
  116.         }  
  117.         return null;  
  118.     }  
  119.     //封装父类增删改方法   
  120.     public boolean executeUpdate(Object ob,Integer wtd){  
  121.         return this.executeUpdateBatch(new Object[]{ob}, new Integer[]{wtd});  
  122.     }  
  123.     //封装父类批处理事务,增删改方法   
  124.     public boolean executeUpdateBatch(Object[] obs,Integer[] wtd){  
  125.         Session session=MySessionFactory.getSession();  
  126.         if(session==null){  
  127.             return false;  
  128.         }  
  129.         Transaction tran=session.beginTransaction();  
  130.         try {  
  131.             for (int i = 0; i < obs.length; i++) {  
  132.                 switch (wtd[i]) {  
  133.                 case ADD:  
  134.                     session.save(obs[i]);  
  135.                     break;  
  136.                 case DEL:  
  137.                     session.delete(obs[i]);  
  138.                     break;  
  139.                 case UPD:  
  140.                     session.update(obs[i]);  
  141.                     break;  
  142.                 default:  
  143.                     return false;  
  144.                 }  
  145.                 if(i%20==0){  
  146.                     session.flush();  
  147.                     session.clear();  
  148.                 }  
  149.             }  
  150.             tran.commit();  
  151.             return true;  
  152.         } catch (Exception e) {  
  153.             tran.rollback();  
  154.         }finally{  
  155.             session.close();  
  156.         }  
  157.         return false;  
  158.     }  
  159. }  
package com.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import com.sessionmanage.MySessionFactory;
import com.tool.CriteriaPoJo;
public abstract class SysDAO {
	public static final int ADD=1;
	public static final int DEL=2;
	public static final int UPD=3;
	
	public abstract boolean insert(Object ob);
	public abstract boolean delete(Object ob);
	public abstract boolean update(Object ob);
	public abstract List findAll();
	public abstract Object findById(Object ob);
	
	//封装Criterion,供Criteria查询自身调用
	private Criterion getCriterion(CriteriaPoJo cp){
		if(cp.getWtd()==cp.IDEQ){
			return Restrictions.idEq(cp.getValues()[0]);
		}
		if(cp.getWtd()==cp.LIKE){
			return Restrictions.like(cp.getProperty(), "%"+cp.getValues()[0]+"%");
		}
		if(cp.getWtd()==cp.BETWEEN){
			if(cp.getValues().length<2)
				return null;
			return Restrictions.between(cp.getProperty(), cp.getValues()[0], cp.getValues()[1]);
		}
		return null;
	}
	//封装父类Criteria查询方法
	public List executeCriteria(Class cl,CriteriaPoJo[] cps){
		Session session=MySessionFactory.getSession();
		if(session==null){
			return null;
		}
		Criteria crt=null;
		try {
			crt=session.createCriteria(cl);
			if(cps!=null&&cps.length>0){
				for (int i = 0; i < cps.length; i++) {
					crt.add(getCriterion(cps[i]));
				}
			}
			return crt.list();
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			session.close();
		}
		return null;
	}
	//封装父类模糊查询方法
	public List getInfoLikePro(String cl,String[] col,String[] colvalue){
		String hql="from "+cl+" where 0=0";
		for (int i = 0; i < col.length; i++) {
			hql+=" and "+col[i]+"like ?";
		}
		return this.executeQuery(hql, colvalue);
	}
	//封装父类根据属性多条件查询方法
	public List getInfoByPro(String cl,String[] col,String[] colvalue){
			String hql="from "+cl+" where 0=0";
			for (int i = 0; i < col.length; i++) {
				hql+=" and "+col[i]+"=?";
			}
		return this.executeQuery(hql, colvalue);
	}
	//封装父类分页查询方法
	public List getInfoByPageSize(String hql,int rowcount,int pagesize){
		Session session=MySessionFactory.getSession();
		if(session==null){
			return null;
		}
		try {
			Query q=session.createQuery(hql);
			int size=rowcount*(pagesize-1);
			q.setFirstResult(size);
			q.setMaxResults(rowcount);
			
			return q.list();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return null;
	}
	//封装父类查询方法
	public List executeQuery(String hql,String[] args){
		Session session=MySessionFactory.getSession();
		if(session==null){
			return null;
		}
		try {
			Query q=session.createQuery(hql);
			if(args!=null&&args.length>0){
				for (int i = 0; i < args.length; i++) {
					q.setString(i,args[i]);
				}
			}
			return q.list();
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			session.close();
		}
		return null;
	}
	//封装父类增删改方法
	public boolean executeUpdate(Object ob,Integer wtd){
		return this.executeUpdateBatch(new Object[]{ob}, new Integer[]{wtd});
	}
	//封装父类批处理事务,增删改方法
	public boolean executeUpdateBatch(Object[] obs,Integer[] wtd){
		Session session=MySessionFactory.getSession();
		if(session==null){
			return false;
		}
		Transaction tran=session.beginTransaction();
		try {
			for (int i = 0; i < obs.length; i++) {
				switch (wtd[i]) {
				case ADD:
					session.save(obs[i]);
					break;
				case DEL:
					session.delete(obs[i]);
					break;
				case UPD:
					session.update(obs[i]);
					break;
				default:
					return false;
				}
				if(i%20==0){
					session.flush();
					session.clear();
				}
			}
			tran.commit();
			return true;
		} catch (Exception e) {
			tran.rollback();
		}finally{
			session.close();
		}
		return false;
	}
}

其他各类的DAO类继承SysDAO类进行使用,这里我就只给出TeacherDAO.java的代码

TeacherDAO.java

  1. package com.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. public class TeacherDAO extends SysDAO {  
  6.   
  7.     @Override  
  8.     public boolean delete(Object ob) {  
  9.         return executeUpdate(ob, SysDAO.DEL);  
  10.     }  
  11.   
  12.     @Override  
  13.     public boolean insert(Object ob) {  
  14.         return executeUpdate(ob, SysDAO.ADD);  
  15.     }  
  16.   
  17.     @Override  
  18.     public boolean update(Object ob) {  
  19.         return executeUpdate(ob, SysDAO.UPD);  
  20.     }  
  21.     //定义批量删除操作的方法   
  22.     public boolean deleteInfos(Object[] obs){  
  23.         Integer[] wtd=new Integer[obs.length];  
  24.         for (int i = 0; i < wtd.length; i++) {  
  25.             wtd[i]=SysDAO.DEL;  
  26.         }  
  27.         return executeUpdateBatch(obs, wtd);  
  28.     }  
  29.   
  30.     @Override  
  31.     public List findAll() {  
  32.         return this.executeQuery("from Teacher"null);  
  33.     }  
  34.   
  35.     @Override  
  36.     public Object findById(Object ob) {  
  37.         return this.executeQuery("from Teacher where tid=?",new String[]{ob+""} );  
  38.     }  
  39. }  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值