spring和hiberate泛型

/**

 * 

 */

package com.thams.util.dao.hibernate;

 

import java.io.Serializable;

import java.lang.reflect.ParameterizedType;

import java.util.Collection;

import java.util.List;

 

import org.hibernate.HibernateException;

import org.hibernate.Query;

import org.hibernate.Session;

import org.springframework.orm.hibernate3.HibernateCallback;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

 

import com.thams.util.dao.GenericDao;

 

/**

 * @author 刘玉华

 * @EMail: [email protected]

 * @version

 */

public class HibernateBaseDaoImpl<T, ID extends Serializable> extends

       HibernateDaoSupport implements GenericDao<T, ID> {

    private Class<T> persistentClass = null;

 

    /*

     * Cmd parameter is the named query's name. Please refer to Hibernate Named

     * Query.

     * 

     * @see com.zybedu.dao.FindCmdDao#findCmd(java.lang.String,

     *      java.lang.Object[], int, int)

     */

    @SuppressWarnings("unchecked")

    public Collection findCmd(final String cmd, final Object[] params,

           final int page, final int count) {

       List result = null;

       Object o = this.getHibernateTemplate().execute(new HibernateCallback() {

           public Object doInHibernate(Session session)

                  throws HibernateException {

              Query query = session.getNamedQuery(cmd);

              if (params != null) {

                  int len = params.length;

                  for (int i = 0; i < len; i++) {

                     query.setParameter(i, params[i]);

                  }

              }

              if (page > 0) {

                  int maxResult = count;

                  if (count < 1)

                     maxResult = 1;

                  int first = (page - 1) * maxResult;

                  query.setFirstResult(first);

                  query.setMaxResults(maxResult + 1);

              } else {

 

              }

              List list = query.list();

              org.hibernate.Hibernate.initialize(list);

              return list;

           }

       });

       if (o != null)

           result = (List) o;

       return result;

    }

 

    public void delete(T entity) {

       this.getHibernateTemplate().delete(entity);

       this.getSession().flush();

    }

 

    @SuppressWarnings("unchecked")

    public List<T> findAll() {

       List list = this.getHibernateTemplate().loadAll(

              this.getPersistentClass());

       org.hibernate.Hibernate.initialize(list);

       return list;

    }

 

    @SuppressWarnings("unchecked")

    public T loadObjectById(ID id) {

       return (T) this.getHibernateTemplate().get(this.getPersistentClass(),

              id);

    }

 

    public T saveOrUpdate(T entity) {

       this.getHibernateTemplate().saveOrUpdate(entity);

       return entity;

    }

 

    protected Class<T> getPersistentClass() {

       if (this.persistentClass == null) {

           this.persistentClass = (Class<T>) ((ParameterizedType) getClass()

                  .getGenericSuperclass()).getActualTypeArguments()[0];

       }

       return this.persistentClass;

    }

 

    public Collection<Object> findCmdByDyn(String querySql, final int page,

           final int count) {

       List result = null;

       final String fullHql = querySql;

       // LazyParser parser=parsers.get(cmd);

       if (fullHql != null) {

           Object o = this.getHibernateTemplate().execute(

                  new HibernateCallback() {

                     public Object doInHibernate(Session session)

                            throws HibernateException {

 

                         Query query = session.createQuery(fullHql);

 

                         if (page > 0) {

                            int maxResult = count;

                            if (count < 1)

                                maxResult = 1;

                            int first = (page - 1) * maxResult;

                            query.setFirstResult(first);

                            query.setMaxResults(maxResult + 1);

                         }

 

                         List list = query.list();

                         return list;

                     }

                  });

           if (o != null)

              result = (List) o;

       }

       return result;

    }

 

    public Object queryByCmd(final String cmd, final Object[] params) {

       // 

       Object avg = null;

       Object avgTemp = this.getHibernateTemplate().execute(

              new HibernateCallback() {

                  public Object doInHibernate(Session session)

                         throws HibernateException {

                     Query query = session.getNamedQuery(cmd);

 

                     if (params != null) {

                         int len = params.length;

                         for (int i = 0; i < len; i++) {

                            query.setParameter(i, params[i]);

                         }

                     }

                     return query.uniqueResult();

                  }

              });

       if (avgTemp != null)

           avg = avgTemp;

       return avg;

    }

 

}

 

  spring

