当前位置: 首页 > article >正文

SSM框架探秘:Spring 整合 Mybatis 框架

搭建和测试 MyBatis 的环境:

  1. 编写 AccountMapper.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.qcby.mapper.AccountMapper">
        <select id="findAll" resultType="com.qcby.domain.Account">
            select * from account;
        </select>
    </mapper>
  2. 在 web 项目中编写 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>
    
        <!-- 配置环境 -->
        <environments default="mysql">
            <environment id="mysql">
                <transactionManager type="JDBC"></transactionManager>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql:///ssm"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                </dataSource>
            </environment>
        </environments>
    
        <!-- 加载映射配置文件 -->
        <mappers>
            <mapper resource="mapper/AccountMapper.xml"/>
        </mappers>
    
    </configuration>
  3. 在 AccountMapper 接口中编写方法:
    public interface AccountMapper {
    
        public List<Account> findAll();
    
    
    }
  4. 编写测试方法(此时数据库还没有数据):
    @Test
    public void run1() throws IOException {
        //加载配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
    
        //创建工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
    
        //创建 session
        SqlSession session = factory.openSession();
    
        //获取代理对象
        AccountMapper accountMapper = session.getMapper(AccountMapper.class);
    
        List<Account> all = accountMapper.findAll();
        all.forEach(System.out::println);
    
        //关闭资源
        session.close();
        in.close();
    }

