Spring+SpringMvc+Mybatis整合小Demo

原始方式整合SSM

不使用spring-mybatis包

项目内容

整合ssm完成对account表新增和查询的操作 

项目大体结构

 创建mavenWeb项目 

pom文件中引入依赖

spring核心、aspectj(aop)、spring-jdbc(jdbcTemplate)、spring-tx(事务)、

数据源:mysql、c3p0、mybatis       mybatis-spring(spring整合mybatis)

junit、spring-tst、

servlet、jsp、jstl、

lombok、

spring-webmvc(springMvc依赖)

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId><!--spring核心,包含aop-->
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId><!--aop相关-->
            <version>1.9.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId><!--jdbcTemplate相关-->
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId><!--事务相关-->
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.8</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.5</version><!--要用这个版本的,之前用的低版本和spring-mybatis整合时查询方法报错-->
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.13</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId><!--spring集成junit-->
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId><!--springMvc-->
            <version>5.0.5.RELEASE</version>
        </dependency>
    </dependencies>
resource下log4j.properties文件
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=info, stdout
resource下jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/jdbc
jdbc.username=root
jdbc.password=root123

spring核心配置:

resource下applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
    <context:component-scan base-package="com.kdy"/><!--开启组件扫描-->
</beans>
数据库数据表

 com.kdy.domain
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Account {
    private int id;
    private String name;
    private double money;
}
com.kdy.mapper中AccountMapper接口
public interface AccountMapper {
    //保存账户数据
    @Insert("insert into `account` values(#{id},#{name},#{money})")
    public void save(Account account);
    //查询账户数据
    @Select("select * from `account`")
    public List<Account> findAll();

}
resource下com.kdy.mapper中AccountMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kdy.mapper.AccountMapper"><!--即使使用mybatis的注解开发也需要加上命名空间的mapper标签-->
</mapper>

resource下mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--通过properties标签机制外部的properties文件-->
    <properties resource="jdbc.properties"></properties>
    <!--起别名:为权限定名的类起一个比较短的别名-->
    <typeAliases>
        <package name="com.kdy.domain"/><!--扫描的为它的类名且不区分大小写-->
        <!--        <typeAlias type="com.kdy.domain.User" alias="user"></typeAlias>-->
        <!--mybatis已经将String->string、Long->long、Integer->int、Double->double、Boolean->boolean转换设置好了别名-->
    </typeAliases>
    <!--数据源环境-->
    <environments default="development">
        <environment id="development"><!--环境development、test,可以配置多个数据库连接的环境信息,将来通过default属性切换-->
            <transactionManager type="JDBC"/><!--事务管理器,spring可接管,这里直接使用的JDBC的提交和回滚。依赖从数据源得到链接来管理事务作用域-->
            <dataSource type="POOLED">
                <!--数据源类型type有三种:
                UNPOOLED:这个数据源的实现只是每次被请求时打开和关闭连接。
                POOLED:这种数据源的实现利用“池” 的概念将JDBC连接对象组织起来。
                JNDI:这个数据源的实现是为了能在如EJB或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个JNDI上下文的引用。-->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <!--如果mysqlurl中有&符号需要进行转义为&amp;,如useSSL=false&amp;useServerPrepStmts=true
                127.0.0.1:3306本机默认端口可省略不写,直接为///-->
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--mappers加载映射,加载方式如下:
    使用相对于类路径的资源引用,例如:<mapper resource="org/mybatis/builder/AuthorMapper.xml/>
    使用完全限定资源定位符(URL) ,例如: <mapper url= "file:///var/mappers/ AuthorMapper.xml"/>
    使用映射器接口实现类的完全限定类名,例如: <mapper class=" org.mybatis.builder.AuthorMapper"/>
    将包内的映射器接口实现全部注册为映射器,例如: <package name="org.mybatis.builder"/>-->
    <mappers>
        <package name="com.kdy.mapper"/>
        <!--        <mapper resource="UserMapper.xml"/>-->
    </mappers>