hiberate 可以说是当下炙手可热的框架结合了。但是会用还不行,最主要的如何结合使用,再次我把自己对这些的认识用代码实现起来,给各位参考一下 ( 把这两个应用发挥到极致 )

首先:我简单介绍下本人这里实现的是springhibernate 有关泛型的实现:

介绍下泛型的定义: 泛型是JDK1.5的一个新的特性,使用泛型机制编写的程序代码要比那些杂乱的使用Object变量,然后再进行强制类型转换的代码具有更好的安全性和可读性。如果你的系统运行在JDK1.5以上的版本上,建议多使用泛型来代替无休止的对象转换

 

现在以本人系统构架做下介绍,应该对一些做程序员,天天写程序,结果程序都实现了。结果对公司底层的认识还不够,现做下补充

首先大家了解下底层构架:(再次本人把ant等相关就不介绍了。大家可以自行修改对应配置信息)

spring_base.xml -- spring基础配置
spring_other.xml -- spring
实例配置

BaseService.java ---- 工厂的基础类.
ServiceFactory.java ----
服务工厂,所有的服务都从该工厂中获得。

GenericDao.java -- 该类为hibernaeDao的基础类,所以其它模块的类的dao都集成该接口

HibernateBaseDaoImpl -- hibernate基本实现Dao,(通用) 大家可以自己实现该类部署自己的工程

UserlistDao.java -- 泛型Dao接口
UserlistDaoImpl.java --
泛型Dao实现(基本无业务方法,都封装到基本实现Dao--GenericDao 中)

BasicService.java -- 模块service接口
BasicServiceImpl.java --
模块service实现(所有业务操作都从该类中实例出来)

BasicTest.java -- 测试类

 

 下面谈下实现(代码):

 

spring_base.xml -- spring基础配置

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans><!-- 关于数据源的bean -->

    <bean id="dataSource"

       class="org.apache.commons.dbcp.BasicDataSource"

       destroy-method="close">

       <property name="driverClassName" value="@db.driver@" />

       <property name="url" value="@db.url@" />

       <property name="username" value="@db.user@" />

       <property name="password" value="@db.password@" />

    </bean>

    <bean id="sessionFactory"

        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><!-- 服务工厂-->

       <property name="dataSource" ref="dataSource" />

       <property name="mappingResources">

           <list>

              <value>com/thams/basic/mappings/Userlist.hbm.xml</value>

              <!-- hibernate 映射文件 -->

           </list>

       </property>

       <property name="hibernateProperties"><!-- hibernate相关设置属性 -->

           <props>

              <prop key="hibernate.dialect">@db.dialect@</prop>

              <prop key="hibernate.c3p0.min_size">5</prop>

              <prop key="hibernate.c3p0.max_size">20</prop>

              <prop key="hibernate.c3p0.timeout">1800</prop>

              <prop key="hibernate.c3p0.max_statements">50</prop>

              <prop key="hibernate.jdbc.batch_size">20</prop>

              <prop key="show_sql">true</prop>

              <prop key="hibernate.connection.isolation">2</prop>

              <prop key="hibernate.jdbc.use_streams_for_binary">

                  true

              </prop>

              <prop key="hibernate.order_updates">true</prop>

              <prop key="hibernate.connection.release_mode">

                  after_transaction

              </prop>

           </props>

       </property>

    </bean><!-- tx -->

    <bean id="txManager"

        class="org.springframework.orm.hibernate3.HibernateTransactionManager">

       <property name="sessionFactory" ref="sessionFactory" />

    </bean>

</beans>

 

 

BaseService.java ---- 工厂的基础类.

package com.thams;
 
import org.springframework.transaction.support.TransactionTemplate;
 
/**
 * * 工厂的基础类. *
 * 
 * @author 刘玉华 *
 * @time 2007-12-14
 */
public class BaseService extends TransactionTemplate {
            private static final long serialVersionUID = 1L;
}

 

