Spring整合Mybatis案例(XML格式)

发布于:2023-01-01 ⋅ 阅读:(197) ⋅ 点赞:(0)

目录

Spring整合Mybatis案例(XML格式)

案例分析

基础准备工作

整合准备工作

整合工作


  • Spring整合Mybatis案例(XML格式)

  • 案例分析

  • 使用spring整合mybatis技术,完成账户模块(Account)的基础增删改查功能
  • 账户模块对应字段
  • 编号:id
  • 账户名:name
  • 余额:money
  • 非spring环境
  • 1.实体类与表
  • 2.业务层接口与实现
  • 3.数据层接口
  • 4.Mybatis核心配置
  • 5.Mybatis映射配置
  • 6.客户端程序测试功能
  • spring环境
  • 1.实体类与表
  • 2.业务层接口与实现(提供数据层接口的注入操作)
  • 3.数据层接口
  • 4.Mybatis核心配置(交给spring控制,该文件省略)
  • 5.Mybatis映射配置
  • 6.客户端程序测试功能(使用spring方式获取bean)
  • 7.Spring核心配置文件
  • 8.Druid数据源的应用(可选)
  • 9.Spring整合Mybatis
  • 基础准备工作

  • 环境准备
  • 1.导入Spring坐标,Mybatis坐标,MySQL坐标,Druid坐标
  • <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>org.example</groupId>
        <artifactId>springdemo2</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <properties>
            <maven.compiler.source>8</maven.compiler.source>
            <maven.compiler.target>8</maven.compiler.target>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.2</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.3.22</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.3.22</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.2.11</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.10</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.30</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.7</version>
            </dependency>
        </dependencies>
    
        <build>
            <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
                <plugins>
                    <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
                    <plugin>
                        <artifactId>maven-clean-plugin</artifactId>
                        <version>3.1.0</version>
                    </plugin>
                    <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
                    <plugin>
                        <artifactId>maven-resources-plugin</artifactId>
                        <version>3.0.2</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-compiler-plugin</artifactId>
                        <version>3.8.0</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>2.22.1</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-jar-plugin</artifactId>
                        <version>3.0.2</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-install-plugin</artifactId>
                        <version>2.5.2</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-deploy-plugin</artifactId>
                        <version>2.8.2</version>
                    </plugin>
                    <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
                    <plugin>
                        <artifactId>maven-site-plugin</artifactId>
                        <version>3.7.1</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-project-info-reports-plugin</artifactId>
                        <version>3.0.0</version>
                    </plugin>
                </plugins>
            </pluginManagement>
        </build>
    </project>
  • 业务类与接口准备
  • 2.创建数据库表,并制作相应的实体类Account
  • CREATE TABLE account(
    		id INT PRIMARY KEY auto_increment,
    		name VARCHAR(20),
    		money DOUBLE(10,2)
    );
    INSERT INTO account VALUES (NULL,'Mike',888.88),(NULL,'Jock',666.66);
  • package com.superdemo.domain;
    
    public class Account {
        private Integer id;
        private String name;
        private Double money;
    
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Double getMoney() {
            return money;
        }
        public void setMoney(Double money) {
            this.money = money;
        }
        @Override
        public String toString() {
            return "Account{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", money=" + money +
                    '}';
        }
    }
  • 3.定义业务层接口与数据层接口
  • package com.superdemo.dao;
    
    import com.superdemo.domain.Account;
    
    import java.util.List;
    
    public interface AccountDao {
    
        void save(Account account);
    
        void delete(Integer id);
    
        void update(Account account);
    
        List<Account> findAll();
    
        Account findByid(Integer id);
    }
  • package com.superdemo.service;
    
    import com.superdemo.domain.Account;
    
    import java.util.List;
    
    public interface AccountService {
    
        void save(Account account);
    
        void delete(Integer id);
    
        void update(Account account);
    
        List<Account> findAll();
    
        Account findByid(Integer id);
    }
  • 4.在业务层调用数据层接口,并实现业务方法的调用
  • package com.superdemo.service.impl;
    
    import com.superdemo.dao.AccountDao;
    import com.superdemo.domain.Account;
    import com.superdemo.service.AccountService;
    
    import java.util.List;
    
    public class AccountServiceImpl  implements AccountService {
        private AccountDao accountDao;
    
        public void setAccountDao(AccountDao accountDao) {
            this.accountDao = accountDao;
        }
    
        public void save(Account account){
            accountDao.save(account);
        }
    
        public void delete(Integer id){
            accountDao.delete(id);
        }
    
        public void update(Account account){
            accountDao.update(account);
        }
    
        public List<Account> findAll(){
            return accountDao.findAll();
        }
    
        public Account findByid(Integer id){
            return accountDao.findByid(id);
        }
    }
  • 基础配置文件
  • 5.jdbc.properties
  • jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/dp1?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useSSL=false
    jdbc.username=root
    jdbc.password=109923
  • 6.Mybatis映射配置文件
  • <?xml version="1.0" encoding="UTF-8" ?>
    <!--MyBatis的DTD约束-->
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <!--mapper:核心根标签;namespace属性:名称空间-->
    <mapper namespace="com.superdemo.dao.AccountDao">
        <!--select:查询功能的标签
            id属性:唯一标识
            resultType属性:指定结果映射对象类型
            parameterType属性:指定参数映射对象类型-->
        <select id="findAll" resultType="account">
            SELECT * FROM account
        </select>
        <select id="findByid" resultType="account" parameterType="int">
            SELECT * FROM account WHERE id = #{id}
        </select>
        <insert id="save" parameterType="account">
            INSERT INTO account(name, money) VALUES (#{name},#{money})
        </insert>
        <update id="update" parameterType="account">
            UPDATE account SET name = #{name},money = #{money} WHERE id = #{id}
        </update>
        <delete id="delete" parameterType="int">
            DELETE FROM account WHERE id = ${id}
        </delete>
    </mapper>
  • 整合准备工作

  • 1.spring配置文件,加上context命名空间,用于加载properties文件
  • 2.开启加载properties文件
  • 3.配置数据源Druid(备用)
  • 4.定义service层bean,注入dao层bean
  • 5.dao的bean无需定义,使用代理自动生成
  • 整合工作

  • 1.导入Spring整合Mybatis坐标
  • 2.将mybatis配置成spring管理的bean(SqlSessionFactoryBean)
    • 将原始配置文件中的所有项,转入到当前配置中
      • 数据源转换
      • 映射转换
  • 3.通过spring加载mybatis的映射配置文件到spring环境中
  • 4.设置类型别名
  • <?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:util="http://www.springframework.org/schema/util"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
            https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">
    
        <!--加载properties配置文件的信息-->
        <context:property-placeholder location="classpath:*.properties"/>
        <!--加载druid资源-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${jdbc.driver}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>
    
        <!--配置service作为spring的bean-->
        <bean id="accountService" class="com.superdemo.service.impl.AccountServiceImpl">
            <property name="accountDao" ref="accountDao"/>
        </bean>
    
        <!--spring整合mybatis后控制的创建连接用的对象-->
        <bean  class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="typeAliasesPackage" value="com.superdemo.domain"/>
        </bean>
        <!--加载mybatis映射配置的扫描,将其作为spring的bean进行管理-->
        <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.superdemo.dao"/>
        </bean>
    </beans>
  • 5.测试结果;使用spring环境加载业务层bean,执行操作
  • import com.superdemo.domain.Account;
    import com.superdemo.service.AccountService;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class App {
        public static void main(String[] args) {
            ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
            AccountService accountService = (AccountService) ctx.getBean("accountService");
            Account ac = accountService.findByid(2);
            System.out.println(ac);
    
            Account account = new Account();
            account.setName("Tom");
            account.setMoney(1314.52);
            accountService.save(account);
    
            ac = accountService.findByid(3);
            System.out.println(ac);
        }
    }
  • 小节:
  • 需要专用的spring整合mybatis的jar包
  • Mybatis核心配置文件消失
    • 环境environment转换成数据源对象
    • 映射Mapper扫描工作交由spring处理
    • 类型别名交由spring处理
  • 业务发起使用spring上下文对象获取对应的bean

网站公告

今日签到

点亮在社区的每一天
去签到