Spring+Mybatis整合+部分源码解析

目录

Spring+mybatis的整合步骤

ApplicationContext.xml配置文件图文解析

使用mybatis+spring实现增删改查

整合需要用到的配置文件

代码展示

实体类

mapper接口

service层

SqlSessionFactoryBean

MapperScannerConfigure

BasicDataSource


Spring+mybatis的整合步骤

1.引入依赖:在项目的构建管理工具中引入Spring和MyBatis的依赖

2.在ApplicationContext.xml配置dataSource数据源 比如连接驱动,连接数据源的url和连接数据库的用户名和密码

3.在ApplicationContext.xml配置文件中创建一个sqlSessionFactory对象,并将数据源和MyBatis的配置文件注入到该对象中

4.配置中使用MapperScannerConfigurer配置MyBatis的扫描器

5.定义Mapper接口,并在XML文件中编写对应的SQL语句

6.在Service层中注入Mapper接口的实例,并调用其方法进行数据库操作

ApplicationContext.xml配置文件图文解析

使用mybatis+spring实现增删改查

整合需要用到的配置文件

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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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">


   <!-- 1.引入properties文件-->
    <context:property-placeholder location="连接数据的配置文件(jdbc.proerities)"></context:property-placeholder>
   <!-- 2.配置数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--3.创建sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/> <!--name此处的name是指上面数据源的id-->
        <property name="configLocation" value="mybatis-config.xml"/> <!--value表示引入mybatis配置文件的路径-->
    </bean>
   <!-- MapperScannerConfigurer-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="mapper"></property>  mapper指代的写接口的那个包名类似于dao
    </bean>

    <!--注解实现依赖注入    下面标签是用于扫描包的注解-->
    <context:component-scan base-package="mapper,service"/>   扫描包

    <bean id="Myaspect" class="Aspect.MyAspect"></bean>  <!--引入切面类-->

    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>  <!--开启注解-->
</beans>
jdbc.properties连接数据库配置文件
==========================================================================================
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ketai?serverTimezone=GMT-8&useUnicode=true&character=utf-8
jdbc.username=root
jdbc.password=root
log4j.properties 日志文件
=========================================================================================
### 设置###
log4j.rootLogger = debug,stdout,logfile,error

### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 输出DEBUG 级别以上的日志到=log.log ###
log4j.appender.logfile = org.apache.log4j.DailyRollingFileAppender
### 这里不写路径就是在当前目录下创建日志文件 ###
log4j.appender.logfile.File = logs/log.log
log4j.appender.logfile.Append = true
log4j.appender.logfile.Threshold = DEBUG 
log4j.appender.logfile.layout = org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

###单独保存ERROR级别以上的异常到=error.log ###
log4j.appender.error = org.apache.log4j.DailyRollingFileAppender
### 这里不写路径就是在当前目录下创建日志文件 ###
log4j.appender.error.File =error.log 
log4j.appender.error.Append = true
log4j.appender.error.Threshold = ERROR 
log4j.appender.error.layout = org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
mybatis-config.xml 配置文件
=========================================================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--1.加载jdbc.properties配置文件-->
    <properties resource="jdbc.properties"></properties>

    <!--2.设置(日志 缓存 自动匹配(autoMappingBehavior))-->
    <settings>
        <setting  name="autoMappingBehavior" value="FULL" />
        <setting name="logImpl" value="LOG4J"/>
    </settings>

    <!--自动扫描pojo包下的所有类 默认别名就是类名 -->
    <typeAliases>
        <package name="pojo.TSupplier"/>
    </typeAliases>

    <!--将mapper文件引入 每增加一个就引入一个-->
    <mappers>
        <mapper resource="mapper/SupplierMapper.xml"/>

    </mappers>
</configuration>

代码展示

实体类

@Data 此注解可以自动生成我们的get 和set方法
==========================================================================================
package pojo;
import lombok.Data;

@Data
public class TSupplier {
  private Integer id;
  private String supCode;
  private String supName;
  private String supDesc;
  private String supContact;
  private String supPhone;
  private String supAddress;
  private String supFax;
  private Integer createdUserId;
  private java.sql.Timestamp createdTime;
  private Integer updatedUserId;
  private java.sql.Timestamp updatedTime;

}
mapper接口
@Repository 用于标注dao层
=========================================================================================
@Repository
public interface SupplierMapper {
    /**
     * 查询所有供货商信息
     * @param
     * @return
     */
    List<TSupplier>searchAll();

