在Service里直接玩iBATIS,为iBATIS添个贴吧

以前使用iBATIS时,都是参考了iBATIS官网上的JPetStore做的。不过这个JPetStore似乎太老了,以致于我们参照后,所写的DB层又难看又繁琐。看了看我的DAO类,需要先定义一个接口,再定义一个Impl类,然后,每个方法里差不多都是一两句话的事。现在,我把DAO直接干掉了,完全用iBATIS来充当DAO,借助于Spring的注解,将iBATIS的DB操作对象直接注入Service中,而且什么也不用继承和实现,单纯的Java类一个。如果使用的是Struts2,一个Action一个Service就可以了,都是单纯的Java类,什么都不继承,什么也不实现。

具体如下:

1、在applicationContext.xml中,添点东西。
  ① beans标签中增加【xmlns:context="http://www.springframework.org/schema/context"】声明。
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="  
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd  
       http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd 
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
       default-lazy-init="true">

  ② 增加annotation自动注册Bean的声明。
<!-- 使用annotation 自动注册bean,并检查@Required,@Autowired的属性已被注入 -->
<context:component-scan base-package="需要自动注册的包名" />
  ③ iBATIS部分的配置
	<!-- Spring的iBatis 配置 -->
	<bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate">
		<constructor-arg>
			<ref bean="sqlMapClient"></ref>
		</constructor-arg>
	</bean>
	<bean id="sqlMapClient"
		class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		<property name="configLocation"
			value="WEB-INF/SqlMapConfig.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>

注:①②,可以Google下;③是关键,这样就搞出一个被注好的sqlMapClientTemplate对象,可以用它来操作数据库了。

2、Service类,什么也不用继承或实现。

代码截段如下:

@Service
public class BookmarkService {
        /** iBATIS的DB操作辅助类对象 */
        @Autowired
        private SqlMapClientTemplate sqlMapClientTemplate;
        // 注:不需要set/get方法,自动注入
.....

    /**
     * 查询基本书签.<br />
     * 
     * @param mapBean
     * @return
     */
    public List searchBookmarkBaseList(Map mapBean) {
        return sqlMapClientTemplate.queryForList("Bookmark.searchBookmarkBaseList", mapBean);
    }

}


通过上面的搞法,就完全可以不用再整出一个如:public class UserDaoImpl extends SqlMapClientDaoSupport implements UserDao {...}这样写法的Impl类了,当然也省了那个接口(这种接口总是想的挺好,往往鸡肋一堆),当然进行DB操作时,更不需要使用那个实在太别扭的:getSqlMapClientTemplate().queryForObject(...)写法了。

现在的作法,简单务实多了。


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