【2020-06-22】Spring学习笔记Part-3

Jammm
2020-06-22 / 0 评论 / 1,260 阅读 / 正在检测是否收录...

Powered By JamPang

QQ:847885907

https://jampang.cn/

Spring笔记


其他部分

第一部分:点击访问
第二部分:点击访问


11、AOP

11.1、什么是AOP

AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

aop1.png

11.2、AOP在Spring中的作用

提供声明式事务;允许用户自定义切面

以下名词需要了解下:

  • 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 ....
  • 切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。
  • 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
  • 目标(Target):被通知对象。
  • 代理(Proxy):向目标对象应用通知之后创建的对象。
  • 切入点(PointCut):切面通知 执行的 “地点”的定义。
  • 连接点(JointPoint):与切入点匹配的执行点。

img

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:

aop3

11.3、使用Spring实现AOP

【重点】使用AOP织入,需要导入一个依赖包!

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.9.4</version>
</dependency>

==方式一:使用Spring的API接口【主要SpringAPI接口实现】==

实体类 service:

UserService.java

public interface UserService {
    public void add();
    public void delete();
    public void update();
    public void select();
}

UserServiceImpl.java

public class UserServiceImpl implements UserService {
    public void add() {
        System.out.println("增加了一个用户");
    }

    public void delete() {
        System.out.println("删除了一个用户");
    }

    public void update() {
        System.out.println("更新了一个用户");
    }

    public void select() {
        System.out.println("查询了一个用户");
    }
}

Log类:

Log.java

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class Log implements MethodBeforeAdvice {

    //method:要执行的目标对象的方法
    //objects:参数
    //o:目标对象
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println(o.getClass().getName()+"的"+method.getName()+"被执行了");
    }

}

AfterLog.java

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterLog implements AfterReturningAdvice {


    //o:returnValue
    //objects:args
    //o1:target
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("执行了"+method.getName()+"方法,返回结果为:"+o);
    }


}

xml: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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!-- 注册bean -->
    <bean id="userService" class="com.jam.service.UserServiceImpl"/>
    <bean id="log" class="com.jam.log.Log"/>
    <bean id="afterLog" class="com.jam.log.AfterLog"/>

    <!-- 方式一:使用原生Spring API接口 -->
    <!-- 配置aop 需要导入AOP的约束-->
    <aop:config>
        <!-- 切入点 expression:表达式, execution(要执行的位置) -->
        <!--
            execution(修饰符  返回值  报名.类名/接口名.方法(参数列表))
            (..):代表所有参数
            (*):代表一个个参数为任何值
            (*,String):代表第一个参数为任何值,第二个参数为String
         -->
        <aop:pointcut id="pointcut" expression="execution(* com.jam.service.UserServiceImpl.*(..))"/>

        <!-- 执行环绕增加 -->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>

    </aop:config>
</beans>

execution表达式详细:

execution()是最常用的切点函数,其语法如下所示:

整个表达式可以分为五个部分:

1、execution(): 表达式主体。

2、第一个号:表示返回类型, 号表示所有的类型。

3、包名:表示需要拦截的包名,后面的两个句点表示当前包和当前包的所有子包,com.sample.service.impl包、子孙包下所有类的方法。

4、第二个号:表示类名,号表示所有的类。

5、(..):最后这个星号表示方法名,号表示所有的方法,后面括弧里面表示方法的参数,两个句点表示任何参数

文章地址:https://blog.csdn.net/corbin_zhang/article/details/80576809

测试类

MyTest.java

import com.jam.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理的是接口
        UserService userService = (UserService) context.getBean("userService");

        userService.add();

    }
}

==方式二:自定义来实现AOP【主要是切面定义】==

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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!-- 注册bean -->
    <bean id="userService" class="com.jam.service.UserServiceImpl"/>
    <bean id="log" class="com.jam.log.Log"/>
    <bean id="afterLog" class="com.jam.log.AfterLog"/>
    
    <!-- 方式二:自定义类 -->
    <bean id="diy" class="com.jam.diy.DiyPointCut"/>

    <aop:config>
        <!-- 自定义切面:ref 要引用的类 -->
        <aop:aspect ref="diy">
            <!-- 切入点 -->
            <aop:pointcut id="point" expression="execution(* com.jam.service.UserServiceImpl.*(..))"/>

            <!-- 通知 -->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>