    /**
     * 删除所有供货商信息
     * @param id
     * @return
     */
    Integer deleteSupplier(Integer id);

    /**
     * 新增供货商信息
     * @param supplier
     * @return
     */
    Integer insertSupplier(TSupplier supplier);

    /**
     * 修改供货商信息
     * @param tSupplier
     * @return
     */
    Integer updateSupplier(TSupplier tSupplier);
}
service层
Service层的接口
=========================================================================================
public interface SupplierService {
    /**
     * 查询所有供货商信息
     * @return
     */
    List<TSupplier> searchAll();

    /**
     * 删除所有供货商信息
     * @param id
     * @return
     */
    Integer deleteSupplier(Integer id);

    /**
     * 新增供货商信息
     * @param supplier
     * @return
     */
    Integer insertSupplier(TSupplier supplier);

    /**
     * 修改供货商信息
     * @param tSupplier
     * @return
     */
    Integer updateSupplier(TSupplier tSupplier);
}

service层的实现类

service包中接口的实现类
=========================================================================================
@Service("SupplierService")
public class SupplierServiceImpl implements SupplierService{

    @Autowired
    private SupplierMapper supplierMapper;

    @Override
    public List<TSupplier> searchAll() {
        return supplierMapper.searchAll();
    }

    @Override
    public Integer deleteSupplier(Integer id) {
        return supplierMapper.deleteSupplier(id);
    }

    @Override
    public Integer insertSupplier(TSupplier supplier) {
        return supplierMapper.insertSupplier(supplier);
    }

    @Override
    public Integer updateSupplier(TSupplier tSupplier) {
        return supplierMapper.updateSupplier(tSupplier);
    }
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapper.SupplierMapper">

    <!--查询所有供货商信息-->
    <select id="searchAll" resultType="pojo.TSupplier">
        select *from t_supplier
    </select>

    <!--根据id删除供货商信息-->
    <delete id="deleteSupplier" parameterType="java.lang.Integer">
        delete  from t_supplier where id=#{id}
    </delete>

