栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

framework学习笔记day09---Spring-Mybatis整合、web

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

framework学习笔记day09---Spring-Mybatis整合、web

事务的回滚和不回滚的异常
  • 概述

    • 默认情况,遇到运行时异常回滚,遇到编译期异常不回滚。
    • rollbackFor设置需要回滚的异常
    • noRollbackFor设置不需要回滚的异常
  • 代码实现

    //@Transactional(rollbackFor = FileNotFoundException.class,noRollbackFor = ArithmeticException.class)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUser(User inputUser) throws Exception {
        System.out.println("UserServiceImpl addUser");
        userDao.addUser(inputUser);
        //运行时异常,会回滚
        System.out.println(1 / 0);
        //编译期异常
        //new FileInputStream("a");
    
    }
    
事务的隔离级别
  • 隔离级别

    • 读未提交:可以读取到事务未提交的数据
    • 读已提交:可以读取到事务中的数据前后不一致
    • 可重复读:查询事务中的数据(id=1)不存在,添加该数据(id=1)已存在
    • 串行化:效率低
  • 代码实现

    @Transactional(isolation = Isolation.REPEATABLE_READ)
    @Override
    public void addUser(User inputUser) throws Exception {
        System.out.println("UserServiceImpl addUser");
        userDao.addUser(inputUser);
        //运行时异常,会回滚
        System.out.println(1 / 0);
        //编译期异常
        //new FileInputStream("a");
    }
    
    @Transactional(isolation = Isolation.REPEATABLE_READ)
    @Override
    public List selectUserList() throws Exception {
        List userList = userDao.selectUserList();
        userList = userDao.selectUserList();
        return userList;
    }
    
事务传播行为(难点)
  • 概述
    • 规定管理员中的事务和协调员中的事务的关系。
  • 传播行为
事务传播行为演示(难点)
  • 需求

    • 进行转账业务时,进行日志记录。
  • REQUIRED

    //事务管理员
    @Transactional(isolation = Isolation.REPEATABLE_READ)
    @Override
    public List selectUserList() throws Exception {
        List userList = userDao.selectUserList();
        userList = userDao.selectUserList();
        return userList;
    }
    
    //事务协调员
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void addLog(String content) throws Exception {
        logDao.addLog(content);
        System.out.println(1 / 0);
    }
    
  • 注意事项

    • 传播行为应该在协调员进行设置.
Spring整合MyBatis概述
  • 概述
    • 将mybatis容器交给spring容器管理
  • 传统dao开发
    • dao接口 + dao实现子类 + mapper映射文件 + spring容器
    • 本质是将dao实现子类交给spring容器管理
  • 接口代理开发
    • dao接口 + mapper映射文件 + spring容器
    • 本质是将dao接口代理对象交给spring容器管理