</configuration>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--全局初始化参数-->
    <context-param><!--servletContext.getInitParameter("contextConfigLocation)、jsp中通过el表达式-->
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!--配置Spring的监听器:spring集成web里的
        1.web.xml中配置全局初始化参数contextConfigLocation和org.springframework.web.context.ContextLoaderListener的listener
        当web项目启动加载初始化参数contextConfigLocation,并根据classpath:applicationContext.xml进行new出ApplicationContext对象app,
        将app对象通过setAttribute("app",app)放入当前web应用最大的域servletContext域中域中,并需要时getAttribute取出该app对象。
        2.还有一种方式为定义监听类和@WebListener注解方式详见spring的博客中集成web部分。-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--springMvc字符编码过滤器,解决post请求中文乱码问题-->
    <filter>
        <filter-name>CharacterEncodingFilter</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>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--配置SpringMVC的前端控制器:
    配置一个servlet,类选择第三方org.springframework的DispatcherServlet
    配置该类,且路径为拦截所有来作为springMvc的前端控制器servlet  -->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param><!--该servlet的初始化参数-->
            <!--spring-mvc.xml是怎么加载的呢
            spring-mvc.xml是怎么加载的呢
            类似web.xml中的<context-param>application域的全局初始化参数。
            这里下面配置初始化参数spring-mvc.xml名称即为web.xml中该DispatcherServlet的servlet的init初始化参数来提供,
            以便org的DispatcherServlet根据这个servlet的init初始化参数去加载springMVC的配置文件,
            继而IOC出controller(特有行为)实例提供给前端控制器DispatcherServlet(共有行为)使用。
            -->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup><!--loadOnStartup=负整数或不加默认第一次访问该servlet执行时创建servlet对象并初始化
        loadOnStartup为0或正整数时,web服务器启动时创建servlet对象,数字越小,优先级越高-->
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern><!-- 配置该servlet的路径为拦截所有/,虽会覆盖tomcat静态资源访问路径,但现在没有静态资源html之类,只有jsp动态页面。-->
    </servlet-mapping>
</web-app>
com.kdy.exception(写着玩的,练习一下spring异常处理)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AccountException extends Exception {
    String message;
}
com.kdy.resolver(写着玩的,练习一下spring异常处理)
public class MyExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        if (e instanceof ClassCastException){
            modelAndView.addObject("info","类转换异常");
        }else if(e instanceof ArithmeticException){
            modelAndView.addObject("info","除零算数异常");
        }else if(e instanceof FileNotFoundException){
            modelAndView.addObject("info","文件找不到异常");
        }else if(e instanceof NullPointerException){
            modelAndView.addObject("info","空指针异常");
        }else if(e instanceof AccountException){
            AccountException ae=(AccountException) e;
            modelAndView.addObject("info","AccountService的报的异常"+ae.getMessage());
        }
        modelAndView.setViewName("error");
        return modelAndView;
    }
}
webapp下jsp中error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>error</title>
</head>
<body>
<h1>异常页面~</h1>
<h2>${info}</h2>
</body>
</html>

resource下spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    ">
    <!--Controller的组件扫描-->
    <context:component-scan base-package="com.kdy"></context:component-scan>
    <!--配置内部资源视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"></property><!--前缀-->
        <property name="suffix" value=".jsp"></property><!--后缀-->
    </bean>

    <!--注解驱动,顶替配置的配置的处理器映射器和适配器,集成了jackson,可Controller资源方法返回字为对象User时,自动转为json-->
    <mvc:annotation-driven />

    <!--js和css和html等被web.xml中配置的前端控制配置拦截了,这里配置springMvc静态资源放行-->
    <mvc:default-servlet-handler/><!--若使用这种方式,必须配置注解驱动,否则controller无法访问-->

    <!--自定义异常处理器-->
    <bean class="com.kdy.resolver.MyExceptionResolver"/>
</beans>
com.kdy.service.impl
@Service
public class AccountServiceImpl implements AccountService {

    @Override
    public void save(Account account) throws AccountException {
        try {
            //1.加载mybatis核心配置,获取SqlSessionFactory
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //2.获取SqlSession对象,用它来执行sql
            SqlSession sqlSession = sqlSessionFactory.openSession();
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
            mapper.save(account);
            sqlSession.commit();
            sqlSession.close();
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            String str = sw.toString();
            throw new AccountException(str);
        }
    }

