Day26SSM之整合

学习目标

  1. SSM整合
  2. CRUD

ssm整合说明

  • SSM是什么?
    Spring,SpringMVC,Mybastis
  • 为什么要专门训练SSM
    要开发一个项目,首先是搭建SSM环境,之后才能开发其他功能
  1. 整合思路是什么?
  • 先搭建整合的环境
  • 先把Spring的配置搭建完成
  • 再使用Spring整合SpringMVC框架
  • 最后使用Spring整合MyBatis框架
  1. SSM整合可以使用多种方式,咱们会选择XML + 注解的方式
    在这里插入图片描述

SSM搭建环境

  1. 数据库创建ssm
  2. 创建maven工程
  3. properties给谁用?
  4. 依赖框架
  5. log4j
    SQL
create database ssm;
use ssm;
create table person(
id int primary key auto_increment, 
`name` varchar(20),
money double
);

在这里插入图片描述

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring.version>5.2.9.RELEASE</spring.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>5.1.6</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
  </properties>

  <dependencies>
    <!-- spring -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.8</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

    <!-- log end -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\ssm.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

整合Spring框架测试代码IOC&DI

  1. 编写业务类调用测试逻辑
  • TestPersonService
  • IPersonService PersonServiceImpl
  • Person
  1. applicationContext.xml
  2. 配置组件扫描 – 验证IOC
  3. 配置哪些不扫描
  4. 验证DI
  • IPersonDao PersonDaoImpl
    src\main\java\com\vission\bean\Person.java
public class Person {
    private Integer id;
    private String name;
    private Double money;
    public Person() {
    }
    public Person(String name, Double money) {
        this.name = name;
        this.money = money;
    }
    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }

src\main\java\com\vission\dao\IPersonDao.java

public interface IPersonDao {
    List<Person> findAll();
    void save(Person person);
}

