Spring+SpringMvc+Mybatis整合小Demo

news2024/10/7 12:26:59

原始方式整合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>

运行部署访问即可。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/772089.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

linux之Ubuntu系列 find 、 ln 、 tar、apt-get 指令 软链接和硬链接

查找文件 find 命令 功能非常强大&#xff0c;通常用来在 特定的目录下 搜索 符合条件的文件 find [path] -name “.txt” 记得要加 “ ” 支持通配符 &#xff0c;正则表达式 包括子目录 ls 不包括 子目录 如果省略路径&#xff0c;表示 在当前路径下&#xff0c;搜索 软链接…

测试老鸟总结,性能测试-最佳并发和最大并发,性能测试实施...

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 性能测试&#xf…

无涯教程-Javascript - Switch语句

从JavaScript 1.2开始&#xff0c;您可以使用 switch 语句来处理这种情况&#xff0c;它比重复的 if ... else if 语句更有效。 流程图 以下流程图说明了switch-case语句的工作原理。 switch 语句的目的是给出一个要求值的表达式&#xff0c;并根据表达式的值执行多个不同的语…

云曦暑期学习第一周——sql注入

1浅谈sql注入 1.1sql注入 sql注入是指web应用程序对用户输入数据的合法性没有判断&#xff0c;前端传入后端的参数是攻击者可控的&#xff0c;并且参数带入数据库查询&#xff0c;攻击者可以通过构造不同的sql语句来实现对数据库的任意操作 1.2原理 条件&#xff1a; 1.参…

接入端口与中继端口

交换机端口是支持 IT 的基本组件&#xff0c;可实现网络通信。这些有线硬件设备负责连接并允许在不同设备和连接到其端口的网络部分之间进行数据传输。由于网络管理员在确保网络连接和可用性方面发挥着关键作用&#xff0c;因此网络管理员必须清楚地了解、映射和查看其网络交换…

面向对象Java基础

前言 看大话设计模式的时候&#xff0c;发现自己的基础不是很扎实&#xff0c;重新回顾一些存在有点点不确定的内容&#xff0c;并从书中截取下来&#xff0c;做成笔记快速复习。 1、字段和属性 字段&#xff1a;用private修饰&#xff0c;也叫私有变量。属性&#xff1a;字…

2.Docker操作

文章目录 Docker操作Docker镜像操作搜索镜像获取镜像镜像加速下载查看镜像详细信息为镜像添加标签删除镜像导出导入镜像上传镜像 Docker容器操作创建容器查看容器状态启动容器创建并启动容器进入容器停止容器删除容器复制容器文件到宿主机容器的导出导入 Docker操作 ###查看do…

【天工Godwork精品教程】天工3.1.7安装教程(附Godwork完整版下载地址)

本文讲解天工3.1.7安装过程(附Godwork完整版网盘下载地址)。 文章目录 一、天工3.1.7安装教程1. 安装GodWork-AT 3.1.72. 安装GodWork-AT 3.1.7补丁3. 安装GodWork-EOS-Setup-2017B-12314. 安装GodWork-EOS补丁5. 运行godwokr软件6. 生成ZC码7. 输入ZC码8. eos插件调用二、天…

AtcoderABC245场

A - Good morningA - Good morning 题目大意 给定Takahashi和Aoki的起床时间&#xff0c;判断谁先起床。 思路分析 题目要求比较Takahashi和Aoki的起床时间。首先&#xff0c;将起床时间转换为以分钟为单位。然后&#xff0c;通过比较两者的起床时间来确定谁先起床。 时间复…

文献阅读笔记——求解车辆路径问题及其变体的元启发式算法的分类综述

论文题目&#xff1a;A taxonomic review of metaheuristic algorithms for solving the vehicle routing problem and its variants 其他信息&#xff1a;Computers & Industrial Engineering|2020|Raafat Elshaer⁎, Hadeer Awad 文章贡献&#xff1a;1&#xff09;对使…

RabbitMQ安装及简单使用