ServiceFactory.java ----服务工厂,所有的服务都从该工厂中获得。

 

package com.thams;

 

import org.springframework.beans.factory.BeanFactory;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.thams.basic.BasicService;

import com.thams.dynamic.dao.CommonDao;

import com.thams.email.EmailService;

import com.thams.ftp.FtpClientService;

import com.thams.search.dao.SearchDao;

import com.thams.util.dao.LazyParser;

 

/**

 * * 服务工厂,所有的服务都从该工厂中获得。 *

 * 

 * @author 刘玉华 *

 * @time 2007-12-14

 */

public class ServiceFactory {

    private static BeanFactory factory = null;

    static {

       ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(

              new String[] { "spring_base.xml", "spring_other.xml" });

       factory = (BeanFactory) context;

    }

 

    public static LazyParser getBaseHbnLazyParser() {

       return (LazyParser) factory.getBean("baseLazyParser");

    }

 

    /**

     * * 获得ftp上传服务 *

     * 

     * @return ftp服务

     */

    public static FtpClientService getFtpClientService() {

       return (FtpClientService) factory.getBean("ftpClientService");

    }

 

    /**

     * * 邮件发送服务 *

     * 

     * @return 邮件发送服务

     */

    public static EmailService getEmailService() {

       return (EmailService) factory.getBean("emailService");

    }

 

    /**

     * * 获得基本数据表操作服务 *

     * 

     * @return 系统数据表操作服务

     */

    public static BasicService getBasicService() {

       return (BasicService) factory.getBean("basicService");

    }

 

    /**

     * * 获取档案信息操作类服务 *

     * 

     * @return 档案操作类服务

     */

    public static CommonDao getCommonDao() {

       return (CommonDao) factory.getBean("commonDao");

    }

 

    /**

     * * 获取项目、案卷、文件操作类服务 *

     * 

     * @return 查询类服务

     */

    public static SearchDao getSearchDao() {

       return (SearchDao) factory.getBean("searchDao");

    }

}

 

 

该接口为泛型Dao的模型

 

 

HibernateBaseDaoImpl -- hibernate基本实现Dao,(通用) 大家可以自己实现该类部署自己的工程

 

/**

 * 

 */

package com.thams.util.dao.hibernate;

 

import java.io.Serializable;

import java.lang.reflect.ParameterizedType;

import java.util.Collection;

import java.util.List;

 

import org.hibernate.HibernateException;

import org.hibernate.Query;

import org.hibernate.Session;

import org.springframework.orm.hibernate3.HibernateCallback;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

 

import com.thams.util.dao.GenericDao;

 

/**

 * @author 刘玉华

 * @EMail: [email protected]

 * @version

 */

