1、Spring框架对MyBatis的支持于JDBC支持非常类似,也不需要特殊的事务管理策略,使用的是标准的JDBC DataSourceTransactionManager和JtaTransactionManager。
2、使用实例:
2.1、Spring对MyBatis框架的支持是通过注入SqlMapClient。通过使用SqlMapClientFactoryBean生成SqlMapClient,方法如下:
<beans>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation" value="WEB-INF/sqlmap-config.xml"/>
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
其中sqlmap-config.xml定义如下:
<sqlMapConfig>
<sqlMap resource="example/Account.xml"/>
</sqlMapConfig>
Account.xml定义如下:
<sqlMap namespace="Account">
<resultMap id="result" class="examples.Account">
<result property="name" column="NAME" columnIndex="1"/>
<result property="email" column="EMAIL" columnIndex="2"/>
</resultMap>
<select id="getAccountByEmail" resultMap="result">
select ACCOUNT.NAME, ACCOUNT.EMAIL
from ACCOUNT
where ACCOUNT.EMAIL = #value#
</select>
<insert id="insertAccount">
insert into ACCOUNT (NAME, EMAIL) values (#name#, #email#)
</insert>
</sqlMap>
领域对象Account的定义如下:
public class Account {
private String name;
private String email;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
}
2.2 使用SqlMapClientTemplate and SqlMapClientDaoSupport
2.2.1、实例对象:
public class SqlMapAccountDao extends SqlMapClientDaoSupport implements AccountDao {
public Account getAccount(String email) throws DataAccessException {
return (Account) getSqlMapClientTemplate().queryForObject("getAccountByEmail", email);
}
public void insertAccount(Account account) throws DataAccessException {
getSqlMapClientTemplate().update("insertAccount", account);
}
}
2.2.2、依赖注入
<beans>
<bean id="accountDao" class="example.SqlMapAccountDao">
<property name="sqlMapClient" ref="sqlMapClient"/>
</bean>
</beans>