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

本文介绍了一种简化iBATIS与Spring框架整合的方法,通过Spring注解直接注入iBATIS操作对象到Service层,避免了DAO接口及其实现类的冗余,使代码更加简洁高效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

具体如下:

[b]1、在applicationContext.xml中,添点东西。[/b]
  ① 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对象,可以用它来操作数据库了。
[b]
2、Service类,什么也不用继承或实现。[/b]
代码截段如下:

@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(...)写法了。

现在的作法,简单务实多了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值