使用Spring减少代码量 SpringDAOHibernate配置管理Apache
程序员文章站
2022-06-17 09:07:37
...
http://www.skyinn.org/wiki/Wiki.jsp?page=Java_blogentry_270704_1
在使用Spring之前,DAO的配置、初始化、获取、释放等都需要自己写,
将近11个类或接口,量比较大,关系复杂,尚未包括配置文件处理、ThreadLocal、Filter等等
原来的DAOFactory,这还将DAO的配置信息由别的模块处理了的
001 /* =============================================
002 * $Id: DAOFactory.java,v 1.4 2003/10/20 14:18:44 l_walker Exp $
003 * Created on [2003-10-8 22:48:12] by l_walker
004 * =============================================
005 * The Skyinn Software License v1.0
006 * ===============================================
007 */
008 package org.skyinn.quasar.dao;
009
010 import org.apache.commons.collections.FastHashMap;
011 import org.apache.commons.logging.Log;
012 import org.apache.commons.logging.LogFactory;
013 import org.skyinn.quasar.config.ApplicationConfiguration;
014 import org.skyinn.quasar.util.StringUtil;
015
016
017 /**
018 * <p>DAO工厂类。</p>
019 *
020 * @author $Author: l_walker $
021 * @version $Revision: 1.4 $ $Date: 2003/10/20 14:18:44 $
022 */
023 public class DAOFactory {
024 //~ Static fields/initializers =============================================
025
026 /**DAOFactory singleton instance.*/
027 private static DAOFactory instance = new DAOFactory();
028
029 //~ Instance fields ========================================================
030
031 /** Logging */
032 private Log log = LogFactory.getLog (this.getClass ());
033
034 /**DAO pool.*/
035 protected FastHashMap daos = new FastHashMap();
036
037 /**DAO configuration.*/
038 protected DAOConfig daoConfig = null;
039
040 //~ Constructors ===========================================================
041
042 /**
043 * Default Construtor.
044 */
045 private DAOFactory () {
046 super();
047 daoConfig = ApplicationConfiguration.getInstance().getDAOConfiguration();
048 }
049
050 //~ Methods ================================================================
051
052 /**
053 * 取DAO工厂,Singleton模式以确保系统中只有一个DAOFactory实例。
054 *
055 * @return DAO工厂实例
056 */
057 public static synchronized DAOFactory getInstance () {
058 if (null == instance) {
059 instance = new DAOFactory();
060 }
061 return instance;
062 }
063
064 /**
065 * 从DAO池中取对应KEY的DAO实例。
066 * 若该实例未存在,则从DAO配置中取该DAO的Mapping,并从中取该DAO的实现类的类名,
067 * 初始化之并将其置入池中缓存。
068 *
069 * @param key
070 * @return
071 * @throws DAOException
072 */
073 public synchronized DAO findDAOByKey (final String key)
074 throws DAOException {
075 //TODO:DAO实例是在初始化时全部创建一边还是在每次被调用时才创建???
076 //get dao instance from dao pool
077 DAO daoInstance = (DAO) daos.get (key);
078
079 //get dao mapping
080 final DAOMapping daoMapping = daoConfig.findDAOMapping (key);
081
082 //if null or different type bewteen the current dao and it's mapping
083 if ((null == daoInstance) ||
084 !daoInstance.validateType (daoMapping.getCurrentType ())) {
085 try {
086 final String daoImplClass =
087 daoMapping.findDAOImplClass (daoMapping.getCurrentType ());
088
089 if (StringUtil.isNullOrEmpty (daoImplClass)) {
090 throw new DAOException("Not found DAO implement class of:[" +
091 daoMapping + "]");
092 }
093
094 //new instance
095 Class clazz = Class.forName (daoImplClass);
096 daoInstance = (DAO) clazz.newInstance ();
097
098 //set current type
099 daoInstance.setCurrentType (daoMapping.getCurrentType ());
100
101 //add to dao pool
102 daos.setFast (false);
103 daos.put (key, daoInstance);
104 daos.setFast (true);
105
106 if (log.isDebugEnabled ()) {
107 log.debug ("A DAO instance created:[" + key + "]");
108 }
109 } catch (ClassNotFoundException e) {
110 log.error ("ClassNotFoundException:" + e.getMessage());
111 throw new DAOException(e);
112 } catch (InstantiationException e) {
113 log.error ("InstantiationException:" + e.getMessage());
114 throw new DAOException(e);
115 } catch (IllegalAccessException e) {
116 log.error ("IllegalAccessException:" + e.getMessage());
117 throw new DAOException(e);
118 }
119 }
120 return daoInstance;
121 }
122 }
相应的配置文件:
01 <!-- Services -->
02 <services>
03 <service name="ACLService" className="org.skyinn.quasar.acl.ACLService"/>
04 </services>
05
06 <!--DAO Mappings-->
07 <dao-mappings>
08 <dao key="org.skyinn.quasar.acl.dao.UserDAO1" currentType="hibernate">
09 <dao-impl type="hibernate" implClass="org.skyinn.quasar.acl.dao.hibernate.UserDAOHibImpl"/>
10 </dao>
11 </dao-mappings>
--------------------------------------------------------------------------------
而现在在使用了spring之后,只定义了三个类或接口:
DAO DAO接口
DAOException 异常
HibernateDAO Hibernate dao 基类,
而且相应的代码不到100行:
01 /* =====================================================================
02 * $Id: HibernateDAO.java,v 1.1 2004/07/26 14:38:22 l_walker Exp $
03 *
04 * Created: [2004-7-25 0:03:47] by l_walker
05 * =====================================================================*/
06 package org.skyinn.quasar.dao;
07
08 import java.util.List;
09
10 import org.skyinn.quasar.common.PersistentObject;
11 import org.springframework.orm.hibernate.support.HibernateDaoSupport;
12
13 /**
14 * <p>HibernateDAO.java</p>
15 *
16 * <p>
17 * <a href="HibernateDAO.java.java.html"><i>View Source</i></a>
18 * </p>
19 *
20 * @author $Author: l_walker $
21 * @version $Reversion$ $Date: 2004/07/26 14:38:22 $
22 */
23 public class HibernateDAO extends HibernateDaoSupport implements DAO {
24 private static final String KEY = "HibernateDAO";
25
26 public PersistentObject createObject(PersistentObject obj) {
27 return (PersistentObject) this.getHibernateTemplate().save(obj);
28 }
29
30 public void updateObject(PersistentObject obj) {
31 this.getHibernateTemplate().update(obj);
32 }
33
34 public void deleteObject(PersistentObject obj) {
35 this.getHibernateTemplate().delete(obj);
36 }
37 public void deleteObjectById(Class clazz, long id) {
38 PersistentObject obj =
39 (PersistentObject) this.getHibernateTemplate().load(
40 clazz,
41 new Long(id));
42 if (null != obj) {
43 this.getHibernateTemplate().delete(obj);
44 }
45 }
46
47 public PersistentObject retriveObjectById(Class clazz, long id) {
48 return (PersistentObject) this.getHibernateTemplate().load(
49 clazz,
50 new Long(id));
51 }
52
53 public List listAll(Class clazz){
54 return this.getHibernateTemplate().loadAll(clazz);
55 }
56
57
58 }
session管理、事务等等都交由spring去处理,确实省事不少。
在使用Spring之前,DAO的配置、初始化、获取、释放等都需要自己写,
将近11个类或接口,量比较大,关系复杂,尚未包括配置文件处理、ThreadLocal、Filter等等
原来的DAOFactory,这还将DAO的配置信息由别的模块处理了的
001 /* =============================================
002 * $Id: DAOFactory.java,v 1.4 2003/10/20 14:18:44 l_walker Exp $
003 * Created on [2003-10-8 22:48:12] by l_walker
004 * =============================================
005 * The Skyinn Software License v1.0
006 * ===============================================
007 */
008 package org.skyinn.quasar.dao;
009
010 import org.apache.commons.collections.FastHashMap;
011 import org.apache.commons.logging.Log;
012 import org.apache.commons.logging.LogFactory;
013 import org.skyinn.quasar.config.ApplicationConfiguration;
014 import org.skyinn.quasar.util.StringUtil;
015
016
017 /**
018 * <p>DAO工厂类。</p>
019 *
020 * @author $Author: l_walker $
021 * @version $Revision: 1.4 $ $Date: 2003/10/20 14:18:44 $
022 */
023 public class DAOFactory {
024 //~ Static fields/initializers =============================================
025
026 /**DAOFactory singleton instance.*/
027 private static DAOFactory instance = new DAOFactory();
028
029 //~ Instance fields ========================================================
030
031 /** Logging */
032 private Log log = LogFactory.getLog (this.getClass ());
033
034 /**DAO pool.*/
035 protected FastHashMap daos = new FastHashMap();
036
037 /**DAO configuration.*/
038 protected DAOConfig daoConfig = null;
039
040 //~ Constructors ===========================================================
041
042 /**
043 * Default Construtor.
044 */
045 private DAOFactory () {
046 super();
047 daoConfig = ApplicationConfiguration.getInstance().getDAOConfiguration();
048 }
049
050 //~ Methods ================================================================
051
052 /**
053 * 取DAO工厂,Singleton模式以确保系统中只有一个DAOFactory实例。
054 *
055 * @return DAO工厂实例
056 */
057 public static synchronized DAOFactory getInstance () {
058 if (null == instance) {
059 instance = new DAOFactory();
060 }
061 return instance;
062 }
063
064 /**
065 * 从DAO池中取对应KEY的DAO实例。
066 * 若该实例未存在,则从DAO配置中取该DAO的Mapping,并从中取该DAO的实现类的类名,
067 * 初始化之并将其置入池中缓存。
068 *
069 * @param key
070 * @return
071 * @throws DAOException
072 */
073 public synchronized DAO findDAOByKey (final String key)
074 throws DAOException {
075 //TODO:DAO实例是在初始化时全部创建一边还是在每次被调用时才创建???
076 //get dao instance from dao pool
077 DAO daoInstance = (DAO) daos.get (key);
078
079 //get dao mapping
080 final DAOMapping daoMapping = daoConfig.findDAOMapping (key);
081
082 //if null or different type bewteen the current dao and it's mapping
083 if ((null == daoInstance) ||
084 !daoInstance.validateType (daoMapping.getCurrentType ())) {
085 try {
086 final String daoImplClass =
087 daoMapping.findDAOImplClass (daoMapping.getCurrentType ());
088
089 if (StringUtil.isNullOrEmpty (daoImplClass)) {
090 throw new DAOException("Not found DAO implement class of:[" +
091 daoMapping + "]");
092 }
093
094 //new instance
095 Class clazz = Class.forName (daoImplClass);
096 daoInstance = (DAO) clazz.newInstance ();
097
098 //set current type
099 daoInstance.setCurrentType (daoMapping.getCurrentType ());
100
101 //add to dao pool
102 daos.setFast (false);
103 daos.put (key, daoInstance);
104 daos.setFast (true);
105
106 if (log.isDebugEnabled ()) {
107 log.debug ("A DAO instance created:[" + key + "]");
108 }
109 } catch (ClassNotFoundException e) {
110 log.error ("ClassNotFoundException:" + e.getMessage());
111 throw new DAOException(e);
112 } catch (InstantiationException e) {
113 log.error ("InstantiationException:" + e.getMessage());
114 throw new DAOException(e);
115 } catch (IllegalAccessException e) {
116 log.error ("IllegalAccessException:" + e.getMessage());
117 throw new DAOException(e);
118 }
119 }
120 return daoInstance;
121 }
122 }
相应的配置文件:
01 <!-- Services -->
02 <services>
03 <service name="ACLService" className="org.skyinn.quasar.acl.ACLService"/>
04 </services>
05
06 <!--DAO Mappings-->
07 <dao-mappings>
08 <dao key="org.skyinn.quasar.acl.dao.UserDAO1" currentType="hibernate">
09 <dao-impl type="hibernate" implClass="org.skyinn.quasar.acl.dao.hibernate.UserDAOHibImpl"/>
10 </dao>
11 </dao-mappings>
--------------------------------------------------------------------------------
而现在在使用了spring之后,只定义了三个类或接口:
DAO DAO接口
DAOException 异常
HibernateDAO Hibernate dao 基类,
而且相应的代码不到100行:
01 /* =====================================================================
02 * $Id: HibernateDAO.java,v 1.1 2004/07/26 14:38:22 l_walker Exp $
03 *
04 * Created: [2004-7-25 0:03:47] by l_walker
05 * =====================================================================*/
06 package org.skyinn.quasar.dao;
07
08 import java.util.List;
09
10 import org.skyinn.quasar.common.PersistentObject;
11 import org.springframework.orm.hibernate.support.HibernateDaoSupport;
12
13 /**
14 * <p>HibernateDAO.java</p>
15 *
16 * <p>
17 * <a href="HibernateDAO.java.java.html"><i>View Source</i></a>
18 * </p>
19 *
20 * @author $Author: l_walker $
21 * @version $Reversion$ $Date: 2004/07/26 14:38:22 $
22 */
23 public class HibernateDAO extends HibernateDaoSupport implements DAO {
24 private static final String KEY = "HibernateDAO";
25
26 public PersistentObject createObject(PersistentObject obj) {
27 return (PersistentObject) this.getHibernateTemplate().save(obj);
28 }
29
30 public void updateObject(PersistentObject obj) {
31 this.getHibernateTemplate().update(obj);
32 }
33
34 public void deleteObject(PersistentObject obj) {
35 this.getHibernateTemplate().delete(obj);
36 }
37 public void deleteObjectById(Class clazz, long id) {
38 PersistentObject obj =
39 (PersistentObject) this.getHibernateTemplate().load(
40 clazz,
41 new Long(id));
42 if (null != obj) {
43 this.getHibernateTemplate().delete(obj);
44 }
45 }
46
47 public PersistentObject retriveObjectById(Class clazz, long id) {
48 return (PersistentObject) this.getHibernateTemplate().load(
49 clazz,
50 new Long(id));
51 }
52
53 public List listAll(Class clazz){
54 return this.getHibernateTemplate().loadAll(clazz);
55 }
56
57
58 }
session管理、事务等等都交由spring去处理,确实省事不少。