    @Override
    public List<Account> findAll() throws AccountException {
        try {
            //1.加载mybatis核心配置,获取SqlSessionFactory
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //2.获取SqlSession对象,用它来执行sql
            SqlSession sqlSession = sqlSessionFactory.openSession();
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
            List<Account> accountList = mapper.findAll();
            sqlSession.close();
            return accountList;
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            String str = sw.toString();
            throw new AccountException(str);
        }
    }
}
com.kdy.controller
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    //保存
    @RequestMapping(value = "/save",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String save(Account account) throws AccountException {
        accountService.save(account);
        return "保存成功";
    }

    //查询
    @RequestMapping("/findAll")
    public ModelAndView findAll() throws AccountException {
        List<Account> accountList = accountService.findAll();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("accountList",accountList);
        modelAndView.setViewName("index");
        return modelAndView;
    }
}
webapp下jsp下save.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>save</title>
</head>
<body>
<h1>添加账户信息表单</h1>
<form name="accountForm" action="${pageContext.request.contextPath}/account/save">
    账户名称:<input type="text" name="name"><br/>
    账户金额:<input type="text" name="money"><br/>
    <input type="submit" value="保存"><br/>
</form>
</body>
</html>
webapp下jsp下index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!--引入jstl标签库URI-->
<html>
<head>
    <title>index</title>
</head>
<body>
<h1>展示用户数据列表</h1>
<table border="1px">
    <tr>
        <th>账户id</th>
        <th>账户名称</th>
        <th>账户金额</th>
    </tr>
    <c:forEach items="${accountList}" var="account">
        <tr>
            <td>${account.id}</td>
            <td>${account.name}</td>
            <td>${account.money}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

运行tomcat访问http://localhost:8080/SsmModule/jsp/save.jsp

http://localhost:8080/SsmModule/account/findAll

原始方式整合sping和mybatis的弊端

如service层中的是实现类中的方法
    public void save(Account account) throws AccountException {
            InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
       SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); ... }

每当执行一次controller就会在service层创建一个sqlSessionFactory工厂

虽然可采取servletContextListener监听器将sqlSessionFactory存放servletContext域中
可参考spring博客中最下方集成web环境中的内容
1、web.xml中增加一个全局初始化参数mybatisConfigLocation
    <!--全局初始化参数-->
    <context-param><!--servletContext.getInitParameter("contextConfigLocation)、jsp中通过el表达式-->
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <context-param><!--servletContext.getInitParameter("contextConfigLocation)、jsp中通过el表达式-->
        <param-name>mybatisConfigLocation</param-name>
        <param-value>mybatis-config.xml</param-value>
    </context-param>
2、com.kdy.listener中
@WebListener
public class MybatisLoadListener implements ServletContextListener {

    @SneakyThrows
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        //获取web.xml中配置的application的全局初始化参数:
        String mybatisConfigLocation = servletContext.getInitParameter("mybatisConfigLocation");//其值为applicationContext.xml
        InputStream inputStream = Resources.getResourceAsStream(mybatisConfigLocation);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        servletContext.setAttribute("sqlSessionFactory",sqlSessionFactory);
    }
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    }
}
3、com.kdy.util下创建一个工具类
public class MybatisContextUtils {
    public static SqlSessionFactory getSqlSessionFactory(ServletContext servletContext){
        return (SqlSessionFactory)servletContext.getAttribute("sqlSessionFactory");
    }
}
controller中修改接口传递一个参数request,且修改service层入参传递一个servletContext
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    //保存
    @RequestMapping(value = "/save",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String save(HttpServletRequest request,Account account) throws AccountException {
        WebApplicationContext ac1= WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
        ServletContext servletContext = ac1.getServletContext();
        accountService.save(account,servletContext);
        return "保存成功";
    }

    //查询
    @RequestMapping("/findAll")
    public ModelAndView findAll(HttpServletRequest request) throws AccountException {
        WebApplicationContext ac1= WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
        ServletContext servletContext = ac1.getServletContext();
        List<Account> accountList = accountService.findAll(servletContext);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("accountList",accountList);
        modelAndView.setViewName("index");
        return modelAndView;
    }
}
@Service
public class AccountServiceImpl implements AccountService {

    @Override
    public void save(Account account, ServletContext servletContext) throws AccountException {
        try {
            SqlSessionFactory sqlSessionFactory = MybatisContextUtils.getSqlSessionFactory(servletContext);
            //2.获取SqlSession对象,用它来执行sql
            SqlSession sqlSession = sqlSessionFactory.openSession();
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
            mapper.save(account);
            sqlSession.commit();
            sqlSession.close();
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            String str = sw.toString();
            throw new AccountException(str);
        }
    }

    @Override
    public List<Account> findAll(ServletContext servletContext) throws AccountException {
        try {
            SqlSessionFactory sqlSessionFactory = MybatisContextUtils.getSqlSessionFactory(servletContext);
            //2.获取SqlSession对象,用它来执行sql
            SqlSession sqlSession = sqlSessionFactory.openSession();
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
            List<Account> accountList = mapper.findAll();
            sqlSession.close();
            return accountList;
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            String str = sw.toString();
            throw new AccountException(str);
        }
    }
}

 运行tomcat访问http://localhost:8080/SsmModule/jsp/save.jsp