说明&#xff1a;RabbitMQ&#xff08;官网&#xff1a;&#xff09;是一门异步通讯技术&#xff0c;使用异步通讯技术&#xff0c;可解决同步通讯的一些问题。 安装 本文介绍在云服务器上安装RabbitMQ&#xff0c;操作系统是CentOS 7&#xff0c;远程连接工具是WindTerm&…

抖音seo源码部署/开源不加密可二开/抖音seo优化开发方案

一、前言 抖音是目前国内非常流行的短视频平台之一&#xff0c;用户数量庞大&#xff0c;更是吸引了许多企业和个人在上面开设账号&#xff0c;通过发布内容来进行流量变现。但是&#xff0c;在一个账号发布内容的同时&#xff0c;管理员又需要同时关注多个账号&#xff0c;对账…

C语言--程序环境和预处理

翻译环境 C语言的代码是文本信息&#xff0c;对于计算机来说无法直接理解&#xff0c;需要通过翻译环境进行翻译成二进制信息&#xff1b; 我们在写代码的时候&#xff0c;一般都会写在一个源文件中&#xff0c;这时候我们就使用我们的编译器(VS)将其转换为机器代码&#xff0…

汉诺塔问题(Hanoi Tower)--递归典型问题--Java版(图文详解)

目录 概述问题来源汉诺塔问题的规则 实现解题思路一个盘子两个盘子三个盘子n个盘子 递归概念递归特性递归的时间复杂度汉诺塔中的递归 代码 总结 概述 问题来源 汉诺塔&#xff08;Tower of Hanoi&#xff09;&#xff0c;又称河内塔&#xff0c;是一个源于印度古老传说的益智…

2023无监督摘要顶会论文合集

2023无监督摘要顶会论文合集 写在最前面ACL-2023Aspect-aware Unsupervised Extractive Opinion Summarization 面向的无监督意见摘要&#xff08;没找到&#xff09;Unsupervised Extractive Summarization of Emotion Triggers *情绪触发(原因)的 *无监督 *抽取式 摘要&#…

Python Request get post 代理 基本使用

Python Request get post 代理 常用示例 文章目录 Python Request get post 代理 常用示例一、Pip install requests二、Requests 请求时携带的常用参数1、参数说明2、headers3、requests 常用参数:url、headers、proxies、verify、timeout 三、Requests Get Post1、Get2、Post…

【Kotlin】基础速览(1):操作符 | 内建类型 | 类型转换 | 字符串模板 | 可变 var 和不可变 val

&#x1f4dc; 本章目录&#xff1a; 0x00 操作符&#xff08;operators&#xff09; 0x01 内建类型&#xff08;Build-in&#xff09; 0x02 类型转换&#xff1a;显式类型转换 0x03 在较长数字中使用下划线 0x04 字符串&#xff08;String&#xff09; 0x05 字符串模板&…

grpc中间件之链路追踪(otel+jaeger)

参考文档 https://github.com/grpc-ecosystem/go-grpc-middleware/blob/main/examples/client/main.go https://github.com/grpc-ecosystem/go-grpc-middleware/blob/main/examples/server/main.go https://github.com/open-telemetry/opentelemetry-go/blob/main/example/jaeg…

基于深度学习的高精度道路瑕疵检测系统(PyTorch+Pyside6+YOLOv5模型)

摘要&#xff1a;基于深度学习的高精度道路瑕疵&#xff08;裂纹&#xff08;Crack&#xff09;、检查井&#xff08;Manhole&#xff09;、网&#xff08;Net&#xff09;、裂纹块&#xff08;Patch-Crack&#xff09;、网块&#xff08;Patch-Net&#xff09;、坑洼块&#x…

销售易的12年与七个瞬间

导读&#xff1a;企业级没有捷径 12年对一家企业意味着什么&#xff1f; 在消费互联网领域&#xff0c;12年足够长&#xff0c;短短几年内上市的故事过去屡见不鲜。在企业服务的toB领域&#xff0c;产业成熟和企业发展的时间维度被拉长&#xff0c;但故事同样精彩。 2023年7月1…