src\main\resources\com\vission\dao\IPersonDao.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="com.vission.dao.IPersonDao">
    <select id="findAll" resultType="person">
            select * from person;
    </select>
    <insert id="save" parameterType="person">
        insert into person (name,money)values(#{name},#{money});
    </insert>
</mapper>

src\main\java\com\vission\Service\IPersonService.java

public interface IPersonService {
    List<Person> findAll();
    int savePerson(Person person);
}

src\main\java\com\vission\ServiceImpl\PersonServiceImpl.java

@Repository//通过扫描
public class PersonServiceImpl implements IPersonService {
    IPersonDao personDao = MySeesionUtils.getMapper(IPersonDao.class);
    private static final Logger log = Logger.getLogger(PersonServiceImpl.class.getName());
    @Override
    public List<Person> findAll() {
        List<Person> list = personDao.findAll();
        return list;
    }
    @Override
    public int  savePerson(Person person) {
        personDao.save(person);
        log.info("dao层添加的"+person);
        int code = 1;
        return code;
    }
}

TestPersonService

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:ApplicationContext.xml")//加载classpath
public class TestPersonService {
    private static final Logger log = Logger.getLogger(TestPersonService.class.getName());//引入日志文件
    MySeesionUtils mySeesionUtils = new MySeesionUtils();//加载工具类
    IPersonDao dao = mySeesionUtils.getMapper(IPersonDao.class);
    @Autowired
    @Qualifier("personServiceImpl")
    //通过注解使接口实现
    IPersonService personService;
    @After
    //最后的表单提交
    public void commitAndCloseSeesion(){
        mySeesionUtils.commitAndClose();
    }
    @Test
    public void addTest(){//DI
        Person person = new Person("78787",100.00);
        int code  = personService.savePerson(person);
        if (code == 1){
           log.info(new Date()+"  添加用户"+person.getName());
        }
    }
    @Test
    public void findTest(){//DI
       List<Person> list = personService.findAll();
       log.info(list);
    }
}

在这里插入图片描述

Spring整合SpringMVC的框架1

  1. web.xml中配置前端控制器DispatcherServlet
    SpringMVC的核心就是DispatcherServlet,DispatcherServlet实质也是一个HttpServlet。DispatcherSevlet负责将请求分发,所有的请求都有经过它来统一分发。
  2. web.xml中配置编码过滤器CharacterEncodingFilter
    在 SpringMVC 中,框架直接给我们提供了一个用来解决请求和响应的乱码问题的过滤器 CharacterEncodingFilter
  3. web.xml中配置编码监听器ContextLoaderListener
    web.xml中的配置文件中ContextLoaderListener作为监听器,会监听web容器相关事件,在web容器启动或者关闭时触发执行响应程序

web.xml 配置DispatcherServlet,CharacterEncodingFilter,ContextLoaderListener

src\main\webapp\WEB-INF\web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>


  <!--设置配置文件的路径  service dao-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:ApplicationContext.xml</param-value>
  </context-param>


  <!--解决中文乱码的过滤器-->
  <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>


  <!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--配置前端控制器  controller-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载springmvc.xml配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--启动服务器,创建该servlet-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

Spring整合SpringMVC的框架2

  1. springmvc中配置视图解析器,组件扫描,注解驱动
  2. 配置springmvc对资源文件的放行
  3. 编写一个PersonController测试
  4. 编写一个list.jsp页面进行展示数据
    src\main\resources\springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc" 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.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">
    <!--springmvc是web层  UserController  @Controller -->
    <!-- 打开组件扫描-->
    <context:component-scan base-package="com.vission">
        <!-- 只处理带@Controller的请求-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--配置的视图解析器对象 /WEB-INF/pages/success.jsp -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--过滤静态资源   .js .css png-->
<!--    <mvc:resources location="/css/" mapping="/css/**" />-->
<!--    <mvc:resources location="/images/" mapping="/images/**" />-->
<!--    <mvc:resources location="/js/" mapping="/js/**" />-->
    <!--开启SpringMVC注解的支持 @RequestMapping @RequestBody @ResponseBody-->
    <mvc:annotation-driven/>
</beans>

Controller

以前的java web项目,需要在web.xml中定义servlet,对应不同的请求,而在spring项目中,我们用controller定义了各种各样的servlet(当然不包括DispatcherServlet),那么controller是servlet吗?

  • servlet的本质其实也是一个java bean,controller是对servlet的封装,底层依旧是servlet。

src\main\java\com\vission\Controller\PersonController.java

package com.vission.Controller;
import com.vission.Service.IPersonService;
import com.vission.bean.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
@Controller
@RequestMapping("/person")
public class PersonController {
    @Autowired
    private IPersonService personService;
    @RequestMapping(path="/list",method = RequestMethod.GET)
    public String list(Model model){
        //显示所有的person数据
        List<Person> list = personService.findAll();
        System.out.println("list() list= "+list);
        //数据放在Model对象,由Model传给页面
        model.addAttribute("list",list);//参1 key  参2 value
        return "list";
    }
}

src\main\webapp\list.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table border="1px" width="100%">
    <c:forEach items="${list}" var="person">
        <tr>
            <td>${person.id}</td>
            <td>${person.name}</td>
            <td>${person.money}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

Spring整合Mybatis

配置Mybatis

  1. SqlMapConfig.xml
  • 指定四大信息:账号密码ip端口
  • 指定domain别名
  • 指定映射文件
  1. 编写测试
  • 保存
  • 查询

src\main\resources\SqlMapConfig.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>
    <!-- 别名  com.wzx.domain.Person  person-->
    <typeAliases>
        <package name="com.vission.bean"/>
    </typeAliases>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <!-- 核心 配置文件扫描到映射文件-->
    <mappers>
        <package name="com.vission.dao"/>
    </mappers>
</configuration>

src\main\java\com\vission\utils\MySeesionUtils.java

public class MySeesionUtils{
    private static SqlSessionFactory sessionFactory;
    //静态类只执行一次
    static{
        //创建SqlSessionFactory工厂类
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //载入配置文件
        InputStream inputStream = MySeesionUtils.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");
       //根据载入的配置文件创建SessionFactory
        sessionFactory = sqlSessionFactoryBuilder.build(inputStream);

    }
    private static ThreadLocal<SqlSession> map = new ThreadLocal<SqlSession>();

    public static SqlSession getSession() {
        SqlSession session = map.get();
        if(session != null){
            return session;
        }else {
            session = sessionFactory.openSession();
            map.set(session);
            return session;
        }
    }
    public static void commitAndClose() {
        //将来进行写操作,之后需要提交,我们定义的方法
        SqlSession session = map.get();
        if (session != null) {
            session.commit();//提交
            session.close();//释放
            //已经关闭的session不能留在local
            //所以要删除
            map.remove();
        }
    }
    public static void rollbackAndClose() {
        //将来进行写操作,之后需要提交,我们定义的方法
        SqlSession session = map.get();
        if (session != null) {
            session.rollback();//回滚
            session.close();//释放
            //已经关闭的session不能留在local
            //所以要删除
            map.remove();
        }
    }
    public static <T> T getMapper(Class clz) {
        return (T) getSession().getMapper(clz);
    }
}

src\test\java\TestMyBatis.java

import com.vission.Service.IPersonService;
import com.vission.bean.Person;
import com.vission.utils.MySeesionUtils;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:ApplicationContext.xml")//加载classpath
public class TestMyBatis {
    private MySeesionUtils mySeesionUtils;
    private static final Logger log = Logger.getLogger(TestPersonService.class.getName());
    @Autowired
    @Qualifier("personServiceImpl")
    IPersonService personService;
    @After
    public void commitAndClose(){
        mySeesionUtils.commitAndClose();
    }
    @Test
    public void addTest(){
        Person person = new Person("vission",200.00);
        personService.savePerson(person);
        log.info("运行addTest:加入成功");
    }
    @Test
    public void findTest(){
        List<Person> list = personService.findAll();
        log.info("运行findTest:查询结果为"+list);
    }
}

Spring整合MyBatis框架

(1)Spring整合MyBatis需要添加整合包
(2)什么是mybatis-spring
MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。它将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapper 和 SqlSession 并注入到 bean 中
不需要调用
MySessionUtils.java
session.getMapper(IpersonDao.class)
session.commit()
session.close()
pom.xml

<dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

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: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.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--   设置扫描包,包下设置注解@Service @Repository @Component @AutoWried-->
    <context:component-scan base-package="com.vission">
        <!--    由于springmvc的controller是由springmvc来扫描,需要将controller排除在外-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
<!--下列是整合MyBatis的配置文件-->
    <!-- 四大信息-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm"></property>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="user" value="root"></property>
        <property name="password" value=""></property>
    </bean>
    <!-- session工厂-->
    <bean id="sqlSessionFactory"  class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- com.vission.Person  person-->
        <property name="typeAliasesPackage" value="com.vission.bean"/>


    </bean>
    <!-- IPersonDao.xml  IPersonDao.java-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.vission.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
</beans>

我们调用dao对象的方法,需要修改一下

因为我们使用Spring整合Mybatis会优先走完ApplicationCotext.xml文档
用不到SqlConfig.xml,Spring会帮我们走完创建session的代码MySessionUtils里面的代码
同理我们MySessionUtils也用不到了
下列代码都用不上了

static{
        //创建SqlSessionFactory工厂类
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //载入配置文件
        InputStream inputStream = MySeesionUtils.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");
       //根据载入的配置文件创建SessionFactory
        sessionFactory = sqlSessionFactoryBuilder.build(inputStream);
    }

也就说dao可以通过Spring框架下注解直接获取dao.xml的信息不用再走MySessionUtils,SqlMapConfig.xml
MySessionUtils,SqlMapConfig.xml从这里都可以删掉了

@Service//通过扫描
public class PersonServiceImpl implements IPersonService {
//	  这是没用Spring创造Dao对象的代码,使用Spring后我们就不需要使用了工具类了
//    IPersonDao personDao = MySeesionUtils.getMapper(IPersonDao.class);
    @Autowired
    IPersonDao personDao;//直接通过注解获取对象
    private static final Logger log = Logger.getLogger(PersonServiceImpl.class.getName());
    @Override
    public List<Person> findAll() {
        List<Person> list = personDao.findAll();
        return list;
    }
    @Override
    public int  savePerson(Person person) {
        personDao.save(person);
        log.info("dao层添加的"+person);
        int code = 1;
        return code;
    }
}

src\test\java\TestDataSources.java

import com.vission.bean.Person;
import com.vission.dao.IPersonDao;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.sql.SQLException;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:ApplicationContext.xml")
public class TestDataSources {
    private static final Logger log = Logger.getLogger(TestDataSources.class.getName());
    @Autowired
    IPersonDao dao;//无缝整合MyBatis直接通过注解调用
    @Test
    public void test01() throws SQLException {
        List<Person> data = dao.findAll();
        System.out.println(data);
    }
    @Test
    public void test02() throws SQLException {
        Person p =  new Person("hello2020",200.00);
        dao.save(p);
    }
}

Spring管理事务***

  1. 表达式设置有哪些serivce方法需要事务管理
  2. 通知设置 增删改查业务方法 具体对应的事务
  3. 运行Test
   <!--配置Spring框架声明式事务管理-->
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>
    <!--配置AOP增强-->
    <aop:config>
        <aop:pointcut id="service" expression="execution(* com.vission.Service.ServiceImpl.*ServiceImpl.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="service"/>
    </aop:config>

src\main\java\com\vission\Service\IPersonService.java

public interface IPersonService {
    List<Person> findAll();

    int savePerson(Person person);

    int savePersonList(List<Person> list);
}

src\main\java\com\vission\Service\ServiceImpl\PersonServiceImpl.java

 @Override
    public int savePersonList(List<Person> list) {
        for (int i = 0; i < list.size(); i++) {
            personDao.save(list.get(i));
//            i = (0/1);
//            断电操作,展示Spring事务管理的代码,要么全部插入要么一个都插入不了
        }
        return 0;
    }

src\test\java\TestPersonService.java

 @Test
    public void addListTest(){
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("jack",100.00));
        personList.add(new Person("rose",200.00));
        personList.add(new Person("tony",300.00));
        log.info(personList);
        personService.savePersonList(personList);
    }

在这里插入图片描述

2020-10-18 14:59:51,393 1669   [           main] INFO               TestPersonService  - [Person{id=0, name='jack', money=100.0}, Person{id=0, name='rose', money=200.0}, Person{id=0, name='tony', money=300.0}]
2020-10-18 14:59:51,438 1714   [           main] INFO  l.AbstractPoolBackedDataSource  - Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge1jbadg8euzdhfaw60|24fcf36f, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge1jbadg8euzdhfaw60|24fcf36f, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/ssm, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值