</beans>

==方式三:使用注解实现==

AnnotationPointCut.java

//方式三:使用注解方式实现AOP

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect //标注这个类是一个切面
public class AnnotationPointCut {

    @Before("execution(* com.jam.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("======方法执行前======");
    }

    @After("execution(* com.jam.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("======方法执行后======");
    }

    //在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点。
    @Around("execution(* com.jam.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint jp) throws Throwable {
        System.out.println("环绕前");

        //获取签名
        Signature signature = jp.getSignature();
        System.out.println("signature:"+signature);

        //执行方法
        Object proceed = jp.proceed();
        System.out.println("环绕后");

        System.out.println(proceed);
    }

}

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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!-- 注册bean -->
    <bean id="userService" class="com.jam.service.UserServiceImpl"/>
    <bean id="log" class="com.jam.log.Log"/>
    <bean id="afterLog" class="com.jam.log.AfterLog"/>

    <!-- 方式三:使用注解现实 -->
    <bean id="annotationPointCut" class="com.jam.diy.AnnotationPointCut"/>
    <!--开启注解支持    JDK(默认 expose-proxy="false")  cglib(expose-proxy="true")-->
    <aop:aspectj-autoproxy/>
</beans>

12、整合Mybatis

项目:spring-10-mybatis

12.1、回忆Mybaits

