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);
      }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值