开发环境:
System:Windows
WebBrowser:IE6+、Firefox3+
JavaEE Server:tomcat5.0.2.8、tomcat6
IDE:eclipse、MyEclipse 8
Database:MySQL
开发依赖库:
JavaEE5、Spring 3.0.5、Mybatis 3.0.4、myBatis-spring-1.0、junit4.8.2
Email:hoojo_@126.com
Blog:http://blog.csdn.net/IBM_hoojo
http://hoojo.cnblogs.com/
1、 首先新建一个WebProject 命名为MyBatisForSpring,新建项目时,使用JavaEE5的lib库。然后手动添加需要的jar包,所需jar包如下:
2、 添加spring的监听及springMVC的核心Servlet,web.xml内容,内容如下:
< -- 加载Spring容器配置 -- >
<!--CRLF-->
< listener >
<!--CRLF-->
< listener-class > org.springframework.web.context.ContextLoaderListener<!--< span-->listener-class >
<!--CRLF-->
<!--< span-->listener >
<!--CRLF-->
<!--CRLF-->
< -- 设置Spring容器加载配置文件路径 -- >
<!--CRLF-->
< context-param >
<!--CRLF-->
< param-name > contextConfigLocation<!--< span-->param-name >
<!--CRLF-->
< param-value > classpath*:applicationContext-*.xml<!--< span-->param-value >
<!--CRLF-->
<!--< span-->context-param >
<!--CRLF-->
<!--CRLF-->
< -- 配置Spring核心控制器 -- >
<!--CRLF-->
< servlet >
<!--CRLF-->
< servlet-name > dispatcher<!--< span-->servlet-name >
<!--CRLF-->
< servlet-class > org.springframework.web.servlet.DispatcherServlet<!--< span-->servlet-class >
<!--CRLF-->
< init-param >
<!--CRLF-->
< param-name > contextConfigLocation<!--< span-->param-name >
<!--CRLF-->
< param-value > /WEB-INF/dispatcher.xml<!--< span-->param-value >
<!--CRLF-->
<!--< span-->init-param >
<!--CRLF-->
< load-on-startup > 1<!--< span-->load-on-startup >
<!--CRLF-->
<!--< span-->servlet >
<!--CRLF-->
<!--CRLF-->
< servlet-mapping >
<!--CRLF-->
< servlet-name > dispatcher<!--< span-->servlet-name >
<!--CRLF-->
< url-pattern > *.do<!--< span-->url-pattern >
<!--CRLF-->
<!--< span-->servlet-mapping >
<!--CRLF-->
<!--CRLF-->
< -- 解决工程编码过滤器 -- >
<!--CRLF-->
< filter >
<!--CRLF-->
< filter-name > characterEncodingFilter<!--< span-->filter-name >
<!--CRLF-->
< filter-class > org.springframework.web.filter.CharacterEncodingFilter<!--< span-->filter-class >
<!--CRLF-->
< init-param >
<!--CRLF-->
< param-name > encoding<!--< span-->param-name >
<!--CRLF-->
< param-value > UTF-8<!--< span-->param-value >
<!--CRLF-->
<!--< span-->init-param >
<!--CRLF-->
<!--< span-->filter >
<!--CRLF-->
<!--CRLF-->
< filter-mapping >
<!--CRLF-->
< filter-name > characterEncodingFilter<!--< span-->filter-name >
<!--CRLF-->
< url-pattern > /*<!--< span-->url-pattern >
<!--CRLF-->
<!--< span-->filter-mapping >
<!--CRLF-->
3、 在WEB-INF目录中添加dispatcher.xml,内容如下:
<!--?</span-->xml version ="1.0" encoding ="UTF-8"?>
<!--CRLF-->
< beans xmlns ="http://www.springframework.org/schema/beans"
<!--CRLF-->
xmlns:context ="http://www.springframework.org/schema/context"
<!--CRLF-->
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
<!--CRLF-->
xsi:schemaLocation ="http://www.springframework.org/schema/beans
<!--CRLF-->
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
<!--CRLF-->
http://www.springframework.org/schema/context
<!--CRLF-->
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--CRLF-->
< -- 注解探测器 -- >
<!--CRLF-->
< context:component-scan base-package ="com.hoo" />
<!--CRLF-->
<!--CRLF-->
< -- annotation默认的方法映射适配器 -- >
<!--CRLF-->
< bean id ="handlerMapping" class ="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<!--CRLF-->
<!--CRLF-->
< bean id ="handlerAdapter" class ="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<!--CRLF-->
<!--< span-->beans >
<!--CRLF-->
4、 在src目录下添加applicationContext-common.xml,内容如下:
<!--?</span-->xml version ="1.0" encoding ="UTF-8"?>
<!--CRLF-->
< beans xmlns ="http://www.springframework.org/schema/beans"
<!--CRLF-->
xmlns:aop ="http://www.springframework.org/schema/aop"
<!--CRLF-->
xmlns:tx ="http://www.springframework.org/schema/tx"
<!--CRLF-->
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
<!--CRLF-->
xsi:schemaLocation ="http://www.springframework.org/schema/beans
<!--CRLF-->
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
<!--CRLF-->
http://www.springframework.org/schema/aop
<!--CRLF-->
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
<!--CRLF-->
http://www.springframework.org/schema/tx
<!--CRLF-->
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
<!--CRLF-->
<!--CRLF-->
< -- 配置DataSource数据源 -- >
<!--CRLF-->
< bean id ="dataSource" class ="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<!--CRLF-->
< property name ="driverClassName" value ="com.mysql.jdbc.Driver" />
<!--CRLF-->
< property name ="url" value ="jdbc:mysql://10.0.0.131:3306/ash2" />
<!--CRLF-->
< property name ="username" value ="dev" />
<!--CRLF-->
< property name ="password" value ="dev" />
<!--CRLF-->
<!--< span-->bean >
<!--CRLF-->
<!--CRLF-->
< -- 配置SqlSessionFactoryBean -- >
<!--CRLF-->
< bean id ="sqlSessionFactory" class ="org.mybatis.spring.SqlSessionFactoryBean" >
<!--CRLF-->
< property name ="dataSource" ref ="dataSource" />
<!--CRLF-->
< property name ="configLocation" value ="classpath:mybatis.xml" />
<!--CRLF-->
< -- mapper和resultmap配置路径 -- >
<!--CRLF-->
< property name ="mapperLocations" >
<!--CRLF-->
< list >
<!--CRLF-->
< -- 表示在com .hoo .resultmap包或以下所有目录中 ,以-resultmap .xml结尾所有文件 -- >
<!--CRLF-->
< value > classpath:com/hoo/resultmap/**/*-resultmap.xml<!--< span-->value >
<!--CRLF-->
< value > classpath:com/hoo/entity/*-resultmap.xml<!--< span-->value >
<!--CRLF-->
< value > classpath:com/hoo/mapper/**/*-mapper.xml<!--< span-->value >
<!--CRLF-->
<!--< span-->list >
<!--CRLF-->
<!--< span-->property >
<!--CRLF-->
<!--< span-->bean >
<!--CRLF-->
<!--CRLF-->
< -- 单独配置一个Mapper ; 这种模式就是得给每个mapper接口配置一个bean -- >
<!--CRLF-->
< --
<!--CRLF-->
<bean id ="accountMapper" class ="org.mybatis.spring.mapper.MapperFactoryBean" >
<!--CRLF-->
< property name ="mapperInterface" value ="com.hoo.mapper.AccountMapper" />
<!--CRLF-->
< property name ="sqlSessionFactory" ref ="sqlSessionFactory" />
<!--CRLF-->
<!--< span-->bean >
<!--CRLF-->
<!--CRLF-->
< bean id ="companyMapper" class ="org.mybatis.spring.mapper.MapperFactoryBean" >
<!--CRLF-->
< property name ="mapperInterface" value ="com.hoo.mapper.CompanyMapper" />
<!--CRLF-->
< property name ="sqlSessionFactory" ref ="sqlSessionFactory" />
<!--CRLF-->
<!--< span-->bean >
<!--CRLF-->
-->
<!--CRLF-->
<!--CRLF-->
< -- 通过扫描的模式 ,扫描目录在com /hoo /mapper目录下 ,所有的mapper都继承SqlMapper接口的接口 , 这样一个bean就可以了 -- >
<!--CRLF-->
< bean class ="org.mybatis.spring.mapper.MapperScannerConfigurer" >
<!--CRLF-->
< property name ="basePackage" value ="com.hoo.mapper" />
<!--CRLF-->
< property name ="markerInterface" value ="com.hoo.mapper.SqlMapper" />
<!--CRLF-->
<!--< span-->bean >
<!--CRLF-->
<!--< span-->beans >
<!--CRLF-->
上面的配置最先配置的是DataSource,这里采用的是jdbc的DataSource;
然后是SqlSessionFactoryBean,这个配置比较关键。SqlSessionFactoryBean需要注入DataSource数据源,其次还要设置configLocation也就是mybatis的xml配置文件路径,完成一些关于mybatis的配置,如settings、mappers、plugin等;
如果使用mapperCannerConfigurer模式,需要设置扫描根路径也就是你的mybatis的mapper接口所在包路径;凡是markerInterface这个接口的子接口都参与到这个扫描,也就是说所有的mapper接口继承这个SqlMapper。
如果你不使用自己的transaction事务,就使用MapperScannerConfigurer来完成SqlSession的打开、关闭和事务的回滚操作。在此期间,出现数据库操作的如何异常都会被转换成DataAccessException,这个异常是一个抽象的类,继承RuntimeException;
5、 SqlMapper内容如下:
package com.hoo.mapper;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: 所有的Mapper继承这个接口
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-12 下午04:00:31
<!--CRLF-->
* @file SqlMapper.java
<!--CRLF-->
* @package com.hoo.mapper
<!--CRLF-->
* @project MyBatisForSpring
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email hoojo_@126.com
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
public interface SqlMapper {
<!--CRLF-->
<!--CRLF-->
}
<!--CRLF-->
6、 实体类和ResultMap.xml
package com.hoo.entity;
<!--CRLF-->
<!--CRLF-->
import java.io.Serializable;
<!--CRLF-->
import javax.persistence.Entity;
<!--CRLF-->
<!--CRLF-->
@Entity
<!--CRLF-->
public class Account implements Serializable {
<!--CRLF-->
<!--CRLF-->
private static final long serialVersionUID = -7970848646314840509L;
<!--CRLF-->
<!--CRLF-->
private Integer accountId;
<!--CRLF-->
private Integer status;
<!--CRLF-->
private String username;
<!--CRLF-->
private String password;
<!--CRLF-->
private String salt;
<!--CRLF-->
private String email;
<!--CRLF-->
private Integer roleId;
<!--CRLF-->
<!--CRLF-->
//getter、setter
<!--CRLF-->
<!--CRLF-->
@Override
<!--CRLF-->
public String toString() {
<!--CRLF-->
return this .accountId + "#" + this .status + "#" + this .username + "#" +
<!--CRLF-->
this .password + "#" + this .email + "#" + this .salt + "#" + this .roleId;
<!--CRLF-->
}
<!--CRLF-->
}
<!--CRLF-->
account-resultmap.xml
<!--?</span-->xml version ="1.0" encoding ="UTF-8"?>
<!--CRLF-->
<!--</span-->DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<!--CRLF-->
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!--CRLF-->
< mapper namespace ="accountMap" >
<!--CRLF-->
< resultMap type ="com.hoo.entity.Account" id ="accountResultMap" >
<!--CRLF-->
< id property ="accountId" column ="account_id" />
<!--CRLF-->
< result property ="username" column ="username" />
<!--CRLF-->
< result property ="password" column ="password" />
<!--CRLF-->
< result property ="status" column ="status" />
<!--CRLF-->
<!--< span-->resultMap >
<!--CRLF-->
<!--< span-->mapper >
<!--CRLF-->
7、 在src目录中添加applicationContext-beans.xml内容如下:
<!--?</span-->xml version ="1.0" encoding ="UTF-8"?>
<!--CRLF-->
< beans xmlns ="http://www.springframework.org/schema/beans"
<!--CRLF-->
xmlns:context ="http://www.springframework.org/schema/context"
<!--CRLF-->
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
<!--CRLF-->
xsi:schemaLocation ="http://www.springframework.org/schema/beans
<!--CRLF-->
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
<!--CRLF-->
http://www.springframework.org/schema/context
<!--CRLF-->
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--CRLF-->
< -- 注解探测器 , 在JUnit测试的时候需要-- >
<!--CRLF-->
< context:component-scan base-package ="com.hoo" />
<!--CRLF-->
<!--CRLF-->
<!--< span-->beans >
<!--CRLF-->
这里配置bean对象,一些不能用annotation注解的对象就可以配置在这里
8、 在src目录中添加mybatis.xml,内容如下:
<!--?</span-->xml version ="1.0" encoding ="UTF-8" ?>
<!--CRLF-->
<!--</span-->DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--CRLF-->
< configuration >
<!--CRLF-->
< -- 别名 -- >
<!--CRLF-->
< typeAliases >
<!--CRLF-->
< typeAlias type ="com.hoo.entity.Account" alias ="account" />
<!--CRLF-->
<!--< span-->typeAliases >
<!--CRLF-->
<!--< span-->configuration >
<!--CRLF-->
在这个文件放置一些全局性的配置,如handler、objectFactory、plugin、以及mappers的映射路径(由于在applicationContext-common中的SqlSessionFactoryBean有配置mapper的location,这里就不需要配置)等
9、 AccountMapper接口,内容如下:
package com.hoo.mapper;
<!--CRLF-->
<!--CRLF-->
import java.util.List;
<!--CRLF-->
import org.apache.ibatis.annotations.Select;
<!--CRLF-->
import com.hoo.entity.Account;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: 继承SqlMapper,MyBatis数据操作接口;此接口无需实现类
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2010-12-21 下午05:21:20
<!--CRLF-->
* @file AccountMapper.java
<!--CRLF-->
* @package com.hoo.mapper
<!--CRLF-->
* @project MyBatis
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email hoojo_@126.com
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
public interface AccountMapper extends SqlMapper {
<!--CRLF-->
<!--CRLF-->
public List getAllAccount();
<!--CRLF-->
<!--CRLF-->
public Account getAccount();
<!--CRLF-->
<!--CRLF-->
public Account getAccountById(String id);
<!--CRLF-->
<!--CRLF-->
public Account getAccountByNames(String spring);
<!--CRLF-->
<!--CRLF-->
@Select("select * from account where username = #{name}" )
<!--CRLF-->
public Account getAccountByName(String name);
<!--CRLF-->
<!--CRLF-->
public void addAccount(Account account);
<!--CRLF-->
<!--CRLF-->
public void editAccount(Account account);
<!--CRLF-->
<!--CRLF-->
public void removeAccount(int id);
<!--CRLF-->
}
<!--CRLF-->
这个接口我们不需要实现,由mybatis帮助我们实现,我们通过mapper文件配置sql语句即可完成接口的实现。然后这个接口需要继承SqlMapper接口,不然在其他地方就不能从Spring容器中拿到这个mapper接口,也就是说当我们注入这个接口的时候将会失败。
当然,你不继承这个接口也可以。那就是你需要给买个mapper配置一个bean。配置方法如下:
< bean id ="accountMapper" class ="org.mybatis.spring.mapper.MapperFactoryBean" >
<!--CRLF-->
< property name ="mapperInterface" value ="com.hoo.mapper.AccountMapper" />
<!--CRLF-->
< property name ="sqlSessionFactory" ref ="sqlSessionFactory" />
<!--CRLF-->
<!--< span-->bean >
<!--CRLF-->
这里的MapperFactoryBean可以帮助我们完成Session的打开、关闭等操作
10、 在com.hoo.mapper也就是在AccountMapper接口的同一个包下,添加account-mapper.xml,内容如下:
<!--?</span-->xml version ="1.0" encoding ="UTF-8"?>
<!--CRLF-->
<!--</span-->DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<!--CRLF-->
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!--CRLF-->
< -- namespace和定义的Mapper接口对应 ,并实现其中的方法 -- >
<!--CRLF-->
< mapper namespace ="com.hoo.mapper.AccountMapper" >
<!--CRLF-->
< -- id和mapper接口中的方法名对应 ,resultType使用mybatis .xml中的别名 -- >
<!--CRLF-->
< select id ="getAccount" resultType ="account" >
<!--CRLF-->
<!--</span-->[CDATA[
<!--CRLF-->
select * from account limit 1
<!--CRLF-->
]]>
<!--CRLF-->
<!--< span-->select >
<!--CRLF-->
<!--CRLF-->
< select id ="getAllAccount" resultType ="list" resultMap ="accountResultMap" >
<!--CRLF-->
<!--</span-->[CDATA[
<!--CRLF-->
select * from account
<!--CRLF-->
]]>
<!--CRLF-->
<!--< span-->select >
<!--CRLF-->
<!--CRLF-->
< -- accountResultMap是account-resultmap .xml中定义的resultmap -- >
<!--CRLF-->
< select id ="getAccountById" parameterType ="string" resultType ="com.hoo.entity.Account" resultMap ="accountResultMap" >
<!--CRLF-->
<!--</span-->[CDATA[
<!--CRLF-->
select * from account where account_id = #{id}
<!--CRLF-->
]]>
<!--CRLF-->
<!--< span-->select >
<!--CRLF-->
<!--CRLF-->
< -- accountMap .accountResultMap是account-resultmap .xml中定义的resultmap ,通过namespace .id找到 -- >
<!--CRLF-->
< select id ="getAccountByNames" parameterType ="string" resultMap ="accountMap.accountResultMap" >
<!--CRLF-->
<!--</span-->[CDATA[
<!--CRLF-->
select * from account where username = #{name}
<!--CRLF-->
]]>
<!--CRLF-->
<!--< span-->select >
<!--CRLF-->
<!--CRLF-->
< sql id ="user_name_pwd" >
<!--CRLF-->
username, password
<!--CRLF-->
<!--< span-->sql >
<!--CRLF-->
<!--CRLF-->
< -- 自动生成id策略 -- >
<!--CRLF-->
< insert id ="addAccount" useGeneratedKeys ="true" keyProperty ="account_id" parameterType ="account" >
<!--CRLF-->
insert into account(account_id, status, username, password)
<!--CRLF-->
values(#{accountId}, #{status}, #{username}, #{password})
<!--CRLF-->
<!--< span-->insert >
<!--CRLF-->
<!--CRLF-->
< -- 根据selectKey语句生成主键 -- >
<!--CRLF-->
< insert id ="addAccount4Key" parameterType ="account" >
<!--CRLF-->
< selectKey keyProperty ="account_id" order ="BEFORE" resultType ="int" >
<!--CRLF-->
select cast(random() * 10000 as Integer) a from #Tab
<!--CRLF-->
<!--< span-->selectKey >
<!--CRLF-->
insert into account(account_id, status, username, password)
<!--CRLF-->
values(#{accountId}, #{status}, #{username}, #{password})
<!--CRLF-->
<!--< span-->insert >
<!--CRLF-->
<!--CRLF-->
< update id ="editAccount" parameterType ="account" >
<!--CRLF-->
update account set
<!--CRLF-->
status = #{status},
<!--CRLF-->
username = #{username},
<!--CRLF-->
password = #{password}
<!--CRLF-->
where account_id = #{accountId}
<!--CRLF-->
<!--< span-->update >
<!--CRLF-->
<!--CRLF-->
< delete id ="removeAccount" parameterType ="int" >
<!--CRLF-->
delete from account where account_id = #{id}
<!--CRLF-->
<!--< span-->delete >
<!--CRLF-->
<!--< span-->mapper >
<!--CRLF-->
上面的namespace和定义接口类路径对应,所有的sql语句,如select、insert、delete、update的id和方法名称对应。关于更多MyBatis内容的讲解,这里就不赘述的。这里只完成整合!如果你不懂可以去阅读其他关于MyBatis的资料。
11、 为了测试发布,这里使用junit和spring官方提供的spring-test.jar,完成spring框架整合的测试,代码如下:
package com.hoo.mapper;
<!--CRLF-->
<!--CRLF-->
import java.util.List;
<!--CRLF-->
import javax.inject.Inject;
<!--CRLF-->
import org.springframework.test.context.ContextConfiguration;
<!--CRLF-->
import org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests;
<!--CRLF-->
import com.hoo.entity.Account;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: AccountMapper JUnit测试类
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-12 下午04:21:50
<!--CRLF-->
* @file AccountMapperTest.java
<!--CRLF-->
* @package com.hoo.mapper
<!--CRLF-->
* @project MyBatisForSpring
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email hoojo_@126.com
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
<!--CRLF-->
@ContextConfiguration("classpath:applicationContext-*.xml" )
<!--CRLF-->
public class AccountMapperTest extends AbstractJUnit38SpringContextTests {
<!--CRLF-->
<!--CRLF-->
@Inject
<!--CRLF-->
//@Named("accountMapper")
<!--CRLF-->
private AccountMapper mapper;
<!--CRLF-->
<!--CRLF-->
public void testGetAccount() {
<!--CRLF-->
System.out.println(mapper.getAccount());
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public void testGetAccountById() {
<!--CRLF-->
System.out.println(mapper.getAccountById("28" ));
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public void testGetAccountByName() {
<!--CRLF-->
System.out.println(mapper.getAccountByName("user" ));
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public void testGetAccountByNames() {
<!--CRLF-->
System.out.println(mapper.getAccountByNames("user" ));
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public void testAdd() {
<!--CRLF-->
Account account = new Account();
<!--CRLF-->
account.setEmail("temp@155.com" );
<!--CRLF-->
account.setPassword("abc" );
<!--CRLF-->
account.setRoleId(1);
<!--CRLF-->
account.setSalt("ss" );
<!--CRLF-->
account.setStatus(0);
<!--CRLF-->
account.setUsername("Jack" );
<!--CRLF-->
mapper.addAccount(account);
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public void testEditAccount() {
<!--CRLF-->
Account acc = mapper.getAccountByNames("Jack" );
<!--CRLF-->
System.out.println(acc);
<!--CRLF-->
acc.setUsername("Zhangsan" );
<!--CRLF-->
acc.setPassword("123123" );
<!--CRLF-->
mapper.editAccount(acc);
<!--CRLF-->
System.out.println(mapper.getAccountById(acc.getAccountId() + "" ));
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public void testRemoveAccount() {
<!--CRLF-->
Account acc = mapper.getAccountByNames("Jack" );
<!--CRLF-->
mapper.removeAccount(acc.getAccountId());
<!--CRLF-->
System.out.println(mapper.getAccountByNames("Jack" ));
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public void testAccountList() {
<!--CRLF-->
List acc = mapper.getAllAccount();
<!--CRLF-->
System.out.println(acc.size());
<!--CRLF-->
System.out.println(acc);
<!--CRLF-->
}
<!--CRLF-->
}
<!--CRLF-->
这里的注入并没有使用@Autowired、@Resource、@Qualifier注入,而是使用@Inject、@Named注入方式,Inject注入是JSR330的标准注入方式;而不局限于某个产品,使用于多个产品的使用,推荐使用这种方式;运行后,没有发现问题,就可以继续后续的编码工作了。
12、 定义AccountDao接口及实现代码,代码如下:
package com.hoo.dao;
<!--CRLF-->
<!--CRLF-->
import java.util.List;
<!--CRLF-->
import org.springframework.dao.DataAccessException;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: Account数据库操作dao接口
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-13 上午10:21:38
<!--CRLF-->
* @file AccountDao.java
<!--CRLF-->
* @package com.hoo.dao
<!--CRLF-->
* @project MyBatisForSpring
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email hoojo_@126.com
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
public interface AccountDao {
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: 添加Account对象信息
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-13 上午11:50:05
<!--CRLF-->
* @param entity Account
<!--CRLF-->
* @return boolean 是否成功
<!--CRLF-->
* @throws DataAccessException
<!--CRLF-->
*/
<!--CRLF-->
public boolean addAccount(T entity) throws DataAccessException;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: 根据id对到Account信息
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-13 上午11:50:45
<!--CRLF-->
* @param id 编号id
<!--CRLF-->
* @return Account
<!--CRLF-->
* @throws DataAccessException
<!--CRLF-->
*/
<!--CRLF-->
public T getAccount(Integer id) throws DataAccessException;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: 查询所有Account信息
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-13 上午11:51:45
<!--CRLF-->
* @param id 编号id
<!--CRLF-->
* @return Account
<!--CRLF-->
* @throws DataAccessException
<!--CRLF-->
*/
<!--CRLF-->
public List getList() throws DataAccessException;
<!--CRLF-->
}
<!--CRLF-->
接口实现
package com.hoo.dao.impl;
<!--CRLF-->
<!--CRLF-->
import java.util.List;
<!--CRLF-->
import javax.inject.Inject;
<!--CRLF-->
import org.springframework.dao.DataAccessException;
<!--CRLF-->
import org.springframework.stereotype.Repository;
<!--CRLF-->
import com.hoo.dao.AccountDao;
<!--CRLF-->
import com.hoo.entity.Account;
<!--CRLF-->
import com.hoo.mapper.AccountMapper;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: Account数据库操作dao
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-13 上午10:25:02
<!--CRLF-->
* @file AccountDaoImpl.java
<!--CRLF-->
* @package com.hoo.dao.impl
<!--CRLF-->
* @project MyBatisForSpring
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email hoojo_@126.com
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
@SuppressWarnings("unchecked" )
<!--CRLF-->
@Repository
<!--CRLF-->
public class AccountDaoImplextends Account> implements AccountDao {
<!--CRLF-->
<!--CRLF-->
@Inject
<!--CRLF-->
private AccountMapper mapper;
<!--CRLF-->
<!--CRLF-->
public boolean addAccount(T entity) throws DataAccessException {
<!--CRLF-->
boolean flag = false;
<!--CRLF-->
try {
<!--CRLF-->
mapper.addAccount(entity);
<!--CRLF-->
flag = true;
<!--CRLF-->
} catch (DataAccessException e) {
<!--CRLF-->
flag = false;
<!--CRLF-->
throw e;
<!--CRLF-->
}
<!--CRLF-->
return flag;
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public T getAccount(Integer id) throws DataAccessException {
<!--CRLF-->
T entity = null;
<!--CRLF-->
try {
<!--CRLF-->
entity = (T) mapper.getAccountById(String.valueOf(id));
<!--CRLF-->
} catch (DataAccessException e) {
<!--CRLF-->
throw e;
<!--CRLF-->
}
<!--CRLF-->
return entity;
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public List getList() throws DataAccessException {
<!--CRLF-->
return (List) mapper.getAllAccount();
<!--CRLF-->
}
<!--CRLF-->
}
<!--CRLF-->
13、 服务层AccountBiz接口及实现代码
接口:
package com.hoo.biz;
<!--CRLF-->
<!--CRLF-->
import java.util.List;
<!--CRLF-->
import org.springframework.dao.DataAccessException;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: biz层Account接口
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-13 上午11:33:04
<!--CRLF-->
* @file AccountBiz.java
<!--CRLF-->
* @package com.hoo.biz
<!--CRLF-->
* @project MyBatisForSpring
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email hoojo_@126.com
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
public interface AccountBiz {
<!--CRLF-->
/**
<!--CRLF-->
* function: 添加Account对象信息
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-13 上午11:50:05
<!--CRLF-->
* @param entity Account
<!--CRLF-->
* @return boolean 是否成功
<!--CRLF-->
* @throws DataAccessException
<!--CRLF-->
*/
<!--CRLF-->
public boolean addAccount(T entity) throws DataAccessException;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: 根据id对到Account信息
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-13 上午11:50:45
<!--CRLF-->
* @param id 编号id
<!--CRLF-->
* @return Account
<!--CRLF-->
* @throws DataAccessException
<!--CRLF-->
*/
<!--CRLF-->
public T getAccount(Integer id) throws DataAccessException;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: 查询所有Account信息
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-13 上午11:51:45
<!--CRLF-->
* @param id 编号id
<!--CRLF-->
* @return Account
<!--CRLF-->
* @throws DataAccessException
<!--CRLF-->
*/
<!--CRLF-->
public List getList() throws DataAccessException;
<!--CRLF-->
}
<!--CRLF-->
实现代码:
package com.hoo.biz.impl;
<!--CRLF-->
<!--CRLF-->
import java.util.List;
<!--CRLF-->
import javax.inject.Inject;
<!--CRLF-->
import org.springframework.dao.DataAccessException;
<!--CRLF-->
import org.springframework.stereotype.Service;
<!--CRLF-->
import com.hoo.biz.AccountBiz;
<!--CRLF-->
import com.hoo.dao.AccountDao;
<!--CRLF-->
import com.hoo.entity.Account;
<!--CRLF-->
import com.hoo.exception.BizException;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: Account Biz接口实现
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-13 上午11:34:39
<!--CRLF-->
* @file AccountBizImpl.java
<!--CRLF-->
* @package com.hoo.biz.impl
<!--CRLF-->
* @project MyBatisForSpring
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email hoojo_@126.com
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
//@Component
<!--CRLF-->
@Service
<!--CRLF-->
public class AccountBizImplextends Account> implements AccountBiz {
<!--CRLF-->
<!--CRLF-->
@Inject
<!--CRLF-->
private AccountDao dao;
<!--CRLF-->
<!--CRLF-->
public boolean addAccount(T entity) throws DataAccessException {
<!--CRLF-->
if (entity == null) {
<!--CRLF-->
throw new BizException(Account.class .getName() + "对象参数信息为Empty!" );
<!--CRLF-->
}
<!--CRLF-->
return dao.addAccount(entity);
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public T getAccount(Integer id) throws DataAccessException {
<!--CRLF-->
return dao.getAccount(id);
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public List getList() throws DataAccessException {
<!--CRLF-->
return dao.getList();
<!--CRLF-->
}
<!--CRLF-->
}
<!--CRLF-->
上面用到了一个自定义的异常信息,代码如下:
package com.hoo.exception;
<!--CRLF-->
<!--CRLF-->
import org.springframework.dao.DataAccessException;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: 自定义Biz层异常信息
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-13 上午11:42:19
<!--CRLF-->
* @file BizException.java
<!--CRLF-->
* @package com.hoo.exception
<!--CRLF-->
* @project MyBatisForSpring
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email hoojo_@126.com
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
public class BizException extends DataAccessException {
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* @author Hoojo
<!--CRLF-->
*/
<!--CRLF-->
private static final long serialVersionUID = 1L;
<!--CRLF-->
<!--CRLF-->
public BizException(String msg) {
<!--CRLF-->
super (msg);
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public BizException(String msg, Throwable cause) {
<!--CRLF-->
super (msg, cause);
<!--CRLF-->
}
<!--CRLF-->
}
<!--CRLF-->
这里只是简单的继承,如果还有其他的异常业务或需求可以进行具体的实现
14、 springMVC的控制器,AccountController代码如下:
package com.hoo.controller;
<!--CRLF-->
<!--CRLF-->
import javax.inject.Inject;
<!--CRLF-->
import javax.servlet.http.HttpServletRequest;
<!--CRLF-->
import org.springframework.stereotype.Controller;
<!--CRLF-->
import org.springframework.ui.Model;
<!--CRLF-->
import org.springframework.web.bind.annotation.ExceptionHandler;
<!--CRLF-->
import org.springframework.web.bind.annotation.RequestMapping;
<!--CRLF-->
import com.hoo.biz.AccountBiz;
<!--CRLF-->
import com.hoo.entity.Account;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: Account控制器
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-13 上午10:18:02
<!--CRLF-->
* @file AccountController.java
<!--CRLF-->
* @package com.hoo.controller
<!--CRLF-->
* @project MyBatisForSpring
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email hoojo_@126.com
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
@Controller
<!--CRLF-->
@RequestMapping("/account" )
<!--CRLF-->
public class AccountController {
<!--CRLF-->
<!--CRLF-->
@Inject
<!--CRLF-->
private AccountBiz biz;
<!--CRLF-->
<!--CRLF-->
@RequestMapping("/add" )
<!--CRLF-->
public String add(Account acc) {
<!--CRLF-->
System.out.println(acc);
<!--CRLF-->
biz.addAccount(acc);
<!--CRLF-->
return "redirect:/account/list.do" ;
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
@RequestMapping("/get" )
<!--CRLF-->
public String get(Integer id, Model model) {
<!--CRLF-->
System.out.println("##ID:" + id);
<!--CRLF-->
model.addAttribute(biz.getAccount(id));
<!--CRLF-->
return "/show.jsp" ;
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
@RequestMapping("/list" )
<!--CRLF-->
public String list(Model model) {
<!--CRLF-->
model.addAttribute("list" , biz.getList());
<!--CRLF-->
return "/list.jsp" ;
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
@ExceptionHandler(Exception.class )
<!--CRLF-->
public String exception(Exception e, HttpServletRequest request) {
<!--CRLF-->
//e.printStackTrace();
<!--CRLF-->
request.setAttribute("exception" , e);
<!--CRLF-->
return "/error.jsp" ;
<!--CRLF-->
}
<!--CRLF-->
}
<!--CRLF-->
15、 基本页面代码
index.jsp
<%@ page language="java" import ="java.util.*" pageEncoding="UTF-8" %>
<!--CRLF-->
<%
<!--CRLF-->
String path = request.getContextPath();
<!--CRLF-->
String basePath = request.getScheme()+"://" +request.getServerName()+":" +request.getServerPort()+path+"/" ;
<!--CRLF-->
%>
<!--CRLF-->
<!--CRLF-->
"-//W3C//DTD HTML 4.01 Transitional//EN">
<!--CRLF-->
<!--CRLF-->
<!--CRLF-->
"<%=basePath%>">
<!--CRLF-->
<!--CRLF-->
<!--CRLF-->
"pragma" content="no-cache" >
<!--CRLF-->
"cache-control" content="no-cache" >
<!--CRLF-->
"expires" content="0" >
<!--CRLF-->
"keywords" content="keyword1,keyword2,keyword3" >
<!--CRLF-->
"description" content="This is my page" >
<!--CRLF-->
<!--CRLF-->
<!--CRLF-->
<!--CRLF-->
MyBatis 3.0.4 整合 Spring 3.0.5
<!--CRLF-->
"account/list.do">查询所有
<!--CRLF-->
"account/add.do?username=abcdef&password=123132&status=2">添加
<!--CRLF-->
"account/get.do?id=25">查询
<!--CRLF-->
<!--CRLF-->
<!--CRLF-->
List.jsp
< %@ page language="java" import="java.util .*" pageEncoding="UTF-8"%>
<!--CRLF-->
< %@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!--CRLF-->
< %
<!--CRLF-->
String path = request.getContextPath ();
<!--CRLF-->
String basePath = request.getScheme ()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
<!--CRLF-->
%>
<!--CRLF-->
<!--CRLF-->
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--CRLF-->
< html >
<!--CRLF-->
< head >
<!--CRLF-->
< base href="< %=basePath%> ">
<!--CRLF-->
<!--CRLF-->
< title > all Account Result< /title >
<!--CRLF-->
<!--CRLF-->
< meta http-equiv="pragma" content ="no-cache">
<!--CRLF-->
< meta http-equiv="cache-control" content ="no-cache">
<!--CRLF-->
< meta http-equiv="expires" content ="0">
<!--CRLF-->
< meta http-equiv="keywords" content ="keyword1,keyword2,keyword3">
<!--CRLF-->
< meta http-equiv="description" content ="This is my page">
<!--CRLF-->
< /head >
<!--CRLF-->
<!--CRLF-->
< body >
<!--CRLF-->
< c:forEach items="${list}" var ="data">
<!--CRLF-->
id: ${data.accountId }---name: ${data.username }---password: ${data.password }< hr />
<!--CRLF-->
< /c:forEach>
<!--CRLF-->
< /body >
<!--CRLF-->
< /html >
<!--CRLF-->
show.jsp
< %@ page language="java" import="java.util .*" pageEncoding="UTF-8"%>
<!--CRLF-->
< %
<!--CRLF-->
String path = request.getContextPath ();
<!--CRLF-->
String basePath = request.getScheme ()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
<!--CRLF-->
%>
<!--CRLF-->
<!--CRLF-->
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--CRLF-->
< html >
<!--CRLF-->
< head >
<!--CRLF-->
< base href="< %=basePath%> ">
<!--CRLF-->
<!--CRLF-->
< title > show Account< /title >
<!--CRLF-->
<!--CRLF-->
< meta http-equiv="pragma" content ="no-cache">
<!--CRLF-->
< meta http-equiv="cache-control" content ="no-cache">
<!--CRLF-->
< meta http-equiv="expires" content ="0">
<!--CRLF-->
< meta http-equiv="keywords" content ="keyword1,keyword2,keyword3">
<!--CRLF-->
< meta http-equiv="description" content ="This is my page">
<!--CRLF-->
< /head >
<!--CRLF-->
<!--CRLF-->
< body >
<!--CRLF-->
${account }< br />
<!--CRLF-->
${account.username }#${account.accountId }
<!--CRLF-->
< /body >
<!--CRLF-->
< /html >
<!--CRLF-->
<!--CRLF-->
error.jsp
< %@ page language="java" import="java.util .*" pageEncoding="UTF-8"%>
<!--CRLF-->
< %
<!--CRLF-->
String path = request.getContextPath ();
<!--CRLF-->
String basePath = request.getScheme ()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
<!--CRLF-->
%>
<!--CRLF-->
<!--CRLF-->
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!--CRLF-->
< html >
<!--CRLF-->
< head >
<!--CRLF-->
< base href="< %=basePath%> ">
<!--CRLF-->
<!--CRLF-->
< title > Error Page< /title >
<!--CRLF-->
<!--CRLF-->
< meta http-equiv="pragma" content ="no-cache">
<!--CRLF-->
< meta http-equiv="cache-control" content ="no-cache">
<!--CRLF-->
< meta http-equiv="expires" content ="0">
<!--CRLF-->
< meta http-equiv="keywords" content ="keyword1,keyword2,keyword3">
<!--CRLF-->
< meta http-equiv="description" content ="This is my page">
<!--CRLF-->
< /head >
<!--CRLF-->
<!--CRLF-->
< body >
<!--CRLF-->
< H2> Exception: ${exception }< /H2>
<!--CRLF-->
< a href="javascript:document.getElementById ('show').style .display = 'block'; void(0);">
<!--CRLF-->
详细信息
<!--CRLF-->
< /a>
<!--CRLF-->
< div id="show" style ="color : red; display : none; ">
<!--CRLF-->
< % Exception ex = (Exception)request.getAttribute ("exception"); %>
<!--CRLF-->
<!--CRLF-->
< % ex.printStackTrace (new java.io .PrintWriter (out)); %>
<!--CRLF-->
< /div >
<!--CRLF-->
< /body >
<!--CRLF-->
< /html >
<!--CRLF-->
16、 以上就基本上完成了整个Spring+SpringMVC+MyBatis的整合了。如果你想添加事务管理,得在applicationContext-common.xml中加入如下配置:
<!-- 配置事务管理器,注意这里的dataSource和SqlSessionFactoryBean的dataSource要一致,不然事务就没有作用了 -->
<!--CRLF-->
< bean id ="transactionManager" class ="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<!--CRLF-->
< property name ="dataSource" ref ="dataSource" />
<!--CRLF-->
<!--< span-->bean >
<!--CRLF-->
同时还需要加入aspectjweaver.jar这个jar包;
注意的是:Jdbc的TransactionManager不支持事务隔离级别,我在整个地方加入其它的TransactionManager,增加对transaction的隔离级别都尝试失败!
也许可以用于jpa、jdo、jta这方面的东西。不知道大家对MyBatis的事务是怎么处理的?
17、 对Dao进行扩展封装,运用SqlSessionDaoSupport进行模板的扩展或运用:
BaseDao代码如下:
package com.hoo.dao.impl;
<!--CRLF-->
<!--CRLF-->
import java.util.ArrayList;
<!--CRLF-->
import java.util.List;
<!--CRLF-->
import javax.inject.Inject;
<!--CRLF-->
import org.apache.ibatis.session.SqlSessionFactory;
<!--CRLF-->
import org.mybatis.spring.support.SqlSessionDaoSupport;
<!--CRLF-->
import org.springframework.stereotype.Repository;
<!--CRLF-->
import com.hoo.dao.BaseDao;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: 运用SqlSessionDaoSupport封装Dao常用增删改方法,可以进行扩展
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-13 下午06:33:37
<!--CRLF-->
* @file BaseDaoImpl.java
<!--CRLF-->
* @package com.hoo.dao.impl
<!--CRLF-->
* @project MyBatisForSpring
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email hoojo_@126.com
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
@Repository
<!--CRLF-->
@SuppressWarnings({ "unchecked" , "unused" })
<!--CRLF-->
public class BaseDaoImplextends Object> extends SqlSessionDaoSupport implements BaseDao {
<!--CRLF-->
<!--CRLF-->
@Inject
<!--CRLF-->
private SqlSessionFactory sqlSessionFactory;
<!--CRLF-->
<!--CRLF-->
public boolean add(String classMethod, T entity) throws Exception {
<!--CRLF-->
boolean flag = false;
<!--CRLF-->
try {
<!--CRLF-->
flag = this .getSqlSession().insert(classMethod, entity) > 0 ? true : false;
<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
flag = false;
<!--CRLF-->
throw e;
<!--CRLF-->
}
<!--CRLF-->
return flag;
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public boolean edit(String classMethod, T entity) throws Exception {
<!--CRLF-->
boolean flag = false;
<!--CRLF-->
try {
<!--CRLF-->
flag = this .getSqlSession().update(classMethod, entity) > 0 ? true : false;
<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
flag = false;
<!--CRLF-->
throw e;
<!--CRLF-->
}
<!--CRLF-->
return flag;
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public T get(String classMethod, T entity) throws Exception {
<!--CRLF-->
T result = null;
<!--CRLF-->
try {
<!--CRLF-->
result = (T) this .getSqlSession().selectOne(classMethod, entity);
<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
throw e;
<!--CRLF-->
}
<!--CRLF-->
return result;
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public List getAll(String classMethod) throws Exception {
<!--CRLF-->
List result = new ArrayList();
<!--CRLF-->
try {
<!--CRLF-->
result = this .getSqlSession().selectList(classMethod);
<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
throw e;
<!--CRLF-->
}
<!--CRLF-->
return result;
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public boolean remove(String classMethod, T entity) throws Exception {
<!--CRLF-->
boolean flag = false;
<!--CRLF-->
try {
<!--CRLF-->
flag = this .getSqlSession().delete(classMethod, entity) > 0 ? true : false;
<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
flag = false;
<!--CRLF-->
throw e;
<!--CRLF-->
}
<!--CRLF-->
return flag;
<!--CRLF-->
}
<!--CRLF-->
}
<!--CRLF-->
值得说明的是,这个类继承了SqlSessionDaoSupport,它需要我们帮助它注入SqlSessionFactory或是SqlSessionTemplate,如果两者都被注入将忽略SqlSessionFactory属性,使用SqlSessionTemplate模板。
继承SqlSessionDaoSupport后,可以拿到SqlSession完成数据库的操作;
18、 对Dao进行扩展封装,运用SqlSessionTemplate进行模板的扩展或运用:
首先看看这个组件中运用的一个Mapper的基类接口:
package com.hoo.mapper;
<!--CRLF-->
<!--CRLF-->
import java.util.List;
<!--CRLF-->
import org.springframework.dao.DataAccessException;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: BaseSqlMapper继承SqlMapper,对Mapper进行接口封装,提供常用的增删改查组件;
<!--CRLF-->
* 也可以对该接口进行扩展和封装
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-14 上午11:36:41
<!--CRLF-->
* @file BaseSqlMapper.java
<!--CRLF-->
* @package com.hoo.mapper
<!--CRLF-->
* @project MyBatisForSpring
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email hoojo_@126.com
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
public interface BaseSqlMapper extends SqlMapper {
<!--CRLF-->
<!--CRLF-->
public void add(T entity) throws DataAccessException;
<!--CRLF-->
<!--CRLF-->
public void edit(T entity) throws DataAccessException;
<!--CRLF-->
<!--CRLF-->
public void remvoe(T entity) throws DataAccessException;
<!--CRLF-->
<!--CRLF-->
public T get(T entity) throws DataAccessException;
<!--CRLF-->
<!--CRLF-->
public List getList(T entity) throws DataAccessException;
<!--CRLF-->
}
<!--CRLF-->
该接口继承SqlMapper接口,但是该接口没有MyBatis的mapper实现。需要我们自己的业务mapper继承这个接口,完成上面的方法的实现。
看看继承SqlSessionTemplate的BaseMapperDao代码:
package com.hoo.dao.impl;
<!--CRLF-->
<!--CRLF-->
import java.util.List;
<!--CRLF-->
import javax.inject.Inject;
<!--CRLF-->
import org.apache.ibatis.session.SqlSessionFactory;
<!--CRLF-->
import org.mybatis.spring.SqlSessionTemplate;
<!--CRLF-->
import org.springframework.stereotype.Repository;
<!--CRLF-->
import com.hoo.dao.BaseMapperDao;
<!--CRLF-->
import com.hoo.mapper.BaseSqlMapper;
<!--CRLF-->
<!--CRLF-->
/**
<!--CRLF-->
* function: 运用SqlSessionTemplate封装Dao常用增删改方法,可以进行扩展
<!--CRLF-->
* @author hoojo
<!--CRLF-->
* @createDate 2011-4-14 下午12:22:07
<!--CRLF-->
* @file BaseMapperDaoImpl.java
<!--CRLF-->
* @package com.hoo.dao.impl
<!--CRLF-->
* @project MyBatisForSpring
<!--CRLF-->
* @blog http://blog.csdn.net/IBM_hoojo
<!--CRLF-->
* @email hoojo_@126.com
<!--CRLF-->
* @version 1.0
<!--CRLF-->
*/
<!--CRLF-->
@SuppressWarnings("unchecked" )
<!--CRLF-->
@Repository
<!--CRLF-->
public class BaseMapperDaoImpl extends SqlSessionTemplate implements BaseMapperDao {
<!--CRLF-->
<!--CRLF-->
@Inject
<!--CRLF-->
public BaseMapperDaoImpl(SqlSessionFactory sqlSessionFactory) {
<!--CRLF-->
super (sqlSessionFactory);
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
private Class<!--? <span style="color: #0000ff"-->extends BaseSqlMapper> mapperClass;
<!--CRLF-->
<!--CRLF-->
public void setMapperClass(Class<!--? <span style="color: #0000ff"-->extends BaseSqlMapper> mapperClass) {
<!--CRLF-->
this .mapperClass = mapperClass;
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
private BaseSqlMapper getMapper() {
<!--CRLF-->
return this .getMapper(mapperClass);
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public boolean add(T entity) throws Exception {
<!--CRLF-->
boolean flag = false;
<!--CRLF-->
try {
<!--CRLF-->
this .getMapper().add(entity);
<!--CRLF-->
flag = true;
<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
flag = false;
<!--CRLF-->
throw e;
<!--CRLF-->
}
<!--CRLF-->
return flag;
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public boolean edit(T entity) throws Exception {
<!--CRLF-->
boolean flag = false;
<!--CRLF-->
try {
<!--CRLF-->
this .getMapper().edit(entity);
<!--CRLF-->
flag = true;
<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
flag = false;
<!--CRLF-->
throw e;
<!--CRLF-->
}
<!--CRLF-->
return flag;
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public T get(T entity) throws Exception {
<!--CRLF-->
return this .getMapper().get(entity);
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public List getAll() throws Exception {
<!--CRLF-->
return this .getMapper().getList(null);
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public boolean remove(T entity) throws Exception {
<!--CRLF-->
boolean flag = false;
<!--CRLF-->
try {
<!--CRLF-->
this .getMapper().remvoe(entity);
<!--CRLF-->
flag = true;
<!--CRLF-->
} catch (Exception e) {
<!--CRLF-->
flag = false;
<!--CRLF-->
throw e;
<!--CRLF-->
}
<!--CRLF-->
return flag;
<!--CRLF-->
}
<!--CRLF-->
}
<!--CRLF-->
上面这个类继承了SqlSessionTemplate,这个类需要提供一个构造函数。这里提供的是SqlSessionFactory的构造函数,通过该函数注入SqlSessionFactory即可完成数据库操作;
例外的是这个类还有一个关键属性mapperClass,这个class需要是BaseSqlMapper接口或是子接口,然后通过SqlSessionTemplate模板获得当前设置的Class的Mapper对象,完成数据库操作。
该类的测试代码:
@ContextConfiguration("classpath:applicationContext-*.xml" )
<!--CRLF-->
public class BaseMapperDaoImplTest extends AbstractJUnit38SpringContextTests {
<!--CRLF-->
<!--CRLF-->
@Inject
<!--CRLF-->
private BaseMapperDao dao;
<!--CRLF-->
<!--CRLF-->
public void init() {
<!--CRLF-->
dao.setMapperClass(CompanyMapper.class );
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public void testGet() throws Exception {
<!--CRLF-->
init();
<!--CRLF-->
Company c = new Company();
<!--CRLF-->
c.setCompanyId(4);
<!--CRLF-->
System.out.println(dao.get(c));
<!--CRLF-->
}
<!--CRLF-->
<!--CRLF-->
public void testAdd() throws Exception {
<!--CRLF-->
init();
<!--CRLF-->
Company c = new Company();
<!--CRLF-->
c.setAddress("北京中关村" );
<!--CRLF-->
c.setName("beijin" );
<!--CRLF-->
System.out.println(dao.add(c));
<!--CRLF-->
}
<!--CRLF-->
}
<!--CRLF-->
一般情况下,你可以在一个Dao中注入BaseMapperDao,紧跟着需要设置MapperClass。只有设置了MapperClass后,BaseMapperDao才能获取对应mapper,完成相关的数据库操作。当然你可以在这个Dao中将SqlSessionTemplate、SqlSession暴露出来,当BaseMapperDao的方法不够用,可以进行扩展
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com