Spring整合MyBatis之传统dao开发
  • 概述

    • 本质将dao实现子类交给Spring容器管理
  • 开发步骤

    • ①引入相关依赖
    • ②定义service及其实现子类
    • ③定义dao及其实现子类
    • ④编写spring-core.xml
      • 扫描注解
      • 将SqlSessionFactory对象交给Spring容器管理(使用SqlSessionFactoryBean),FactoryBean机制
        • 加载mybatis核心配置文件SqlMapConfig.xml
      • 将DruidDataSource对象交给Spring容器管理
    • ⑤代码测试
  • ①引入相关依赖

    
        8
        8
        4.13.2
        1.18.22
        5.3.13
        1.7
        1.2.8
        5.1.48
        3.5.7
        2.0.6
    
    
    
    
        
        
            junit
            junit
            ${junit.version}
            test
        
        
    
        
        
            org.projectlombok
            lombok
            ${lombok.version}
        
        
    
        
        
            org.springframework
            spring-core
            ${spring.version}
        
        
            org.springframework
            spring-beans
            ${spring.version}
        
        
            org.springframework
            spring-context
            ${spring.version}
        
        
            org.springframework
            spring-expression
            ${spring.version}
        
    
        
            org.springframework
            spring-test
            ${spring.version}
        
    
        
            org.springframework
            spring-jcl
            ${spring.version}
        
    
        
            org.springframework
            spring-aop
            ${spring.version}
        
    
        
            org.springframework
            spring-aspects
            ${spring.version}
        
    
        
            org.springframework
            spring-jdbc
            ${spring.version}
        
    
        
            org.springframework
            spring-tx
            ${spring.version}
        
        
    
    
        
        
            org.mybatis
            mybatis-spring
            ${mybatis-spring.version}
        
        
    
    
        
        
            org.mybatis
            mybatis
            ${mybatis.version}
        
        
    
        
        
            com.alibaba
            druid
            ${druid.version}
        
        
            mysql
            mysql-connector-java
            ${mysql.version}
        
        
    
    
    
  • ②定义service及其实现子类

    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserDao userDao;
    
        @Override
        public List selectUserList() throws Exception {
            return userDao.selectUserList();
        }
    }
    
  • ③定义dao及其实现子类

    @Repository
    public class UserDaoImpl implements UserDao {
    
        @Autowired
        private SqlSessionFactory sqlSessionFactory;
        @Override
        public List selectUserList() throws Exception {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            List userList = sqlSession.selectList("selectUserList");
            sqlSession.close();
            return userList;
        }
    
    }
    
  • ④编写spring-core.xml

    
    
    
        
        
    
        
            
            
            
        
    
        
        
            
            
            
            
        
    
    
    
  • ⑤代码测试

    public class UserController {
    
        public static void main(String[] args) throws Exception {
            //Spring容器初始化
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-core.xml");
    
            UserService userService = applicationContext.getBean(UserService.class);
            List userList = userService.selectUserList();
            System.out.println("userList = " + userList);
        }
    
    }
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:spring-core.xml")
    public class UserServiceTest {
    
        @Autowired
        private UserService userService;
        @Test
        public void selectUserList() throws Exception {
            List userList = userService.selectUserList();
            System.out.println("userList = " + userList);
        }
    }
    
  • 存在问题

    • 每次都需要通过SqlSessionFactory获取SqlSession对象并使用,结束后还得关闭,比较麻烦。
Spring整合MyBatis之传统dao开发优化
  • 概述

    • 使用SqlSessionDaoSupport类
  • 优化一

    @Repository
    public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
    
    
        //给UserDaoImpl的父类SqlSessionDaoSupport注入SqlSessionFactory对象
        @Autowired
        @Override
        public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
            super.setSqlSessionFactory(sqlSessionFactory);
        }
    
        @Override
        public List selectUserList() throws Exception {
            List userList = getSqlSession().selectList("selectUserList");
            return userList;
        }
    
    }
    
  • 优化二

    public class baseDao extends SqlSessionDaoSupport {
    
        @Autowired
        @Override
        public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
            super.setSqlSessionFactory(sqlSessionFactory);
        }
    }
    
    @Repository
    public class UserDaoImpl extends baseDao implements UserDao {
    
    
        @Override
        public List selectUserList() throws Exception {
            List userList = getSqlSession().selectList("selectUserList");
            return userList;
        }
    
    }
    
Spring整合MyBatis之接口代理
  • 概述

    • 本质将接口代理对象交给Spring容器管理
  • 开发步骤

    • ①定义service接口及其实现子类
    • ②定义dao接口
    • ③编写spring-core.xml
      • 扫描注解
      • 将dao接口代理类对象放入Spring容器(使用MapperFactoryBean)
      • 将SqlSessionFactory对象放入Spring容器(使用SqlSessionFactoryBean)
      • 将DruidDataSource对象放入到Spring容器
    • ④代码测试
  • ①定义service接口及其实现子类

  • ②定义dao接口

  • ③编写spring-core.xml

    
    
    
        
        
    
        
        
            
            
        
    
        
            
            
        
    
    
        
        
            
            
            
            
        
    
    
    
  • ④代码测试

  • 存在问题

    • ①在SqlMapConfig.xml文件中,不需要再通过标签加载映射文件
    • ②如果有100个mapper接口,那么就需要写100次将mapper接口代理类对象放入到Spring容器,过于麻烦。