http://localhost:8080/SsmModule/account/findAll

但是这种方式麻烦不说

service层每次还要加上一个servletContext的入参使得controller和service界限模糊不清

所以绝不推荐使用

Spring整合mybatis的方式整合SSM

思路

将session工厂交给spring容器管理,从容器中获得执行操作的Mapper实例即可

将事务的控制(sqlSession.commit和sqlSession.close等)交给spring容器进行声明式事务控制

操作

接着原始方式整合SSM的案例写
如果写了上面监听器抽的步骤先回退到原始方式整合SSM案例
pom文件中引入spring-mybatis的包(上面已经引入了,包中有spring提供的工厂的实现类)
1、resource下的mybatis-config.xml文件删除掉数据源和引入jdbc.properties的内容
2、applicationContext.xml中加上数据源和引入jdbc.properties的内容
接下来让service中的sqlSession交由spring产生
3、applicationContext.xml中配置sqlSessionFactory的bean
接下来mybatis核心配置中mapper映射的加载也可以交由spring托管
4、resource下的mybatis-config.xml文件删除加载映射<mappers><package>...
5、applicationContext.xml中配置MapperScannerConfigurer扫描mapper所在的包,并为mapper创建实现类
mybatis-config.xml变为
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--起别名:为权限定名的类起一个比较短的别名-->
    <typeAliases>
        <package name="com.kdy.domain"/><!--扫描的为它的类名且不区分大小写-->
        <!--        <typeAlias type="com.kdy.domain.User" alias="user"></typeAlias>-->
        <!--mybatis已经将String->string、Long->long、Integer->int、Double->double、Boolean->boolean转换设置好了别名-->
    </typeAliases>
</configuration>
applicationContext.xml变为
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
    <context:component-scan base-package="com.kdy"/><!--开启组件扫描-->
    <context:property-placeholder location="classpath:jdbc.properties"/><!--引入配置文件,使用el获取-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--配置sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!--加载mybatis核心文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>
    <!--mybatis核心配置中mapper映射的加载也可以交由spring托管
    这样spring扫描包,并将mapper放入spring容器中。-->
    <!--扫描mapper所在的包,并为mapper创建实现类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.kdy.mapper"></property>
    </bean>
</beans>

使用

只需在用到mapper的地方注入mapper包下的某个mapper接口即可
删除 spring-mvc.xml自定义异常处理器,删MyException,删myExceptionResolver
AccountServiceImpl
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public void save(Account account){
        try {
            accountMapper.save(account);
        } catch (Exception e) {
          e.printStackTrace();
        }
    }

    @Override
    public List<Account> findAll(){
        try {
            List<Account> accountList = accountMapper.findAll();
            return accountList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

接下来为其加上spring的事务管理

applicationContext.xml中加上配置平台事务管理器、事务的增强和织入
<?xml version="1.0" encoding="UTF-8"?>
<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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation=
               "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
">
    <context:component-scan base-package="com.kdy"/><!--开启组件扫描-->
    <context:property-placeholder location="classpath:jdbc.properties"/><!--引入配置文件,使用el获取-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--配置sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!--加载mybatis核心文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>
    <!--mybatis核心配置中mapper映射的加载也可以交由spring托管
    这样spring扫描包,并将mapper放入spring容器中。-->
    <!--扫描mapper所在的包,并为mapper创建实现类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.kdy.mapper"></property>
    </bean>

    <!--配置平台事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/><!--引入数据源,需要它的connection对象事务控制,提交和回滚-->
    </bean>
    <!--通知 事务的增强-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--isolation隔离级别、propagation传播行为、timeout超时时间、readonly是否只读-->
            <!--对目标类中的某些名称的方法进行事务处理的增强-->
            <tx:method name="*"/>
            <!--<tx:method name="*" isolation="DEFAULT" propagation="REQUIRED" timeout="-1" read-only="false"/>
            <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
            <tx:method name="save" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
            <tx:method name="findAll" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
            <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>-->
            <!--以update开头的通配符的写法-->
        </tx:attributes>
    </tx:advice>
    <!--配置事务的aop织入,也可抽取切点点表达式出来后引用-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.kdy.service.impl.*.*(..))"></aop:advisor>
    </aop:config>
</beans>
运行部署访问即可。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值