步骤:

  1. 导入相关jar包

    • junit
    • mybatis
    • mysql数据库

      /*
       Navicat MySQL Data Transfer
      
       Source Server         : 111
       Source Server Type    : MySQL
       Source Server Version : 50724
       Source Host           : localhost:3306
       Source Schema         : mybatis
      
       Target Server Type    : MySQL
       Target Server Version : 50724
       File Encoding         : 65001
      
       Date: 22/06/2020 17:14:45
      */
      
      SET NAMES utf8mb4;
      SET FOREIGN_KEY_CHECKS = 0;
      
      -- ----------------------------
      -- Table structure for blog
      -- ----------------------------
      DROP TABLE IF EXISTS `blog`;
      CREATE TABLE `blog`  (
        `id` int(50) NOT NULL COMMENT '博客id',
        `title` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '博客标题',
        `author` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '博客作者',
        `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创作时间',
        `views` int(30) NULL DEFAULT NULL COMMENT '浏览量',
        PRIMARY KEY (`id`) USING BTREE
      ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
      
      -- ----------------------------
      -- Records of blog
      -- ----------------------------
      INSERT INTO `blog` VALUES (1, 'Mybatis-08动态Sql-01', 'Jammm2', '2020-05-06 00:32:40', 9999);
      INSERT INTO `blog` VALUES (2, 'Mybatis-08动态Sql-02', 'Jam', '2020-05-06 00:32:40', 9999);
      
      -- ----------------------------
      -- Table structure for student
      -- ----------------------------
      DROP TABLE IF EXISTS `student`;
      CREATE TABLE `student`  (
        `id` int(10) NOT NULL,
        `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
        `tid` int(10) NULL DEFAULT NULL,
        PRIMARY KEY (`id`) USING BTREE
      ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
      
      -- ----------------------------
      -- Records of student
      -- ----------------------------
      INSERT INTO `student` VALUES (1, '小明', 1);
      INSERT INTO `student` VALUES (2, '小红', 1);
      INSERT INTO `student` VALUES (3, '小张', 1);
      INSERT INTO `student` VALUES (4, '小李', 1);
      INSERT INTO `student` VALUES (5, '小王', 1);
      
      -- ----------------------------
      -- Table structure for teacher
      -- ----------------------------
      DROP TABLE IF EXISTS `teacher`;
      CREATE TABLE `teacher`  (
        `id` int(10) NOT NULL,
        `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
        PRIMARY KEY (`id`) USING BTREE
      ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
      
      -- ----------------------------
      -- Records of teacher
      -- ----------------------------
      INSERT INTO `teacher` VALUES (1, '庞老师');
      
      -- ----------------------------
      -- Table structure for user
      -- ----------------------------
      DROP TABLE IF EXISTS `user`;
      CREATE TABLE `user`  (
        `id` int(10) NOT NULL AUTO_INCREMENT,
        `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
        `pwd` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
        PRIMARY KEY (`id`) USING BTREE
      ) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
      
      -- ----------------------------
      -- Records of user
      -- ----------------------------
      INSERT INTO `user` VALUES (1, 'jam', '123');
      INSERT INTO `user` VALUES (2, 'aaa', 'bbb');
      INSERT INTO `user` VALUES (3, 'mary', '345');
      INSERT INTO `user` VALUES (4, 'jeck', '456');
      INSERT INTO `user` VALUES (5, 'jackey', '567');
      
      SET FOREIGN_KEY_CHECKS = 1;
      
  • spring相关
  • aop植入
  • mybatis-spring【new】
<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <!-- Spring操作数据库的话。还需要一个Spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.5</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>
    
    <!--偷懒专用-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
    </dependencies>

<!-- build中配置resources,来防止我们资源导出失败的问题 -->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>
  1. 实体类

    User.java

    import lombok.Data;
    
    @Data
    public class User {
        private int id;
        private String name;
        private String pwd;
    }

    UserMapper.java

    import com.jam.pojo.User;
    
    import java.util.List;
    
    public interface UserMapper {
    
        public List<User> selectUser();
    
    }

    UserMapper.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    
    <mapper namespace="com.jam.mapper.UserMapper">
        <select id="selectUser" resultType="user">
            select * from user;
        </select>
    </mapper>
  1. 编写配置文件

    mybatis-config.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>
             <package name="com.jam.pojo"/>
         </typeAliases>
        
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="1234"/>
                </dataSource>
            </environment>
        </environments>
    
        <mappers>
            <mapper class="com.jam.mapper.UserMapper"/>
        </mappers>
    
    </configuration>
  1. 测试

    import com.jam.mapper.UserMapper;
    import com.jam.pojo.User;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    public class MyTest {
    
        @Test
        public void test() throws IOException {
            String resources = "mybatis-config.xml";
            InputStream in = Resources.getResourceAsStream(resources);
    
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
            SqlSession sqlSession = sessionFactory.openSession(true);
    
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = mapper.selectUser();
    
            for (User user : userList) {
                System.out.println(user);
            }
        }
    }

12.2、Mybatis-spring

  1. 编写数据源【各种xml文件】

    mybatis-config.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>
             <package name="com.jam.pojo"/>
         </typeAliases>
    
        <!--设置-->
    <!--    <settings>-->
    <!--        <setting name="" value=""/>-->
    <!--    </settings>-->
    
    </configuration>

    spring-dao.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:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    
    
        <!-- DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
            我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasource
        -->
    
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="1234"/>
    
        </bean>
    
    
        <!-- sqlSessionFactory -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <!--绑定Mybatis配置文件-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <property name="mapperLocations" value="classpath:com/jam/mapper/*.xml"/>
        </bean>
    
        <!--SqlSessionTemplate:就是我们使用的SqlSession-->
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
            <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
            <constructor-arg index="0" ref="sqlSessionFactory"/>
        </bean>
    
    </beans>

    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:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    
        <import resource="spring-dao.xml"/>
    
        <!---->
        <bean id="userMapper" class="com.jam.mapper.UserMapperImpl">
            <property name="sqlSession" ref="sqlSession"/>
        </bean>
    
    </beans>
  1. sqlSessionFactory【在spring-dao.xml中】
  2. sqlSessionTemplate

    UserMapperImpl.java

    package com.jam.mapper;
    
    import com.jam.pojo.User;
    import org.mybatis.spring.SqlSessionTemplate;
    
    import java.util.List;
    
    public class UserMapperImpl implements UserMapper{
    
        //我们的所有操作都使用sqlSession来执行,现在都使用SqlSessionTemplate
        private SqlSessionTemplate sqlSession;
    
        public void setSqlSession(SqlSessionTemplate sqlSession) {
            this.sqlSession = sqlSession;
        }
    
        public List<User> selectUser() {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            return mapper.selectUser();
        }
    }
    
  1. 需要给接口加实现类【在mybatis-config.xml中】
  2. 将自己写的实现类,注入到Spring中【在applicationContext.xml中】
  3. 测试类

    MyTest.java

     @Test
    public void test() throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }
    }

