使用数据访问对象(DAO)使我们可以将底层数据访问逻辑与业务逻辑分离开。我们构建了为每一个数据源提供 GRUD (创建、读取、更新、删除)操作的 DAO 类。
下面是一个数据源GRUD(创建)操作的DAO实例.
1.接口(DemoDAO.java)
package com.company.demo.dao; import net.sf.hibernate.HibernateException; import com.company.demo.jdo.Demo; import com.company.demo.datamodule.*; /** * <p>Title: Struts+Hibernate开发模板</p> * <p>Description: 通用开发模板</p> * <p>Copyright: Copyright (c) 2003</p> * <p>Company: 优势科技</p> * @author 段洪杰 * @version 1.0 */ public interface DemoDAO { /**设置数据模型**/ public void setDataModule(DataModule dataModule); /** 建立对象 **/ public void createDemo(Demo demo) throws HibernateException,Exception; }
2.抽象工厂(DemoDAOFactory.java)
package com.company.demo.dao; /** * <p>Title: Struts+Hibernate开发模板</p> * <p>Description: 通用开发模板</p> * <p>Copyright: Copyright (c) 2003</p> * <p>Company: 优势科技</p> * @author 段洪杰 * @version 1.0 */ public class DemoDAOFactory { private DemoDAOFactory() { } public final static DemoDAO getDemoDAO(){ return new DemoDAOImpl(); } }
3.DAO类(DemoDAOImpl.java)
package com.company.demo.dao; import java.util.List; import com.company.demo.datamodule.*; import com.company.demo.jdo.Demo; import net.sf.hibernate.SessionFactory; import net.sf.hibernate.HibernateException; import net.sf.hibernate.Session; import net.sf.hibernate.Transaction; import net.sf.hibernate.Query; /** * <p>Title: Struts+Hibernate开发模板</p> * <p>Description: 通用开发模板</p> * <p>Copyright: Copyright (c) 2003</p> * <p>Company: 优势科技</p> * @author 段洪杰 * @version 1.0 */ public class DemoDAOImpl implements DemoDAO { private SessionFactory sessionFactory; private DataModule dataModule; /** * 设数据模型 * @param dataModule */ public void setDataModule(DataModule dataModule){ this.dataModule=dataModule; this.sessionFactory=dataModule.getSessionFactory(); } /** * 建立DEMO * @param demo * @throws HibernateException * @throws java.lang.Exception */ public void createDemo(Demo demo) throws HibernateException,Exception { Transaction transaction = null; Session session=sessionFactory.openSession(); try{ transaction = session.beginTransaction(); session.save(demo); transaction.commit(); }catch(HibernateException he){ if ( transaction!=null ){ transaction.rollback(); } throw he; }finally{ session.close(); } } }