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

搭建和测试 MyBatis 的环境:

编写 AccountMapper.xml 映射配置文件:
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>
在 web 项目中编写 SqlMapConfig.xml 的配置文件,编写核心配置文件
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>
在 AccountMapper 接口中编写方法:
java 复制代码
public interface AccountMapper {

    public List<Account> findAll();


}
编写测试方法(此时数据库还没有数据):
java 复制代码
@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. 把 SqlMapConfig.xml 配置文件中的内容配置到 applicationContext.xml 配置文件中:

    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>
在 AccountMapper 接口中添加 @Repository 注解:
在 service 中注入 mapper 对象,进行测试:
  1. service 层代码:

    java 复制代码
    @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. 层代码:

    java 复制代码
    @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. 配置声明事务管理:

    XML 复制代码
    <!-- 平台事务管理器 -->
    <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. 表单代码:

    XML 复制代码
    <%@ 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 代码:

    java 复制代码
    @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 代码:

    java 复制代码
    @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 代码:

    java 复制代码
    @Repository
    public interface AccountMapper {
    
        public List<Account> findAll();
    
    
        @Insert("insert into account (name,money) values (#{name},#{money})")
        void save(Account account);
    }
相关推荐
小梁不秃捏1 小时前
深入浅出Java虚拟机(JVM)核心原理
java·开发语言·jvm
yngsqq4 小时前
c# —— StringBuilder 类
java·开发语言
星星点点洲4 小时前
【操作幂等和数据一致性】保障业务在MySQL和COS对象存储的一致
java·mysql
xiaolingting5 小时前
JVM层面的JAVA类和实例(Klass-OOP)
java·jvm·oop·klass·instanceklass·class对象
风口上的猪20155 小时前
thingboard告警信息格式美化
java·服务器·前端
追光少年33226 小时前
迭代器模式
java·迭代器模式
超爱吃士力架7 小时前
MySQL 中的回表是什么?
java·后端·面试
扣丁梦想家7 小时前
设计模式教程:装饰器模式(Decorator Pattern)
java·前端·装饰器模式
drebander7 小时前
Maven 构建中的安全性与合规性检查
java·maven
drebander7 小时前
Maven 与 Kubernetes 部署:构建和部署到 Kubernetes 环境中
java·kubernetes·maven