public class HibernateBaseDaoImpl<T, ID extends Serializable> extends

       HibernateDaoSupport implements GenericDao<T, ID> {

    private Class<T> persistentClass = null;

 

    /*

     * Cmd parameter is the named query's name. Please refer to Hibernate Named

     * Query.

     * 

     * @see com.zybedu.dao.FindCmdDao#findCmd(java.lang.String,

     *      java.lang.Object[], int, int)

     */

    @SuppressWarnings("unchecked")

    public Collection findCmd(final String cmd, final Object[] params,

           final int page, final int count) {

       List result = null;

       Object o = this.getHibernateTemplate().execute(new HibernateCallback() {

           public Object doInHibernate(Session session)

                  throws HibernateException {

              Query query = session.getNamedQuery(cmd);

              if (params != null) {

                  int len = params.length;

                  for (int i = 0; i < len; i++) {

                     query.setParameter(i, params[i]);

                  }

              }

              if (page > 0) {

                  int maxResult = count;

                  if (count < 1)

                     maxResult = 1;

                  int first = (page - 1) * maxResult;

                  query.setFirstResult(first);

                  query.setMaxResults(maxResult + 1);

              } else {

 

              }

              List list = query.list();

              org.hibernate.Hibernate.initialize(list);

              return list;

           }

       });

       if (o != null)

           result = (List) o;

       return result;

    }

 

    public void delete(T entity) {

       this.getHibernateTemplate().delete(entity);

       this.getSession().flush();

    }

 

    @SuppressWarnings("unchecked")

    public List<T> findAll() {

       List list = this.getHibernateTemplate().loadAll(

              this.getPersistentClass());

       org.hibernate.Hibernate.initialize(list);

       return list;

    }

 

    @SuppressWarnings("unchecked")

    public T loadObjectById(ID id) {

       return (T) this.getHibernateTemplate().get(this.getPersistentClass(),

              id);

    }

 

    public T saveOrUpdate(T entity) {

       this.getHibernateTemplate().saveOrUpdate(entity);

       return entity;

    }

 

    protected Class<T> getPersistentClass() {

       if (this.persistentClass == null) {

           this.persistentClass = (Class<T>) ((ParameterizedType) getClass()

                  .getGenericSuperclass()).getActualTypeArguments()[0];

       }

       return this.persistentClass;

    }

 

    public Collection<Object> findCmdByDyn(String querySql, final int page,

           final int count) {

       List result = null;

       final String fullHql = querySql;

       // LazyParser parser=parsers.get(cmd);

       if (fullHql != null) {

           Object o = this.getHibernateTemplate().execute(

                  new HibernateCallback() {

                     public Object doInHibernate(Session session)

                            throws HibernateException {

 

                         Query query = session.createQuery(fullHql);

 

                         if (page > 0) {

                            int maxResult = count;

                            if (count < 1)

                                maxResult = 1;

                            int first = (page - 1) * maxResult;

                            query.setFirstResult(first);

                            query.setMaxResults(maxResult + 1);

                         }

 

                         List list = query.list();

                         return list;

                     }

                  });

           if (o != null)

              result = (List) o;

       }

       return result;

    }

 

    public Object queryByCmd(final String cmd, final Object[] params) {

       // 

       Object avg = null;

       Object avgTemp = this.getHibernateTemplate().execute(

              new HibernateCallback() {

                  public Object doInHibernate(Session session)

                         throws HibernateException {

                     Query query = session.getNamedQuery(cmd);

 

                     if (params != null) {

                         int len = params.length;

                         for (int i = 0; i < len; i++) {

                            query.setParameter(i, params[i]);

                         }

                     }

                     return query.uniqueResult();

                  }

              });

       if (avgTemp != null)

           avg = avgTemp;

       return avg;

    }

 

}

 

 

注:该hibernate泛型Dao实现类 主要实现功能有 增删查改 分页模型,

基本的系统数据库操作已经涵盖,大家这点要研究下

 

 

UserlistDao.java -- 泛型Dao接口

 

package com.thams.basic.dao;

 

import com.thams.basic.mappings.Userlist;

import com.thams.util.dao.GenericDao;

 

public interface UserlistDao extends GenericDao<Userlist, String> {

}

 

 

注意描红字段,通过该实现 自动实现了interface GenericDao<T,ID extends Serializable> 中的方法映射,直接返回当前类型的GenericDao中各个操作

 

UserlistDaoImpl.java -- 泛型Dao实现(基本无业务方法,都封装到基本实现Dao--GenericDao 中)

 

package com.thams.basic.dao;

 

import com.thams.basic.mappings.Userlist;

import com.thams.util.dao.hibernate.HibernateBaseDaoImpl;

 

public class UserlistDaoImpl extends HibernateBaseDaoImpl<Userlist, String>

       implements UserlistDao {

}

 

 

Dao实现可不定义方法,(基本的操作方法)GenericDao 中已经实现

 

例如别的Dao实现如下:

DatabaselibDao.java - public interface DatabaselibDao extends GenericDao<Databaselib, Long>
DatabaselibDaoImpl.java - public class DatabaselibDaoImpl extends HibernateBaseDaoImpl<Databaselib,Long> implements DatabaselibDao
PathconfigDao.java - public interface PathconfigDao extends GenericDao<Pathconfig, PathconfigId>
PathconfigDaoImpl.java - public class PathconfigDaoImpl extends HibernateBaseDaoImpl<Pathconfig, PathconfigId> implements PathconfigDao

 

 

