SpringMvc+mybatis if test true框架 从控制器调用方法没抛异常返回true,update的语句能放到数据库 执行

&首先在整合这个框架的时候,想想其一般的步骤是怎样的,先有个步骤之后,不至于在后面的搞混了,这样在整合的时候也比较清晰些。
然后我们就细细的一步一步来整合。
1 &创建一个Web项目。
2 &导入Mybatis3、Spring4、SpringMVC4、连接数据库(我使用的数据库是mysql)的jar包。
&我所用的包:
&spring-websocket-4.2.0.RELEASE.jar
3 &创建Mybatis3、Spring4、SpringMVC4、连接数据库的配置文件。
4 &配置web.xml&
1 &?xml version="1.0" encoding="UTF-8"?&
2 &web-app version="2.5"
xmlns="/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="/xml/ns/javaee
/xml/ns/javaee/web-app_2_5.xsd"&
&!-- 告知javaEE容器,有哪些内容需要添加到上下文中去 --&
&context-param&
&param-name&contextConfigLocation&/param-name&
&param-value&
/WEB-INF/classes/applicationContext.xml,
&!-- /WEB-INF/classes/mvc-servlet.xml --&
&/param-value&
&/context-param&
&!-- 加载LOG4J --&
&context-param&
&param-name&log4jConfigLocation&/param-name&
&param-value&/WEB-INF/log4j.xml&/param-value&
&/context-param&
&context-param&
&param-name&log4jRefreshInterval&/param-name&
&param-value&60000&/param-value&
&/context-param&
&!-- 动态设置项目的运行路径 --&
&context-param&
&param-name&webAppRootKey&/param-name&
&param-value&ssm.root&/param-value&
&/context-param&
&!-- 配置静态资源 --&
&servlet-mapping&
&servlet-name&default&/servlet-name&
&url-pattern&/static/*&/url-pattern&
&/servlet-mapping&
&!-- 配置springmvc的前端控制器 --&
&servlet-name&mvc&/servlet-name&
&servlet-class&org.springframework.web.servlet.DispatcherServlet&/servlet-class&
&!-- 默认情况下:DispatcherServlet会寻找WEB-INF下,命名规范为[servlet-name]-servlet.xml文件。如:在上例中,它就会找/WEB-INF/spring-servlet.xml
如果需要修改,需要在web.xml中的&servlet&标记中增加 &init-param&。。。
&/init-param&:--&
&init-param&
&param-name&contextConfigLocation&/param-name&
&param-value&/WEB-INF/classes/mvc-servlet.xml&/param-value&
&/init-param&
&/servlet&
&servlet-mapping&
&servlet-name&mvc&/servlet-name&
&url-pattern&/&/url-pattern&
&/servlet-mapping&
&!-- spring框架提供的字符集过滤器 --&
&!-- spring Web MVC框架提供了org.springframework.web.filter.CharacterEncodingFilter用于解决POST方式造成的中文乱码问题
&filter-name&encodingFilter&/filter-name&
&filter-class&org.springframework.web.filter.CharacterEncodingFilter&/filter-class&
&init-param&
&param-name&encoding&/param-name&
&param-value&UTF-8&/param-value&
&/init-param&
&!-- force强制,促使 --&
&init-param&
&param-name&forceEncoding&/param-name&
&param-value&true&/param-value&
&/init-param&
&filter-mapping&
&filter-name&encodingFilter&/filter-name&
&url-pattern&/*&/url-pattern&
&/filter-mapping&
&!-- 登录过滤器--&
&filter-name&loginFilter&/filter-name&
&filter-class&com.cy.ssm.filter.LoginFilter&/filter-class&
&filter-mapping&
&filter-name&loginFilter&/filter-name&
&url-pattern&/*&/url-pattern&
&/filter-mapping&
&!-- 监听器 --&
&listener&
&listener-class&org.springframework.web.context.ContextLoaderListener&/listener-class&
&/listener&
&listener&
&listener-class&org.springframework.web.util.Log4jConfigListener&/listener-class&
&/listener&
&welcome-file-list&
&welcome-file&index.jsp&/welcome-file&
&/welcome-file-list&
99 &/web-app&
5&datasource.properties 连接数据库
1 jdbc.driver=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8
3 jdbc.username=root
4 jdbc.password=root
6 mybatis.cfg.xml文件
&?xml version="1.0" encoding="UTF-8"?&
&!DOCTYPE configuration PUBLIC "-//mybatis.org/DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd" &
&configuration&
&/configuration&
7 &mvc-servlet.xml
1 &?xml version="1.0" encoding="UTF-8"?&
2 &beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
6 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
7 http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
8 http://www.springframework.org/schema/mvc
9 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"&
&!-- 启动注解,注册服务,如验证框架、全局类型转换器--&
&mvc:annotation-driven/&
&!-- 启动自动扫描 --&
&context:component-scan base-package="com.cy.ssm"&
&!-- 制定扫包规则 ,只扫描使用@Controller注解的JAVA类 --&
&context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/&
&/context:component-scan&
&!-- 配置视图解析器 --&
prefix和suffix:查找视图页面的前缀和后缀(前缀[逻辑视图名]后缀),
比如传进来的逻辑视图名为WEB-INF/jsp/hello,则该该jsp视图页面应该存放在&WEB-INF/jsp/hello.jsp&; --&
&bean class="org.springframework.web.servlet.view.UrlBasedViewResolver"&
&property name="viewClass" value="org.springframework.web.servlet.view.JstlView"&&/property&
&property name="prefix" value="/"&&/property& &!-- 我这里的视图直接放在WebRoot下的 --&
&property name="suffix" value=".jsp"&&/property&
31 &/beans&
&8 applicationContext.xml
1 &?xml version="1.0" encoding="UTF-8"?&
2 &beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd"&
&!-- 开启自动扫包 --&
&context:component-scan base-package="com.cy.ssm"&
&!--制定扫包规则,不扫描@Controller注解的JAVA类,其他的还是要扫描
&context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/&
&/context:component-scan&
&!-- 启动AOP支持 --&
&aop:aspectj-autoproxy/&
&!-- 引入外部数据源配置信息 --&
&bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&
&property name="locations"&
&value&classpath:datasource.properties&/value&
&/property&
&!-- 配置数据源 --&
&bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&
&property name="driverClassName" value="${jdbc.driver}"&&/property&
&property name="url" value="${jdbc.url}"&&/property&
&property name="username" value="${jdbc.username}"&&/property&
&property name="password" value="${jdbc.password}"&&/property&
&!-- 配置Session工厂 --&
&bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"&
&property name="dataSource" ref="dataSource"&&/property&
&!-- 加载mybatis.cfg.xml文件 --&
&property name="configLocation" value="classpath:mybatis.cfg.xml"&&/property&
&!-- 自动扫描需要定义类别名的包,将包内的JAVA类的类名作为类别名 --&
&property name="typeAliasesPackage" value="com.cy.ssm.beans"&&/property&
&!-- 自动扫描所有的Mapper接口与文件 --&
&bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"&
&property name="basePackage" value="com.cy.ssm.mapper"&&/property&
&!-- 配置事务管理器 --&
&bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&
&property name="dataSource" ref="dataSource"&&/property&
&!-- 定义个通知,指定事务管理器 --&
&tx:advice id="txAdvice" transaction-manager="txManager"&
&tx:attributes&
&tx:method name="delete*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" /&
&tx:method name="save*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" /&
&tx:method name="insert*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" /&
&tx:method name="update*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" /&
&tx:method name="load*" propagation="SUPPORTS" read-only="true"/&
&tx:method name="find*" propagation="SUPPORTS" read-only="true"/&
&tx:method name="search*" propagation="SUPPORTS" read-only="true"/&
&tx:method name="select*" propagation="SUPPORTS" read-only="true"/&
&tx:method name="get*" propagation="SUPPORTS" read-only="true"/&
&/tx:attributes&
&/tx:advice&
&aop:config&
&!-- 配置一个切入点 --&
&aop:pointcut id="serviceMethods" expression="execution(* com.cy.ssm.service.impl.*ServiceImpl.*(..))" /&
&aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" /&
&/aop:config&
85 &/beans&
&9 &配置文件都差不多配置好了,接下来就写个测试的。
&UserBean.java
1 package com.cy.ssm.
3 import java.io.S
5 public class UserBean implements Serializable {
private static final long serialVersionUID = -0221059L;
public UserBean() {
// TODO Auto-generated constructor stub
public UserBean(Integer id, String username, String password, Double account) {
this.username =
this.password =
this.account =
public Integer getId() {
public void setId(Integer id) {
public String getUsername() {
public void setUsername(String username) {
this.username =
public String getPassword() {
public void setPassword(String password) {
this.password =
public Double getAccount() {
public void setAccount(Double account) {
this.account =
public String toString() {
return "UserBean [account=" + account + ", id=" + id + ", password="
+ password + ", username=" + username + "]";
&UserMapper.java
1 package com.cy.ssm.
3 import java.util.L
4 import java.util.M
7 import org.apache.ibatis.annotations.D
8 import org.apache.ibatis.annotations.I
9 import org.apache.ibatis.annotations.O
10 import org.apache.ibatis.annotations.P
11 import org.apache.ibatis.annotations.R
12 import org.apache.ibatis.annotations.ResultM
13 import org.apache.ibatis.annotations.R
14 import org.apache.ibatis.annotations.S
15 import org.apache.ibatis.annotations.U
17 import com.cy.ssm.beans.UserB
20 public interface UserMapper {
* @param userName
* @param password
* @throws Exception
@Select("select * from t_user where username=#{un} and password=#{pw}")
@Results({
@Result(id=true,property="id",column="id",javaType=Integer.class),
@Result(property="username",column="username",javaType=String.class),
@Result(property="password",column="password",javaType=String.class),
@Result(property="account",column="account",javaType=Double.class)
public UserBean login(@Param("un")String username,@Param("pw")String password);
* 新增用戶
* @param user
* @throws Exception
@Insert("insert into t_user value (null,user.username,user.password,user.account)")
@Options(useGeneratedKeys=true,keyProperty="user.id")
public int insertUser(@Param("user")UserBean user) throws E
* 修改用戶
* @param user
* @param id
* @throws Exception
@Update(" update t_user set username=#{u.username},password=#{u.password},account=#{u.account} where id=#{id}")
public int updateUser (@Param("u")UserBean user,@Param("id")int id) throws E
* 刪除用戶
* @param id
* @throws Exception
@Delete(" delete from t_user where id=#{id}
public int deleteUser(int id) throws E
* 根据id查询用户信息
* @param id
* @throws Exception
@Select(" select * from t_user where id=#{id}")
@Results({
@Result(id=true,property="id",column="id",javaType=Integer.class),
@Result(property="username",column="username",javaType=String.class),
@Result(property="password",column="password",javaType=String.class),
@Result(property="account",column="account",javaType=Double.class)
public UserBean selectUserById(int id) throws E
* 查询所有的用户信息
* @throws Exception
@Select(" select * from t_user")
@ResultMap("userMap")
public List&UserBean& selectAllUser() throws E
* 批量增加
* @param user
* @throws Exception
public int batchInsertUser(@Param("users")List&UserBean& user) throws E
* 批量删除
* @param list
* @throws Exception
public int batchDeleteUser(@Param("list")List&Integer& list) throws E
* 分页查询数据
* @param parma
* @throws Exception
public List&UserBean& pagerUser(Map&String, Object& parmas) throws E
* 分页统计数据
* @param parma
* @throws Exception
public int countUser(Map&String, Object& parmas) throws E
UserMapper.xml
1 &?xml version="1.0" encoding="UTF-8"?&
2 &!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"&
3 &mapper namespace="com.cy.ssm.mapper.UserMapper"&
4 &!-- 自定义返回结果集 --&
&resultMap id="userMap" type="UserBean"&
&id property="id" column="id" javaType="java.lang.Integer"&&/id&
&result property="username" column="username" javaType="java.lang.String"&&/result&
&result property="password" column="password" javaType="java.lang.String"&&/result&
&result property="account" column="account" javaType="java.lang.Double"&&/result&
&/resultMap&
&!-- 批量操作和foreach标签 --&
&insert id="batchInsertUser" parameterType="java.util.List"&
insert into t_user values
&foreach collection="users" item="users" separator=","&
(null,#{users.username},#{users.password},#{users.account})
&/foreach&
&delete id="batchDeleteUser"&
delete from t_user where id in (
&foreach collection="list" item="list" separator=","&
&/foreach&
&!--collection 为用于遍历的元素(必选),支持数组、List、Set
&!-- item 表示集合中每一个元素进行迭代时的别名. --&
&!--separator表示在每次进行迭代之间以什么符号作为分隔 符.
&!--#在生成SQL时,对于字符类型参数,会拼装引号
$在生成SQL时,不会拼装引号,可用于order by之类的参数拼装
&select id="pagerUser" parameterType="java.util.Map" resultMap="userMap"&
select * from t_user where 1=1
&if test="username!=null"&
and username like '%${username}%'
limit ${index},${pageSize}
&select id="countUser" parameterType="java.util.Map" resultType="int"&
select count(*) from t_user where 1=1
&if test="username != null"&
and username like '%${username}%'
52 &/mapper&
ILoginService.java
1 package com.cy.ssm.
4 import com.cy.ssm.beans.UserB
6 public interface ILoginService {
public UserBean Login(String username,String password);
LoginServiceImpl.java
1 package com.cy.ssm.service.
3 import javax.annotation.R
5 import org.springframework.stereotype.S
7 import com.cy.ssm.mapper.UserM
8 import com.cy.ssm.beans.UserB
9 import com.cy.ssm.service.ILoginS
10 @Service
11 public class LoginServiceImpl implements ILoginService{
private UserM
public UserBean Login(String username, String password) {
return um.login(username, password);
LoginController .java
1 package com.cy.ssm.
4 import javax.annotation.R
5 import javax.servlet.http.HttpServletR
7 import org.apache.log4j.L
8 import org.springframework.stereotype.C
9 import org.springframework.web.bind.annotation.RequestM
10 import org.springframework.web.servlet.ModelAndV
12 import com.cy.ssm.beans.UserB
13 import com.cy.ssm.service.ILoginS
17 @Controller
18 public class LoginController {
private Logger log = Logger.getLogger(this.getClass());
private ILoginService loginServiceI
@RequestMapping("/login")
public ModelAndView login(HttpServletRequest req,UserBean user){
ModelAndView mv = new ModelAndView();
UserBean u=loginServiceImpl.Login(user.getUsername(), user.getPassword());
if(u != null){
req.getSession().setAttribute("user", u);
mv.addObject("password", u.getPassword());
System.out.println(u.getPassword());
mv.setViewName("index");
&jsp页面;
&form action="&%=basePath%&login" method="post"&
&input type="text" name="username"/&
&input type="text" name="password"/&
&input type="submit" value="提交"/&
&index.jsp
&body&& &${password }
整体大概就这样了!
我把整个文件上传到:
继续我的作业了!
阅读(...) 评论()springmvc调整mybatis,mysql - MySQL当前位置:& &&&springmvc调整mybatis,mysqlspringmvc调整mybatis,mysql&&网友分享于:&&浏览:589次springmvc整合mybatis,mysql
开发环境:
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_@
1、 首先新建一个WebProject 命名为MyBatisForSpring,新建项目时,使用JavaEE5的lib库。然后手动添加需要的jar包,所需jar包如下:
2、 添加spring的监听及springMVC的核心Servlet,web.xml内容,内容如下:
&-- 加载Spring容器配置 --&
&listener&
&listener-class&org.springframework.web.context.ContextLoaderListenerlistener-class&
&-- 设置Spring容器加载配置文件路径 --&
&context-param&
&param-name&contextConfigLocationparam-name&
&param-value&classpath*:applicationContext-*.xmlparam-value&
context-param&
&-- 配置Spring核心控制器 --&
&servlet-name&dispatcherservlet-name&
&servlet-class&org.springframework.web.servlet.DispatcherServletservlet-class&
&init-param&
&param-name&contextConfigLocationparam-name&
&param-value&/WEB-INF/dispatcher.xmlparam-value&
init-param&
&load-on-startup&1load-on-startup&
&servlet-mapping&
&servlet-name&dispatcherservlet-name&
&url-pattern&*.dourl-pattern&
servlet-mapping&
&-- 解决工程编码过滤器 --&
&filter-name&characterEncodingFilterfilter-name&
&filter-class&org.springframework.web.filter.CharacterEncodingFilterfilter-class&
&init-param&
&param-name&encodingparam-name&
&param-value&UTF-8param-value&
init-param&
&filter-mapping&
&filter-name&characterEncodingFilterfilter-name&
&url-pattern&/*url-pattern&
filter-mapping&
3、 在WEB-INF目录中添加dispatcher.xml,内容如下:
xml version="1.0" encoding="UTF-8"?&
&beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"&
&-- 注解探测器 --&
&context:component-scan base-package="com.hoo"/&
annotation默认的方法映射适配器 --&
&bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /&
&bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /&
4、 在src目录下添加applicationContext-common.xml,内容如下:
xml version="1.0" encoding="UTF-8"?&
&beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "&
&-- 配置DataSource数据源 --&
&bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&
&property name="driverClassName" value="com.mysql.jdbc.Driver"/&
&property name="url" value="jdbc:mysql://10.0.0.131:3306/ash2"/&
&property name="username" value="dev"/&
&property name="password" value="dev"/&
&-- 配置SqlSessionFactoryBean --&
&bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"&
&property name="dataSource" ref="dataSource"/&
&property name="configLocation" value="classpath:mybatis.xml"/&
&-- mapper和resultmap配置路径 --&
&property name="mapperLocations"&
&-- 表示在com.hoo.resultmap包或以下所有目录中,以-resultmap.xml结尾所有文件 --&
&value&classpath:com/hoo/resultmap/**/*-resultmap.xmlvalue&
&value&classpath:com/hoo/entity/*-resultmap.xmlvalue&
&value&classpath:com/hoo/mapper/**/*-mapper.xmlvalue&
&-- 单独配置一个Mapper; 这种模式就是得给每个mapper接口配置一个bean --&
&bean id="accountMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"&
&property name="mapperInterface" value="com.hoo.mapper.AccountMapper" /&
&property name="sqlSessionFactory" ref="sqlSessionFactory" /&
&bean id="companyMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"&
&property name="mapperInterface" value="com.panyMapper" /&
&property name="sqlSessionFactory" ref="sqlSessionFactory" /&
&-- 通过扫描的模式,扫描目录在com/hoo/mapper目录下,所有的mapper都继承SqlMapper接口的接口, 这样一个bean就可以了 --&
&bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"&
&property name="basePackage" value="com.hoo.mapper"/&
&property name="markerInterface" value="com.hoo.mapper.SqlMapper"/&
上面的配置最先配置的是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.
* function:所有的Mapper继承这个接口
* @author hoojo
* @createDate
下午04:00:31
* @file SqlMapper.java
* @package com.hoo.mapper
* @project MyBatisForSpring
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@
* @version 1.0
public interface SqlMapper {
6、 实体类和ResultMap.xml
package com.hoo.
import java.io.S
import javax.persistence.E
public class Account implements Serializable {
private static final long serialVersionUID = -4840509L;
private Integer accountId;
private Integer roleId;
//getter、setter
public String toString() {
return this.accountId + "#" + this.status + "#" + this.username +
this.password +
"#" + this.email +
"#" + this.salt + "#" + this.roleId;
account-resultmap.xml
xml version="1.0" encoding="UTF-8"?&
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"&
&mapper namespace="accountMap"&
&resultMap type="com.hoo.entity.Account" id="accountResultMap"&
&id property="accountId" column="account_id"/&
&result property="username" column="username"/&
&result property="password" column="password"/&
&result property="status" column="status"/&
resultMap&
7、 在src目录中添加applicationContext-beans.xml内容如下:
xml version="1.0" encoding="UTF-8"?&
&beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"&
&-- 注解探测器 , 在JUnit测试的时候需要--&
&context:component-scan base-package="com.hoo"/&
这里配置bean对象,一些不能用annotation注解的对象就可以配置在这里
8、 在src目录中添加mybatis.xml,内容如下:
xml version="1.0" encoding="UTF-8" ?&
DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"&
&configuration&
&-- 别名 --&
&typeAliases&
&typeAlias type="com.hoo.entity.Account" alias="account"/&
typeAliases&
configuration&
在这个文件放置一些全局性的配置,如handler、objectFactory、plugin、以及mappers的映射路径(由于在applicationContext-common中的SqlSessionFactoryBean有配置mapper的location,这里就不需要配置)等
9、 AccountMapper接口,内容如下:
package com.hoo.
import java.util.L
import org.apache.ibatis.annotations.S
import com.hoo.entity.A
* function:继承SqlMapper,MyBatis数据操作接口;此接口无需实现类
* @author hoojo
* @createDate
下午05:21:20
* @file AccountMapper.java
* @package com.hoo.mapper
* @project MyBatis
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@
* @version 1.0
public interface AccountMapper extends SqlMapper {
public List getAllAccount();
public Account getAccount();
public Account getAccountById(String id);
public Account getAccountByNames(String spring);
@Select("select * from account where username = #{name}")
public Account getAccountByName(String name);
public void addAccount(Account account);
public void editAccount(Account account);
public void removeAccount(int id);
这个接口我们不需要实现,由mybatis帮助我们实现,我们通过mapper文件配置sql语句即可完成接口的实现。然后这个接口需要继承SqlMapper接口,不然在其他地方就不能从Spring容器中拿到这个mapper接口,也就是说当我们注入这个接口的时候将会失败。
当然,你不继承这个接口也可以。那就是你需要给买个mapper配置一个bean。配置方法如下:
&bean id="accountMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"&
&property name="mapperInterface" value="com.hoo.mapper.AccountMapper" /&
&property name="sqlSessionFactory" ref="sqlSessionFactory" /&
这里的MapperFactoryBean可以帮助我们完成Session的打开、关闭等操作
10、 在com.hoo.mapper也就是在AccountMapper接口的同一个包下,添加account-mapper.xml,内容如下:
xml version="1.0" encoding="UTF-8"?&
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"&
&-- namespace和定义的Mapper接口对应,并实现其中的方法 --&
&mapper namespace="com.hoo.mapper.AccountMapper"&
&-- id和mapper接口中的方法名对应,resultType使用mybatis.xml中的别名 --&
&select id="getAccount" resultType="account"&
select * from account limit 1
&select id="getAllAccount" resultType="list" resultMap="accountResultMap"&
select * from account
&-- accountResultMap是account-resultmap.xml中定义的resultmap --&
&select id="getAccountById" parameterType="string" resultType="com.hoo.entity.Account" resultMap="accountResultMap"&
select * from account where account_id = #{id}
&-- accountMap.accountResultMap是account-resultmap.xml中定义的resultmap,通过namespace.id找到 --&
&select id="getAccountByNames" parameterType="string" resultMap="accountMap.accountResultMap"&
select * from account where username = #{name}
&sql id="user_name_pwd"&
username, password
&-- 自动生成id策略 --&
&insert id="addAccount" useGeneratedKeys="true" keyProperty="account_id" parameterType="account"&
insert into account(account_id, status, username, password)
values(#{accountId}, #{status}, #{username}, #{password})
&-- 根据selectKey语句生成主键 --&
&insert id="addAccount4Key" parameterType="account"&
&selectKey keyProperty="account_id" order="BEFORE" resultType="int"&
select cast(random() * 10000 as Integer) a from #Tab
selectKey&
insert into account(account_id, status, username, password)
values(#{accountId}, #{status}, #{username}, #{password})
&update id="editAccount" parameterType="account"&
update account set
status = #{status},
username = #{username},
password = #{password}
where account_id = #{accountId}
&delete id="removeAccount" parameterType="int"&
delete from account where account_id = #{id}
上面的namespace和定义接口类路径对应,所有的sql语句,如select、insert、delete、update的id和方法名称对应。关于更多MyBatis内容的讲解,这里就不赘述的。这里只完成整合!如果你不懂可以去阅读其他关于MyBatis的资料。
11、 为了测试发布,这里使用junit和spring官方提供的spring-test.jar,完成spring框架整合的测试,代码如下:
package com.hoo.
import java.util.L
import javax.inject.I
import org.springframework.test.context.ContextC
import org.springframework.test.context.junit38.AbstractJUnit38SpringContextT
import com.hoo.entity.A
* function: AccountMapper JUnit测试类
* @author hoojo
* @createDate
下午04:21:50
* @file AccountMapperTest.java
* @package com.hoo.mapper
* @project MyBatisForSpring
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@
* @version 1.0
@ContextConfiguration("classpath:applicationContext-*.xml")
public class AccountMapperTest extends AbstractJUnit38SpringContextTests {
//@Named("accountMapper")
private AccountM
public void testGetAccount() {
System.out.println(mapper.getAccount());
public void testGetAccountById() {
System.out.println(mapper.getAccountById("28"));
public void testGetAccountByName() {
System.out.println(mapper.getAccountByName("user"));
public void testGetAccountByNames() {
System.out.println(mapper.getAccountByNames("user"));
public void testAdd() {
Account account = new Account();
account.setEmail("");
account.setPassword("abc");
account.setRoleId(1);
account.setSalt("ss");
account.setStatus(0);
account.setUsername("Jack");
mapper.addAccount(account);
public void testEditAccount() {
Account acc = mapper.getAccountByNames("Jack");
System.out.println(acc);
acc.setUsername("Zhangsan");
acc.setPassword("123123");
mapper.editAccount(acc);
System.out.println(mapper.getAccountById(acc.getAccountId() + ""));
public void testRemoveAccount() {
Account acc = mapper.getAccountByNames("Jack");
mapper.removeAccount(acc.getAccountId());
System.out.println(mapper.getAccountByNames("Jack"));
public void testAccountList() {
List acc = mapper.getAllAccount();
System.out.println(acc.size());
System.out.println(acc);
这里的注入并没有使用@Autowired、@Resource、@Qualifier注入,而是使用@Inject、@Named注入方式,Inject注入是JSR330的标准注入方式;而不局限于某个产品,使用于多个产品的使用,推荐使用这种方式;运行后,没有发现问题,就可以继续后续的编码工作了。
12、 定义AccountDao接口及实现代码,代码如下:
package com.hoo.
import java.util.L
import org.springframework.dao.DataAccessE
* function: Account数据库操作dao接口
* @author hoojo
* @createDate
上午10:21:38
* @file AccountDao.java
* @package com.hoo.dao
* @project MyBatisForSpring
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@
* @version 1.0
public interface AccountDao {
* function: 添加Account对象信息
* @author hoojo
* @createDate
上午11:50:05
* @param entity Account
* @return boolean 是否成功
* @throws DataAccessException
public boolean addAccount(T entity) throws DataAccessE
* function: 根据id对到Account信息
* @author hoojo
* @createDate
上午11:50:45
* @param id 编号id
* @return Account
* @throws DataAccessException
public T getAccount(Integer id) throws DataAccessE
* function: 查询所有Account信息
* @author hoojo
* @createDate
上午11:51:45
* @param id 编号id
* @return Account
* @throws DataAccessException
public List getList() throws DataAccessE
package com.hoo.dao.
import java.util.L
import javax.inject.I
import org.springframework.dao.DataAccessE
import org.springframework.stereotype.R
import com.hoo.dao.AccountD
import com.hoo.entity.A
import com.hoo.mapper.AccountM
* function: Account数据库操作dao
* @author hoojo
* @createDate
上午10:25:02
* @file AccountDaoImpl.java
* @package com.hoo.dao.impl
* @project MyBatisForSpring
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@
* @version 1.0
@SuppressWarnings("unchecked")
@Repository
public class AccountDaoImplextends Account& implements AccountDao {
private AccountM
public boolean addAccount(T entity) throws DataAccessException {
boolean flag =
mapper.addAccount(entity);
} catch (DataAccessException e) {
public T getAccount(Integer id) throws DataAccessException {
T entity =
entity = (T) mapper.getAccountById(String.valueOf(id));
} catch (DataAccessException e) {
public List getList() throws DataAccessException {
return (List) mapper.getAllAccount();
13、 服务层AccountBiz接口及实现代码
package com.hoo.
import java.util.L
import org.springframework.dao.DataAccessE
* function: biz层Account接口
* @author hoojo
* @createDate
上午11:33:04
* @file AccountBiz.java
* @package com.hoo.biz
* @project MyBatisForSpring
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@
* @version 1.0
public interface AccountBiz {
* function: 添加Account对象信息
* @author hoojo
* @createDate
上午11:50:05
* @param entity Account
* @return boolean 是否成功
* @throws DataAccessException
public boolean addAccount(T entity) throws DataAccessE
* function: 根据id对到Account信息
* @author hoojo
* @createDate
上午11:50:45
* @param id 编号id
* @return Account
* @throws DataAccessException
public T getAccount(Integer id) throws DataAccessE
* function: 查询所有Account信息
* @author hoojo
* @createDate
上午11:51:45
* @param id 编号id
* @return Account
* @throws DataAccessException
public List getList() throws DataAccessE
实现代码:
package com.hoo.biz.
import java.util.L
import javax.inject.I
import org.springframework.dao.DataAccessE
import org.springframework.stereotype.S
import com.hoo.biz.AccountB
import com.hoo.dao.AccountD
import com.hoo.entity.A
import com.hoo.exception.BizE
* function: Account Biz接口实现
* @author hoojo
* @createDate
上午11:34:39
* @file AccountBizImpl.java
* @package com.hoo.biz.impl
* @project MyBatisForSpring
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@
* @version 1.0
//@Component
public class AccountBizImplextends Account& implements AccountBiz {
private AccountD
public boolean addAccount(T entity) throws DataAccessException {
if (entity == null) {
throw new BizException(Account.class.getName() + "对象参数信息为Empty!");
return dao.addAccount(entity);
public T getAccount(Integer id) throws DataAccessException {
return dao.getAccount(id);
public List getList() throws DataAccessException {
return dao.getList();
上面用到了一个自定义的异常信息,代码如下:
package com.hoo.
import org.springframework.dao.DataAccessE
* function:自定义Biz层异常信息
* @author hoojo
* @createDate
上午11:42:19
* @file BizException.java
* @package com.hoo.exception
* @project MyBatisForSpring
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@
* @version 1.0
public class BizException extends DataAccessException {
* @author Hoojo
private static final long serialVersionUID = 1L;
public BizException(String msg) {
super(msg);
public BizException(String msg, Throwable cause) {
super(msg, cause);
这里只是简单的继承,如果还有其他的异常业务或需求可以进行具体的实现
14、 springMVC的控制器,AccountController代码如下:
package com.hoo.
import javax.inject.I
import javax.servlet.http.HttpServletR
import org.springframework.stereotype.C
import org.springframework.ui.M
import org.springframework.web.bind.annotation.ExceptionH
import org.springframework.web.bind.annotation.RequestM
import com.hoo.biz.AccountB
import com.hoo.entity.A
* function: Account控制器
* @author hoojo
* @createDate
上午10:18:02
* @file AccountController.java
* @package com.hoo.controller
* @project MyBatisForSpring
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@
* @version 1.0
@Controller
@RequestMapping("/account")
public class AccountController {
private AccountB
@RequestMapping("/add")
public String add(Account acc) {
System.out.println(acc);
biz.addAccount(acc);
return "redirect:/account/list.do";
@RequestMapping("/get")
public String get(Integer id, Model model) {
System.out.println("##ID:" + id);
model.addAttribute(biz.getAccount(id));
return "/show.jsp";
@RequestMapping("/list")
public String list(Model model) {
model.addAttribute("list", biz.getList());
return "/list.jsp";
@ExceptionHandler(Exception.class)
public String exception(Exception e, HttpServletRequest request) {
//e.printStackTrace();
request.setAttribute("exception", e);
return "/error.jsp";
15、 基本页面代码
&%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%&
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
"-//W3C//DTD HTML 4.01 Transitional//EN"&
"&%=basePath%&"&
"pragma" content="no-cache"&
"cache-control" content="no-cache"&
"expires" content="0"&
"keywords" content="keyword1,keyword2,keyword3"&
"description" content="This is my page"&
MyBatis 3.0.4 整合 Spring 3.0.5
"account/list.do"&查询所有
"account/add.do?username=abcdef&password=123132&status=2"&添加
"account/get.do?id=25"&查询
&%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%&
&%@ taglib uri="http:///jsp/jstl/core" prefix="c" %&
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
&!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&
&base href="&%=basePath%&"&
&title&all Account Result&/title&
&meta http-equiv="pragma" content="no-cache"&
&meta http-equiv="cache-control" content="no-cache"&
&meta http-equiv="expires" content="0"&
&meta http-equiv="keywords" content="keyword1,keyword2,keyword3"&
&meta http-equiv="description" content="This is my page"&
&c:forEach items="${list}" var="data"&
id: ${data.accountId }---name: ${data.username }---password: ${data.password }&hr/&
&/c:forEach&
&%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%&
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
&!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&
&base href="&%=basePath%&"&
&title&show Account&/title&
&meta http-equiv="pragma" content="no-cache"&
&meta http-equiv="cache-control" content="no-cache"&
&meta http-equiv="expires" content="0"&
&meta http-equiv="keywords" content="keyword1,keyword2,keyword3"&
&meta http-equiv="description" content="This is my page"&
${account }&br/&
${account.username }#${account.accountId }
&%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%&
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
&!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&
&base href="&%=basePath%&"&
&title&Error Page&/title&
&meta http-equiv="pragma" content="no-cache"&
&meta http-equiv="cache-control" content="no-cache"&
&meta http-equiv="expires" content="0"&
&meta http-equiv="keywords" content="keyword1,keyword2,keyword3"&
&meta http-equiv="description" content="This is my page"&
&H2&Exception: ${exception }&/H2&
&a href="javascript:document.getElementById('show').style.display = 'block';void(0);"&
&div id="show" style="color:
display: "&
&% Exception ex = (Exception)request.getAttribute("exception"); %&
&% ex.printStackTrace(new java.io.PrintWriter(out)); %&
16、 以上就基本上完成了整个Spring+SpringMVC+MyBatis的整合了。如果你想添加事务管理,得在applicationContext-common.xml中加入如下配置:
&bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&
&property name="dataSource" ref="dataSource" /&
同时还需要加入aspectjweaver.jar这个jar包;
注意的是:Jdbc的TransactionManager不支持事务隔离级别,我在整个地方加入其它的TransactionManager,增加对transaction的隔离级别都尝试失败!
也许可以用于jpa、jdo、jta这方面的东西。不知道大家对MyBatis的事务是怎么处理的?
17、 对Dao进行扩展封装,运用SqlSessionDaoSupport进行模板的扩展或运用:
BaseDao代码如下:
package com.hoo.dao.
import java.util.ArrayL
import java.util.L
import javax.inject.I
import org.apache.ibatis.session.SqlSessionF
import org.mybatis.spring.support.SqlSessionDaoS
import org.springframework.stereotype.R
import com.hoo.dao.BaseD
* function: 运用SqlSessionDaoSupport封装Dao常用增删改方法,可以进行扩展
* @author hoojo
* @createDate
下午06:33:37
* @file BaseDaoImpl.java
* @package com.hoo.dao.impl
* @project MyBatisForSpring
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@
* @version 1.0
@Repository
@SuppressWarnings({ "unchecked", "unused" })
public class BaseDaoImplextends Object& extends SqlSessionDaoSupport implements BaseDao {
private SqlSessionFactory sqlSessionF
public boolean add(String classMethod, T entity) throws Exception {
boolean flag =
flag = this.getSqlSession().insert(classMethod, entity) & 0 ? true :
} catch (Exception e) {
public boolean edit(String classMethod, T entity) throws Exception {
boolean flag =
flag = this.getSqlSession().update(classMethod, entity) & 0 ? true :
} catch (Exception e) {
public T get(String classMethod, T entity) throws Exception {
T result =
result = (T) this.getSqlSession().selectOne(classMethod, entity);
} catch (Exception e) {
public List getAll(String classMethod) throws Exception {
List result = new ArrayList();
result = this.getSqlSession().selectList(classMethod);
} catch (Exception e) {
public boolean remove(String classMethod, T entity) throws Exception {
boolean flag =
flag = this.getSqlSession().delete(classMethod, entity) & 0 ? true :
} catch (Exception e) {
值得说明的是,这个类继承了SqlSessionDaoSupport,它需要我们帮助它注入SqlSessionFactory或是SqlSessionTemplate,如果两者都被注入将忽略SqlSessionFactory属性,使用SqlSessionTemplate模板。
继承SqlSessionDaoSupport后,可以拿到SqlSession完成数据库的操作;
18、 对Dao进行扩展封装,运用SqlSessionTemplate进行模板的扩展或运用:
首先看看这个组件中运用的一个Mapper的基类接口:
package com.hoo.
import java.util.L
import org.springframework.dao.DataAccessE
* function: BaseSqlMapper继承SqlMapper,对Mapper进行接口封装,提供常用的增删改查组件;
* 也可以对该接口进行扩展和封装
* @author hoojo
* @createDate
上午11:36:41
* @file BaseSqlMapper.java
* @package com.hoo.mapper
* @project MyBatisForSpring
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@
* @version 1.0
public interface BaseSqlMapper extends SqlMapper {
public void add(T entity) throws DataAccessE
public void edit(T entity) throws DataAccessE
public void remvoe(T entity) throws DataAccessE
public T get(T entity) throws DataAccessE
public List getList(T entity) throws DataAccessE
该接口继承SqlMapper接口,但是该接口没有MyBatis的mapper实现。需要我们自己的业务mapper继承这个接口,完成上面的方法的实现。
看看继承SqlSessionTemplate的BaseMapperDao代码:
package com.hoo.dao.
import java.util.L
import javax.inject.I
import org.apache.ibatis.session.SqlSessionF
import org.mybatis.spring.SqlSessionT
import org.springframework.stereotype.R
import com.hoo.dao.BaseMapperD
import com.hoo.mapper.BaseSqlM
* function:运用SqlSessionTemplate封装Dao常用增删改方法,可以进行扩展
* @author hoojo
* @createDate
下午12:22:07
* @file BaseMapperDaoImpl.java
* @package com.hoo.dao.impl
* @project MyBatisForSpring
* @blog http://blog.csdn.net/IBM_hoojo
* @email hoojo_@
* @version 1.0
@SuppressWarnings("unchecked")
@Repository
public class BaseMapperDaoImpl extends SqlSessionTemplate implements BaseMapperDao {
public BaseMapperDaoImpl(SqlSessionFactory sqlSessionFactory) {
super(sqlSessionFactory);
private Classextends BaseSqlMapper& mapperC
public void setMapperClass(Classextends BaseSqlMapper& mapperClass) {
this.mapperClass = mapperC
private BaseSqlMapper getMapper() {
return this.getMapper(mapperClass);
public boolean add(T entity) throws Exception {
boolean flag =
this.getMapper().add(entity);
} catch (Exception e) {
public boolean edit(T entity) throws Exception {
boolean flag =
this.getMapper().edit(entity);
} catch (Exception e) {
public T get(T entity) throws Exception {
return this.getMapper().get(entity);
public List getAll() throws Exception {
return this.getMapper().getList(null);
public boolean remove(T entity) throws Exception {
boolean flag =
this.getMapper().remvoe(entity);
} catch (Exception e) {
上面这个类继承了SqlSessionTemplate,这个类需要提供一个构造函数。这里提供的是SqlSessionFactory的构造函数,通过该函数注入SqlSessionFactory即可完成数据库操作;
例外的是这个类还有一个关键属性mapperClass,这个class需要是BaseSqlMapper接口或是子接口,然后通过SqlSessionTemplate模板获得当前设置的Class的Mapper对象,完成数据库操作。
该类的测试代码:
@ContextConfiguration("classpath:applicationContext-*.xml")
public class BaseMapperDaoImplTest extends AbstractJUnit38SpringContextTests {
private BaseMapperD
public void init() {
dao.setMapperClass(CompanyMapper.class);
public void testGet() throws Exception {
Company c = new Company();
c.setCompanyId(4);
System.out.println(dao.get(c));
public void testAdd() throws Exception {
Company c = new Company();
c.setAddress("北京中关村");
c.setName("beijin");
System.out.println(dao.add(c));
一般情况下,你可以在一个Dao中注入BaseMapperDao,紧跟着需要设置MapperClass。只有设置了MapperClass后,BaseMapperDao才能获取对应mapper,完成相关的数据库操作。当然你可以在这个Dao中将SqlSessionTemplate、SqlSession暴露出来,当BaseMapperDao的方法不够用,可以进行扩展。
页面访问:http://localhost:8080/shcowin/add.do
12345678910
12345678910
12345678910 上一篇:下一篇:文章评论相关解决方案 12345678910 Copyright & &&版权所有

我要回帖

更多关于 mybatis if true 的文章

 

随机推荐