    <!--新增供货商信息-->
    <insert id="insertSupplier" parameterType="pojo.TSupplier" >
        INSERT INTO `t_supplier` (`id`, `supCode`, `supName`, `supDesc`, `supContact`, `supPhone`, `supAddress`, `supFax`, `createdUserId`, `createdTime`, `updatedUserId`, `updatedTime`)
        VALUES (#{id}, #{supCode}, #{supName}, #{supDesc},#{supContact}, #{supPhone},#{supAddress},#{supFax},#{createdUserId},#{createdTime},#{updatedUserId},#{updatedTime});
    </insert>

    <!--修改供货商信息-->
    <update id="updateSupplier" parameterType="pojo.TSupplier">
        UPDATE `t_supplier`
        <trim prefix="SET" suffixOverrides=",">
            <if test="supCode!=null">supCode=#{supCode},</if>
            <if test="supName!=null">supName=#{supName},</if>
            <if test="supDesc!=null">supDesc=#{supDesc},</if>
            <if test="supContact!=null">supContact=#{supContact},</if>
            <if test="supPhone!=null">supPhone=#{supPhone},</if>
            <if test="supAddress!=null">supAddress=#{supAddress},</if>
            <if test="supFax!=null">supFax=#{supFax},</if>
            <if test="createdUserId!=null">createdUserId=#{createdUserId},</if>
            <if test="createdTime!=null">createdTime=#{createdTime},</if>
            <if test="updatedUserId!=null">updatedUserId=#{updatedUserId},</if>
            <if test="updatedTime!=null">updatedTime=#{updatedTime},</if>
        </trim>
        where id=#{id}
    </update>
</mapper>

 测试类

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.TSupplier;
import service.SupplierService;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

public class TestSupplier {

    /**
     * 查询供应商信息
     */
    @Test
    public void SearchAll(){
        ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext.xml");
        SupplierService service=(SupplierService)context.getBean("SupplierService");
        List<TSupplier>list=service.searchAll();
        System.out.println(list);
    }

    /**
     * 删除供应商信息
     */
    @Test
    public void deleteSupplier(){
        ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext.xml");
        SupplierService service=(SupplierService)context.getBean("SupplierService");
        TSupplier tSupplier=new TSupplier();
        tSupplier.setId(12);
        int count=service.deleteSupplier(12);
        if(count>0){
            System.out.println("删除供货商信息成功!");
       }else{
            System.out.println("删除供货商信息失败!");
        }
    }

    /**
     * 新增供货商信息
     * @throws ParseException
     */
    @Test
     public void insertSupplier() throws ParseException {
        ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext.xml");
        SupplierService service=(SupplierService)context.getBean("SupplierService");
        TSupplier tSupplier=new TSupplier();
        tSupplier.setId(16);
        tSupplier.setSupCode("11");
        tSupplier.setSupName("222");
        tSupplier.setSupDesc("111");
        tSupplier.setSupContact("111");
        tSupplier.setSupPhone("222");
        tSupplier.setSupAddress("12");
        tSupplier.setSupFax("1");
        tSupplier.setCreatedUserId(1);
        SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        tSupplier.setCreatedTime(new Timestamp(format.parse("2001-05-27 14:13:24").getTime()));
        tSupplier.setUpdatedUserId(null);
        tSupplier.setUpdatedTime(null);
        int count=service.insertSupplier(tSupplier);
        if(count>0){
            System.out.println("新增供货商信息成功!");
        }else{
            System.out.println("新增供货商信息失败!");
        }
     }


    /**
     * 修改供应商信息
     * @throws ParseException
     */
    @Test
    public void UpdateSupplier() throws ParseException {
        ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext.xml");
        SupplierService service=(SupplierService)context.getBean("SupplierService");
        TSupplier tSupplier=new TSupplier();
        tSupplier.setId(16);
        tSupplier.setSupCode("哈哈哈哈");
        tSupplier.setSupName("222");
        tSupplier.setSupDesc("111");
        tSupplier.setSupContact("111");
        tSupplier.setSupPhone("222");
        tSupplier.setSupAddress("12");
        tSupplier.setSupFax("1");
        tSupplier.setCreatedUserId(1);
        SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        tSupplier.setCreatedTime(new Timestamp(format.parse("2001-05-27 14:13:24").getTime()));
        tSupplier.setUpdatedUserId(null);
        tSupplier.setUpdatedTime(null);
        int count=service.updateSupplier(tSupplier);
        if(count>0){
            System.out.println("修改供货商信息成功!");
        }else{
            System.out.println("修改供货商信息失败!");
        }
    }
}

源码解析

SqlSessionFactoryBean

SqlSessionFactoryBean:这是MyBatis框架与Spring框架的集成点。它是一个FactoryBean,用于创建SqlSessionFactory实例。SqlSessionFactory是MyBatis的核心类,用于创建SqlSession对象,从而执行SQL语句和管理事务。

public class SqlSessionFactoryBean extends org.mybatis.spring.SqlSessionFactoryBean {
    ... // 具体实现省略
}

MapperScannerConfigure

MapperScannerConfigure:这是MyBatis框架与Spring框架的集成点。它用于扫描指定包路径下的Mapper接口,并将其注册到Spring容器中,使得可以通过@Autowired或@Resource注解在代码中使用这些Mapper接口。

public class MapperScannerConfigure extends org.mybatis.spring.mapper.MapperScannerConfigurer {
    ... // 具体实现省略
}

BasicDataSource

BasicDataSource:这是Apache Commons DBCP连接池提供的一个数据源实现类,用于管理数据库连接。它可以配置数据库的连接URL、用户名、密码等信息,并提供了一些连接池的配置选项,比如最大连接数、最大等待时间等。

public class BasicDataSource extends org.apache.commons.dbcp2.BasicDataSource {
    ... // 具体实现省略
}

这些类和组件通常需要在Spring的配置文件中进行配置,示例如下:

<!-- 配置SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="com.example.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
</bean>

<!-- 配置MapperScannerConfigure -->
<bean class="com.example.MapperScannerConfigure">
    <property name="basePackage" value="com.example.mapper" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>

<!-- 配置BasicDataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/mydb" />
    <property name="username" value="root" />
    <property name="password" value="password" />
    <property name="initialSize" value="10" />
    <property name="maxTotal" value="100" />
    <property name="maxWaitMillis" value="5000" />
</bean>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值