BasicService.java -- 模块service接口

 

package com.thams.basic;

 

import java.util.Collection;

import com.thams.basic.mappings.Databaselib;

import com.thams.basic.mappings.Pathconfig;

import com.thams.basic.mappings.PathconfigId;

import com.thams.basic.mappings.Userlist;

 

public interface BasicService {

    /**

     * * 根据用户code获取用户对象 *

     * 

     * @param code

     *            档案类型code *

     * @return 当前code的档案类型实体

     */

    public Userlist getUserlistByCode(final String code);

 

    /**

     * * 根据档案类型code的获取该档案类型实体 *

     * 

     * @param code

     *            档案类型code *

     * @return 当前code的档案类型实体

     */

    public Databaselib getDatabaselibByCmd(final Long code);

 

    /**

     * * 列出所有档案类型实体Collection 列表 *

     * 

     * @return 全部档案实体的Collection 列表

     */

    public Collection<Databaselib> listDatabaselibAll();

 

    /**

     * * 根据pathname获取系统配置表pathconfig实体 *

     * 

     * @param pathconfigId *

     * @return pathconfig实体

     */

    public Pathconfig getPathconfigByCmd(final PathconfigId id);

 

    /**

     * * 列出详细配置信息 *

     * 

     * @return

     */

    public Collection listPathconfigAll();

 

    /**

     * * 添加或者修改配置信息 *

     * 

     * @param pathconfig *

     * @return Pathconfig 对象

     */

    public Pathconfig saveOrUpdatePathconfig(final Pathconfig pathconfig);

}

 

 

描红字段不做说明,只做参考 

 

 

 

service

 

 

BasicServiceImpl.java -- 模块service实现(所有业务操作都从该类中实例出来)

 

package com.thams.basic;

 

import java.util.Collection;

 

import org.springframework.transaction.TransactionStatus;

import org.springframework.transaction.support.TransactionCallback;

 

import com.thams.BaseService;

import com.thams.basic.dao.DatabaselibDao;

import com.thams.basic.dao.PathconfigDao;

import com.thams.basic.dao.UserlistDao;

import com.thams.basic.mappings.Databaselib;

import com.thams.basic.mappings.Pathconfig;

import com.thams.basic.mappings.PathconfigId;

import com.thams.basic.mappings.Userlist;

 

public class BasicServiceImpl extends BaseService implements BasicService {

    private static final long serialVersionUID = 1L;

    DatabaselibDao databaselibDao;

    PathconfigDao pathconfigDao;

    UserlistDao userlistDao;

 

    public UserlistDao getUserlistDao() {

       return userlistDao;

    }

 

    public void setUserlistDao(UserlistDao userlistDao) {

       this.userlistDao = userlistDao;

    }

 

    public PathconfigDao getPathconfigDao() {

       return pathconfigDao;

    }

 

    public void setPathconfigDao(PathconfigDao pathconfigDao) {

       this.pathconfigDao = pathconfigDao;

    }

 

    public DatabaselibDao getDatabaselibDao() {

       return databaselibDao;

    }

 

    public void setDatabaselibDao(DatabaselibDao databaselibDao) {

       this.databaselibDao = databaselibDao;

    }

 

    public Databaselib getDatabaselibByCmd(final Long code) {

       Object o = execute(new TransactionCallback() {

           public Object doInTransaction(TransactionStatus status) {

              return databaselibDao.loadObjectById(code);

           }

       });

       return (Databaselib) o;

    }

 

    public Collection<Databaselib> listDatabaselibAll() {

       Object o = execute(new TransactionCallback() {

           public Object doInTransaction(TransactionStatus status) {

              return databaselibDao.findAll();

           }

       });

       return (Collection) o;

    }

 

    public Pathconfig getPathconfigByCmd(final PathconfigId id) {

       Object o = execute(new TransactionCallback() {

           public Object doInTransaction(TransactionStatus status) {

              return pathconfigDao.loadObjectById(id);

           }

       });

       return (Pathconfig) o;

    }

 