Spring整合MyBatis之接口代理优化
  • 概述

    • 使用MapperScannerConfigurer
  • 代码实现

    
    
    
        
        
    
        
        
            
        
    
        
            
            
        
    
    
        
        
            
            
            
            
        
    
    
    
Spring整合MyBatis引入logback
  • 开发步骤

    • ①引入相关依赖
    • ②编写logback.xml
    • ③代码测试
  • ①引入相关依赖

    
        ch.qos.logback
        logback-classic
        1.2.7
    
    
        org.slf4j
        slf4j-api
        1.7.32
    
    
  • ②编写logback.xml

    
    
        
        
            
                
                
                [%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n
            
        
    
        
        
        
            
            
        
    
        
            
        
    
        
            
        
    
        
            
        
    
    
    
    
  • ③代码测试

    public class UserController {
    
        public static Logger logger = LoggerFactory.getLogger(UserController.class);
    
        public static void main(String[] args) throws Exception {
            //Spring容器初始化
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-core.xml");
    
            UserService userService = applicationContext.getBean(UserService.class);
            List userList = userService.selectUserList();
            logger.debug("userList : " + userList);
        }
    
    }
    
Spring整合MyBatis引入分页插件
  • 开发步骤

    • ①引入相关依赖
    • ②编写UserService
    • ③编写SqlMapConfig.xml
      • 配置PageInterceptor
    • ④代码测试
  • ①引入相关依赖

    
        com.github.pagehelper
        pagehelper
        5.2.1
    
    
  • ②编写UserService

    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserMapper userMapper;
    
    
        @Override
        public PageInfo selectUserListByPage(Integer currentPage, Integer pageSize) throws Exception {
            PageHelper.startPage(currentPage,pageSize);
            List userList = userMapper.selectUserList();
            return new PageInfo<>(userList);
        }
    }
    
  • ③编写SqlMapConfig.xml

    
        
            
        
    
    
Spring整合MyBatis引入事务管理
  • 开发步骤

    • ①编写spring-core.xml
      • 开启支持事务注解
    • ②编写UserService
      • 使用@Transactional注解
  • ①编写spring-core.xml

    
    
    
        
    
    
  • ②编写UserService

    @Transactional
    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        @Override
        public void addUser(User inputUser) throws Exception {
            userMapper.addUser(inputUser);
            System.out.println(1 / 0);
        }
    
        @Override
        public List selectUserList() throws Exception {
            return userMapper.selectUserList();
        }
    
        @Override
        public PageInfo selectUserListByPage(Integer currentPage, Integer pageSize) throws Exception {
            PageHelper.startPage(currentPage, pageSize);
            List userList = userMapper.selectUserList();
            return new PageInfo<>(userList);
        }
    }
    