Spring 整合 MyBatis 框架:

  1. 目的:
    1. 把 SqlMapConfig.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: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 -->
          <context:component-scan base-package="com.qcby.service"/>
      
          <!-- 配置 druid 连接池 -->
          <!-- 配置开源连接池 Druid 连接池 -->
          <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
              <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
              <property name="url" value="jdbc:mysql:///ssm"/>
              <property name="username" value="root"/>
              <property name="password" value="root"/>
          </bean>
      
          <!-- Spring 框架整合 MyBatis 框架 -->
          <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
              <!-- 注入连接池对象 -->
              <property name="dataSource" ref="dataSource"/>
              <!-- 加载映射配置文件 -->
              <property name="mapperLocations" value="classpath:mapper/*.xml"/>
          </bean>
      
          <!-- 把 mapper 对象存入 IOC 容器中 -->
          <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
              <property name="sqlSessionFactory" ref="sessionFactory"/>
              <property name="basePackage" value="com.qcby.mapper"/>
          </bean>
      
          <!-- 平台事务管理器 -->
          <bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
              <property name="dataSource" ref="dataSource"/>
          </bean>
      
          <!-- 配置事务的通知 -->
          <tx:advice id="txAdvice" transaction-manager="transactionManger">
              <tx:attributes>
                  <tx:method name="find*" read-only="true"/>
                  <tx:method name="*"/>
              </tx:attributes>
          </tx:advice>
      
          <!-- 配置事务的增强 -->
          <aop:config>
              <aop:advisor advice-ref="txAdvice" pointcut="execution(public * com.qcby.service.Impl.*ServiceImpl.*(..))"/>
          </aop:config>
      
      </beans>
  2. 在 AccountMapper 接口中添加 @Repository 注解:
  3. 在 service 中注入 mapper 对象,进行测试:
    1. service 层代码:
      @Service
      public class AccountServiceImpl implements AccountService {
      
          @Autowired
          private AccountMapper accountMapper;
      
          @Override
          public List<Account> findAll() {
              System.out.println("业务层逻辑:查询所有账号");
              List<Account> list = accountMapper.findAll();
              return list;
          }
      
          @Override
          public void save(Account account) {
              accountMapper.save(account);
          }
      }
    2.                                                                                                                层代码:
      @Controller
      @RequestMapping("/account")
      public class AccountController {
      
          @Autowired
          private AccountService accountService;
      
          /**
           * 查询所有方法
           */
          @RequestMapping("/findAll")
          public ModelAndView findAll(){
              System.out.println("表现层:查询所有账户");
              List<Account> list = accountService.findAll();
      
              for (Account a : list){
                  System.out.println(a);
              }
      
              ModelAndView mv = new ModelAndView();
              mv.setViewName("suc");
              return mv;
          }
      }
    3. 配置声明事务管理:
      <!-- 平台事务管理器 -->
      <bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
          <property name="dataSource" ref="dataSource"/>
      </bean>
      
      <!-- 配置事务的通知 -->
      <tx:advice id="txAdvice" transaction-manager="transactionManger">
          <tx:attributes>
              <tx:method name="find*" read-only="true"/>
              <tx:method name="*"/>
          </tx:attributes>
      </tx:advice>
      
      <!-- 配置事务的增强 -->
      <aop:config>
          <aop:advisor advice-ref="txAdvice" pointcut="execution(public * com.qcby.service.Impl.*ServiceImpl.*(..))"/>
      </aop:config>
    4. 表单代码:
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <body>
          <h2>Hello World!</h2>
      
          <a href="/account/findAll">查询所有</a>
      
          <h3>账号列表页面</h3>
          <a href="/account/findAll.do">查询所有</a>
          
          <h3>测试新增</h3>
          <form action="/account/save" method="post">
              姓名:<input type="text" name="name" /><br/>
              金额:<input type="text" name="money" /><br/>
              <input type="submit" value="保存" />
          </form>
      
      </body>
      </html>
    5. controller 代码:
      @Controller
      @RequestMapping("/account")
      public class AccountController {
      
          @Autowired
          private AccountService accountService;
      
          /**
           * 查询所有方法
           */
          @RequestMapping("/findAll")
          public ModelAndView findAll(){
              System.out.println("表现层:查询所有账户");
              List<Account> list = accountService.findAll();
      
              for (Account a : list){
                  System.out.println(a);
              }
      
              ModelAndView mv = new ModelAndView();
              mv.setViewName("suc");
              return mv;
          }
      
          @RequestMapping("/save")
          public String save(Account account){
              //调用 Service 层保存数据
              accountService.save(account);
      
              return "suc";
          }
      }
    6. service 代码:
      @Service
      public class AccountServiceImpl implements AccountService {
      
          @Autowired
          private AccountMapper accountMapper;
      
          @Override
          public List<Account> findAll() {
              System.out.println("业务层逻辑:查询所有账号");
              List<Account> list = accountMapper.findAll();
              return list;
          }
      
          @Override
          public void save(Account account) {
              accountMapper.save(account);
          }
      }
    7. mapper 代码:
      @Repository
      public interface AccountMapper {
      
          public List<Account> findAll();
      
      
          @Insert("insert into account (name,money) values (#{name},#{money})")
          void save(Account account);
      }

http://www.kler.cn/a/518250.html

相关文章:

  • Linux(Centos 7.6)命令详解:wc
  • linux查看上次开机时间
  • Effective C++ 规则46: 需要类型转换时,请为模板定义非成员函数
  • LVGL+FreeRTOS实战项目:智能健康助手(xgzp6847a篇)
  • 【算法工程】VS Code问题解决:Failed to parse remote port from server output
  • Java多线程的面试面试题及答案解析
  • Golang之Context详解
  • 【pytorch 】miniconda python3.11 环境安装pytorch
  • 无公网IP 外网访问媒体服务器 Emby
  • GS论文阅读--GeoTexDensifier
  • 如何实现分页相关功能
  • 比简单工厂更好的 - 工厂方法模式(Factory Method Pattern)
  • Lambda 表达式
  • 笔记《Effective Java》01: 创建和销毁对象
  • 软件测试丨消息管道(Kafka)测试体系
  • 电路研究9.2.1——合宙Air780EP音频的AT控制指令
  • 【工程篇】01:GPU可用测试代码
  • python学opencv|读取图像(四十四)原理探究:bitwise_and()函数实现图像按位与运算
  • UGUI判断点击坐标是否在UI内部,以及子UI内部
  • 运行虚幻引擎UE设置Visual Studio