    public Pathconfig saveOrUpdatePathconfig(final Pathconfig pathconfig) {

       Object o = execute(new TransactionCallback() {

           public Object doInTransaction(TransactionStatus status) {

              return pathconfigDao.saveOrUpdate(pathconfig);

           }

       });

       return (Pathconfig) o;

    }

 

    public Collection listPathconfigAll() {

       Object o = execute(new TransactionCallback() {

           public Object doInTransaction(TransactionStatus status) {

              return pathconfigDao.findAll();

           }

       });

       return (Collection) o;

    }

 

    public Userlist getUserlistByCode(final String code) {

       Object o = execute(new TransactionCallback() {

           public Object doInTransaction(TransactionStatus status) {

              return userlistDao.loadObjectById(code);

           }

       });

       return (Userlist) o;

    }

}

 

 

 描红字段不做说明,只做参考 ,大家发现没有定义的 userlistDao 根本没有写业务直接可以使用

 

测试:

 

package com.thams.junit;

 

import java.util.List;

 

import junit.framework.TestCase;

 

import com.thams.ServiceFactory;

import com.thams.basic.BasicService;

import com.thams.basic.mappings.Databaselib;

import com.thams.basic.mappings.Pathconfig;

import com.thams.basic.mappings.PathconfigId;

public class BasicTest extends TestCase {

       public static String test1(Long id){

              BasicService service = ServiceFactory.getBasicService();

              Databaselib db = new Databaselib();

              db = service.getDatabaselibByCmd(id);

              System.out.println(db==null?"db为空":"db不为空");

              System.out.println(db.getChname());

              return db.getChname()==null||db.getChname().equals("")?"对象为空":db.getChname();

       }

       public static void test2(){

              BasicService service = ServiceFactory.getBasicService();

              List<Databaselib> ls = (List<Databaselib>) service.listDatabaselibAll();

              System.out.println(ls.size());

       }

       public static void test3(){

              BasicService service = ServiceFactory.getBasicService();

              Pathconfig pathconfig = new Pathconfig();

              PathconfigId id = new PathconfigId();

              id.setPathname("a");

              id.setPathvalue("b");

              pathconfig = service.getPathconfigByCmd(id);

              System.out.println(pathconfig==null);

              System.out.println(pathconfig.getId().getPathvalue());

       }

       public static void test4(){

              BasicService service = ServiceFactory.getBasicService();

              Pathconfig pathconfig = new Pathconfig();

              PathconfigId id = new PathconfigId();

              id.setPathname("22");

              id.setPathvalue("33333333");

              pathconfig.setId(id);

              service.saveOrUpdatePathconfig(pathconfig);

       }

       public static void test5(){

              BasicService service = ServiceFactory.getBasicService();

              List ls = (List) service.listPathconfigAll();

              System.out.println(ls.size());

              for (int i = 0; i < ls.size(); i++) {

                     Pathconfig pg = new Pathconfig();

                     pg = (Pathconfig) ls.get(i);

                     System.out.println(pg.getId().getPathname());

              }

       }

       public static Databaselib listDatabaselibBycode(Long id){

              BasicService service = ServiceFactory.getBasicService();

              Databaselib databaselib =  service.getDatabaselibByCmd(id);

              System.out.println(databaselib.getChname());

              return databaselib;

       }

}

 

 

spring_other.xml -- spring实例配置

 

该文件可与上文件合二为一 为了区分业务 建议分开

 

 

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans><!--=========================== 系统表操作模块 ================================ -->

    <bean id="basicService" class="com.thams.basic.BasicServiceImpl">

       <property name="databaselibDao" ref="databaselibDao" />

       <property name="pathconfigDao" ref="pathconfigDao" />

       此处可删除本文章把该实现略去

       <property name="userlistDao" ref="userlistDao" />

       <property name="transactionManager" ref="txManager" />

    </bean><!-- 用户Dao -->

    <bean id="userlistDao"

       class="com.thams.basic.dao.UserlistDaoImpl">

       <property name="sessionFactory" ref="sessionFactory" />

    </bean>

</beans>

 

你可能感兴趣的:(DAO,spring,Hibernate,bean,orm)