Spring整合web环境第一版
  • 需求

    • 在JavaWeb程序中使用Spring容器(在UserServlet中使用Spring容器中的UserService对象)
  • 开发步骤

    • ①创建web项目
    • ②Spring整合MyBatis
    • ③编写UserController
  • ①创建web项目

  • ②Spring整合MyBatis

  • ③编写UserController

    @WebServlet("/selectUserList")
    public class UserController extends HttpServlet {
    
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //初始化Spring容器
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-core.xml");
            UserService userService = applicationContext.getBean(UserService.class);
            try {
                //使用Spring容器中的UserService对象
                List userList = userService.selectUserList();
                System.out.println("userList = " + userList);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
  • 存在问题

    • 发起一次请求UserController,就会创建一次Spring容器。
Spring整合web环境第二版
  • 概述

    • Spring容器只需要初始化一次,在后续的操作中都能够一直被使用。
  • 解决方案

    • 服务器启动,项目启动,就初始化Spring容器,使用ServletContextListener监听器;
  • 代码实现

    public class MyContextLoaderListener implements ServletContextListener {
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            //项目启动,初始化Spring容器
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-core.xml");
            sce.getServletContext().setAttribute("applicationContext", applicationContext);
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            //项目销毁
        }
    }
    
    
        com.atguigu.listenter.MyContextLoaderListener
    
    
    @WebServlet("/selectUserList")
    public class UserController extends HttpServlet {
    
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //初始化Spring容器
            //ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-core.xml");
            ApplicationContext applicationContext = (ApplicationContext) getServletContext().getAttribute("applicationContext");
            UserService userService = applicationContext.getBean(UserService.class);
            try {
                //使用Spring容器中的UserService对象
                List userList = userService.selectUserList();
                System.out.println("userList = " + userList);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
  • 存在问题

    • 存在"spring-core.xml"、"applicationContext"字符串硬编码问题。
Spring整合Web环境第三版
  • 概述

    • 将"spring-core.xml"设置web.xml中;
    • 将"applicationContext"放入到工具类中
  • 代码实现

    
        Archetype Created Web Application
    
        
        
            contextConfigLocation
            classpath:spring-core.xml
        
    
        
            com.atguigu.listenter.MyContextLoaderListener
        
    
    
    
    
    public class MyContextLoaderListener implements ServletContextListener {
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            //获取contextConfigLocation全局变量的值=spring-core.xml
            String contextConfigLocation = sce.getServletContext().getInitParameter("contextConfigLocation");
            //项目启动,初始化Spring容器
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext(contextConfigLocation);
            sce.getServletContext().setAttribute("applicationContext", applicationContext);
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            //项目销毁
        }
    }
    
    public class MyApplicationContextUtils {
    
    
        public static ApplicationContext getApplicationContext(ServletContext servletContext){
            return (ApplicationContext) servletContext.getAttribute("applicationContext");
        }
    
    }
    
    @WebServlet("/selectUserList")
    public class UserController extends HttpServlet {
    
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //初始化Spring容器
            //ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-core.xml");
            ApplicationContext applicationContext = MyApplicationContextUtils.getApplicationContext(getServletContext());
            UserService userService = applicationContext.getBean(UserService.class);
            try {
                //使用Spring容器中的UserService对象
                List userList = userService.selectUserList();
                System.out.println("userList = " + userList);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
  • 存在问题

    • 特别麻烦,不要自己写,Spring已经提供给你了!!
Spring整合Web环境终极版
  • 概述

    • Spring框架提供了ContextLoaderListener、WebApplicationContextUtils
  • 开发步骤

    • ①引入相关依赖
    • ②编写web.xml
      • 配置ContextLoaderListener
    • ③编写UserController
      • 使用WebApplicationContextUtils
  • ①引入相关依赖

    
        org.springframework
        spring-web
        ${spring.version}
    
    
    
        org.springframework
        spring-webmvc
        ${spring.version}
    
    
  • ②编写web.xml

    
        contextConfigLocation
        classpath:spring-core.xml
    
    
    
        org.springframework.web.context.ContextLoaderListener
    
    
  • ③编写UserController

    @WebServlet("/selectUserList")
    public class UserController extends HttpServlet {
    
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
            UserService userService = applicationContext.getBean(UserService.class);
            try {
                //使用Spring容器中的UserService对象
                List userList = userService.selectUserList();
                System.out.println("userList = " + userList);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
  • 注意事项
    t.ContextLoaderListener

     
  • ③编写UserController

    @WebServlet("/selectUserList")
    public class UserController extends HttpServlet {
    
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
            UserService userService = applicationContext.getBean(UserService.class);
            try {
                //使用Spring容器中的UserService对象
                List userList = userService.selectUserList();
                System.out.println("userList = " + userList);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
  • 注意事项

    • 在web项目中,引用第三方配置文件时,需要在前面加上"classpath",比如:classpath:SqlMapConfig.xml"、“classpath:jdbc.properties”
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/685173.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号