12.3、SqlSessionDaoSupport

UserMapperImpl2.java

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {

    public List<User> selectUser() {
//        SqlSession sqlSession = getSqlSession();
//        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//        return mapper.selectUser();
        return getSqlSession().getMapper(UserMapper.class).selectUser();
    }
}

applicationContext.xml

<bean id="userMapper2" class="com.jam.mapper.UserMapperImpl2">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

13、声明式事务

项目:spring-11-transaction

13.1、回顾事务

  • 把一组业务当成一个业务来做;要么成功,要么失败
  • 事务在项目开发中十分重要,涉及到数据的一致性问题,不能马虎。
  • 确保完整性和一致性。

事务ACID原则:

  • 原子性
  • 一致性
  • 隔离性

    • 多个业务可能操作同一个资源,防止数据损坏
  • 持久性

    • 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写到存储器中。

13.2、Spring中的事务管理

  • 声明式事务:AOP
  • 编程时事务:需要在代码中,进行事务的管理

为什么要事务?

  • 如果不配置书屋,可能存在数据提交不一致的情况。
  • 如果我们不在Spring中去配置声明事务,我们就需要在代码中手动配置事务。
  • 配置在项目的开发中十分重要,设计到数据的一致性和完整性问题。

pojo类

User.java

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;

}

Mapper

UserMapper.java

public interface UserMapper {

    public List<User> selectUser();

    //添加一个用户
    public int addUser(User user);

    //删除一个用户
    public int deleteUser(int id);

}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="com.jam.mapper.UserMapper">
    <select id="selectUser" resultType="user">
        select * from user;
    </select>

    <insert id="addUser" parameterType="user">
        insert into user (id,name,pwd) values (##{id},##{name},##{pwd})
    </insert>

    <!--这里我们这里故意写错-->
    <delete id="deleteUser" parameterType="int">
        deletes from user where id=##{id}
    </delete>
</mapper>

UserMapperImpl.java

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{


    public List<User> selectUser() {

        User user = new User(6,"aa","aaa");

        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);

        mapper.addUser(user);
        mapper.deleteUser(5);

        return mapper.selectUser();
    }

    public int addUser(User user) {
        return getSqlSession().getMapper(UserMapper.class).addUser(user);
    }

    public int deleteUser(int id) {
        return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
    }
}

xml配置

mybatis-config.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>
         <package name="com.jam.pojo"/>
     </typeAliases>


</configuration>

spring-dao.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        ">



    <!-- DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid
        我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasource
    -->

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="1234"/>

    </bean>


    <!-- sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--绑定Mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/jam/mapper/*.xml"/>
    </bean>

    <!--SqlSessionTemplate:就是我们使用的SqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <!--配置事务声明-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--结合AOP进行事务-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--配置事务的传播特性:new  propagation-->
        <tx:attributes>
            <tx:method name="add"/>
            <tx:method name="delete"/>
            <tx:method name="update"/>
            <tx:method name="query"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.jam.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

</beans>

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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <import resource="spring-dao.xml"/>

    <bean id="userMapper" class="com.jam.mapper.UserMapperImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

</beans>

Test类

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);

        List<User> userList = userMapper.selectUser();
        for (User user : userList) {
            System.out.println(user);
        }

    }
}

完结

本文共 1444 个字数,平均阅读时长 ≈ 4分钟
0

打赏

海报

正在生成.....

评论 (0)

取消
2019 - 2022 © • Jammmの日常 • 赣ICP备20003066号-1