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);
    }
相关推荐
LiuYaoheng几秒前
【Android】View 的基础知识
android·java·笔记·学习
勇往直前plus8 分钟前
Sentinel微服务保护
java·spring boot·微服务·sentinel
星辰大海的精灵9 分钟前
SpringBoot与Quartz整合,实现订单自动取消功能
java·后端·算法
小鸡脚来咯11 分钟前
一个Java的main方法在JVM中的执行流程
java·开发语言·jvm
江团1io012 分钟前
深入解析三色标记算法
java·开发语言·jvm
天天摸鱼的java工程师20 分钟前
RestTemplate 如何优化连接池?—— 八年 Java 开发的踩坑与优化指南
java·后端
你我约定有三24 分钟前
java--泛型
java·开发语言·windows
知其然亦知其所以然31 分钟前
三分钟接入!SpringAI 玩转 Perplexity 聊天模型实战
后端·spring·langchain
杨杨杨大侠32 分钟前
第3章:实现基础事件总线
java·github·eventbus
杨杨杨大侠33 分钟前
第4章:添加注解支持
java·github·eventbus