【Spring】(六)MyBatis与Spring的整合步骤(含详细整合案例)

简介: 【Spring】(六)MyBatis与Spring的整合步骤(含详细整合案例)

MyBatis与Spring的整合


第一步:导入jar包


20191106213117180.png


包含spring、mybatis、mybatis-spring的jar包,如有需要的朋友可以直接留言哦~


第二步:创建两个Source Folder文件夹( resources和test)


20191106213507636.png


第三步:创建实体类


20191106213644502.png


第四步:创建dao层接口、实现类、mapper映射文件


1、BillMapper接口

package cn.smbms.dao.bill;
import java.util.List;
import cn.smbms.pojo.Bill;
import org.apache.ibatis.annotations.Param;
public interface BillMapper {
  /**
  * 增加订单
  * @param bill
  * @return
  * @throws Exception
  */
  public int add(Bill bill)throws Exception;
  /**
  * 通过查询条件获取供应商列表-模糊查询-getBillList
  * @return
  * @throws Exception
  */
  public List<Bill> getBillList(@Param(value = "providerId") String providerId,
          @Param(value = "productName") String productName,
          @Param(value = "isPayment") String isPayment)throws Exception;
  /**
  * 通过delId删除Bill
  * @param delId
  * @return
  * @throws Exception
  */
  public int deleteBillById(String delId)throws Exception;
  /**
  * 通过billId获取Bill
  * @param id
  * @return
  * @throws Exception
  */
  public Bill getBillById(String id)throws Exception;
  /**
  * 修改订单信息
  * @param bill
  * @return
  * @throws Exception
  */
  public int modify(Bill bill)throws Exception;
  /**
  * 根据供应商ID查询订单数量
  * @param providerId
  * @return
  * @throws Exception
  */
  public int getBillCountByProviderId(String providerId)throws Exception;
}


2、BillMapperImpl实现类

package cn.smbms.dao.bill;
import cn.smbms.pojo.Bill;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class BillMapperImpl implements BillMapper {
    ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext.xml");
    BillMapper mapper= (BillMapper) context.getBean("billMapper");
    @Override
    public int add(Bill bill) throws Exception {
        return mapper.add(bill);
    }
    @Override
    public List<Bill> getBillList(String providerId, String productName, String isPayment) throws Exception {
        return mapper.getBillList(providerId, productName, isPayment);
    }
    @Override
    public int deleteBillById(String delId) throws Exception {
        return mapper.deleteBillById(delId);
    }
    @Override
    public Bill getBillById(String id) throws Exception {
        return mapper.getBillById(id);
    }
    @Override
    public int modify(Bill bill) throws Exception {
        return mapper.modify(bill);
    }
    @Override
    public int getBillCountByProviderId(String providerId) throws Exception {
        return mapper.getBillCountByProviderId(providerId);
    }
}


3、BillMapper.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="cn.smbms.dao.bill.BillMapper">
    <insert id="add" parameterType="cn.smbms.pojo.Bill">
        insert into smbms_bill (billCode, productName, productDesc,
         productUnit, productCount, totalPrice, isPayment, createdBy,
          creationDate, modifyBy, modifyDate, providerId)
          values (#{billCode},#{productName},#{productDesc},#{productUnit},#{productCount},
          #{totalPrice},#{isPayment},#{createdBy},#{creationDate},#{modifyBy},
          #{modifyDate},#{providerId})
    </insert>
    <select id="getBillList" resultType="cn.smbms.pojo.Bill">
        select b.*,p.proName as providerName
        from smbms_bill b, smbms_provider p
        where b.providerId = p.id
        <if test="providerId!=null">
            and providerId=#{providerId}
        </if>
        <if test="providerId!=null">
            and productName like CONCAT('%',#{productName},'%')
        </if>
        <if test="providerId!=null">
            and isPayment=#{isPayment}
        </if>
    </select>
    <delete id="deleteBillById" parameterType="int">
        delete from smbms_bill where id=#{id}
    </delete>
    <select id="getBillById" resultType="cn.smbms.pojo.Bill">
        select b.*,p.proName as providerName
        from smbms_bill b, smbms_provider p
  where b.providerId = p.id and b.id=#{id}
    </select>
    <update id="modify" parameterType="cn.smbms.pojo.Bill">
        update smbms_bill set billCode=#{billCode}, productName=#{productName}, productDesc=#{productDesc},
        productUnit=#{productUnit},productCount=#{productCount},totalPrice=#{totalPrice},
  isPayment=#{isPayment},providerId=#{providerId},modifyBy=#{modifyBy},modifyDate=#{modifyDate}
  where id = #{id}
    </update>
    <select id="getBillCountByProviderId" resultType="int">
        select count(1) as billCount
        from smbms_bill
        where providerId = #{providerId}
    </select>
</mapper>


第五步:创建service层接口、实现类


1、BillService接口

package cn.smbms.service.bill;
import java.util.List;
import cn.smbms.pojo.Bill;
public interface BillService {
  /**
  * 增加订单
  * @param bill
  * @return
  */
  public boolean add(Bill bill);
  /**
  * 通过条件获取订单列表-模糊查询-billList
  * @param bill
  * @return
  */
  public List<Bill> getBillList(Bill bill);
  /**
  * 通过billId删除Bill
  * @param delId
  * @return
  */
  public boolean deleteBillById(String delId);
  /**
  * 通过billId获取Bill
  * @param id
  * @return
  */
  public Bill getBillById(String id);
  /**
  * 修改订单信息
  * @param bill
  * @return
  */
  public boolean modify(Bill bill);
}


2、BillServiceImpl实现类

package cn.smbms.service.bill;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import cn.smbms.dao.BaseDao;
import cn.smbms.dao.bill.BillMapper;
import cn.smbms.dao.bill.BillMapperImpl1;
import cn.smbms.pojo.Bill;
public class BillServiceImpl implements BillService {
  private BillMapper billMapper;
  public BillServiceImpl(){
  billMapper = new BillMapperImpl1();
  }
  @Override
  public boolean add(Bill bill) {
  // TODO Auto-generated method stub
  boolean flag = false;
  Connection connection = null;
  try {
    connection = BaseDao.getConnection();
    connection.setAutoCommit(false);//开启JDBC事务管理
    if(billMapper.add(bill) > 0)
    flag = true;
    connection.commit();
  } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    try {
    System.out.println("rollback==================");
    connection.rollback();
    } catch (SQLException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    }
  }finally{
    //在service层进行connection连接的关闭
    BaseDao.closeResource(connection, null, null);
  }
  return flag;
  }
  @Override
  public List<Bill> getBillList(Bill bill) {
  // TODO Auto-generated method stub
  Connection connection = null;
  List<Bill> billList = null;
  System.out.println("query productName ---- > " + bill.getProductName());
  System.out.println("query providerId ---- > " + bill.getProviderId());
  System.out.println("query isPayment ---- > " + bill.getIsPayment());
  try {
    connection = BaseDao.getConnection();
    billList = billMapper.getBillList("","","");
  } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }finally{
    BaseDao.closeResource(connection, null, null);
  }
  return billList;
  }
  @Override
  public boolean deleteBillById(String delId) {
  // TODO Auto-generated method stub
  Connection connection = null;
  boolean flag = false;
  try {
    connection = BaseDao.getConnection();
    if(billMapper.deleteBillById(delId) > 0)
    flag = true;
  } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }finally{
    BaseDao.closeResource(connection, null, null);
  }
  return flag;
  }
  @Override
  public Bill getBillById(String id) {
  // TODO Auto-generated method stub
  Bill bill = null;
  Connection connection = null;
  try{
    connection = BaseDao.getConnection();
    bill = billMapper.getBillById(id);
  }catch (Exception e) {
    // TODO: handle exception
    e.printStackTrace();
    bill = null;
  }finally{
    BaseDao.closeResource(connection, null, null);
  }
  return bill;
  }
  @Override
  public boolean modify(Bill bill) {
  // TODO Auto-generated method stub
  Connection connection = null;
  boolean flag = false;
  try {
    connection = BaseDao.getConnection();
    if(billMapper.modify(bill) > 0)
    flag = true;
  } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }finally{
    BaseDao.closeResource(connection, null, null);
  }
  return flag;
  }
}


第六步:在resource文件夹中编写mybatis-config.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>
 <!--这里可以加入类型别名,其他配置已经转到Spring中-->
</configuration>


第七步:在resource文件夹中编写applicationContext.xml


因为测试了三种MyBatis与Spring整合的方法,所以配置文件显得很冗长,请注意注掉的部分代码!


最终采用的是org.mybatis.spring.mapper.MapperScannerConfigurer,这也是在实际工作情况中使用较多的一种整合方式。

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--引入properties文件-->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>classpath:database.properties</value>
        </property>
    </bean>
    <!--配置DataSource-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${pwd}"/>
    </bean>
    <!--配置SqlSessionFactoryBean-->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--引用数据源组件-->
        <property name="dataSource" ref="dataSource"/>
        <!--引用MyBatis配置文件中的配置,必须有,里面的内容可以为空-->
        <!-- 有关mybatis的特性配置可以写在该文件中,比如插件,setting属性等 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 指定mapper文件位置,当不指定时mapper映射文件默认与接口在一个包下 -->
        <property name="mapperLocations" value="classpath*:cn/smbms/dao/**/*.xml"/>
    </bean>
    <!--
         Mybatis-Spring为我们提供了一个实现了SqlSession接口的SqlSessionTemplate类,它是线程安全的,
         可以被多个Dao同时使用。
         同时它还跟Spring的事务进行了关联,确保当前被使用的SqlSession是一个已经和Spring的事务进行绑定了的。
         而且它还可以自己管理Session的提交和关闭。当使用了Spring的事务管理机制后,
         SqlSession还可以跟着Spring的事务一起提交和回滚。
      -->
    <!--配置SqlSessionTemplate-->
    <bean id="session" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="factory"></constructor-arg>
    </bean>
    <!--配置实现类-->
    <!--<bean id="userMapper" class="cn.smbms.dao.user.UserMapperImpl">-->
        <!--<property name="session" ref="session"/>-->
        <!--<property name="session" ref="session"></property>-->
    <!--</bean>-->
    <!--直接配置接口-->
    <!--<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">-->
        <!--<property name="mapperInterface" value="cn.smbms.dao.user.UserMapper"/>-->
        <!--<property name="sqlSessionFactory" ref="factory"/>-->
    <!--</bean>-->
    <!--直接配置接口-->
    <!--<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">-->
        <!--<property name="basePackage" value="cn.smbms.dao"/>-->
        <!--<property name="sqlSessionFactoryBeanName" value="factory"/>-->
    <!--</bean>-->
    <!--配置扫描包--> <!-- 代理dao层接口实现类 -->
    <bean id="mapConf" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.smbms.dao"/>
    </bean>
    <!--配置扫描注解定义的业务Bean-->
    <context:component-scan base-package="cn.smbms.service"/>
    <!--<context:annotation-config></context:annotation-config>-->
    <!--配置事务管理bean-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置对应的方法和事务传播机制-->
    <!--<tx:advice id="txAdvice" transaction-manager="txManager">-->
        <!--<tx:attributes>-->
            <!--<tx:method name="updateTian*" timeout="-1"/>-->
            <!--<tx:method name="*" propagation="REQUIRED"/>-->
        <!--</tx:attributes>-->
    <!--</tx:advice>-->
    <!--配置定义切面-->
    <!--<aop:config>-->
        <!--&lt;!&ndash;定义切入点&ndash;&gt;-->
        <!--<aop:pointcut id="serviceMethod" expression="execution(public int updateTian())"/>-->
        <!--&lt;!&ndash;将事务增强与切入点组合&ndash;&gt;-->
        <!--<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>-->
    <!--</aop:config>-->
    <!--注解-->
    <tx:annotation-driven transaction-manager="txManager"/>
</beans>


第八步:在test文件夹中编写测试方法


一个简单的快捷键:ctrl+shift+T ,我们创建BillMapperImpl类的测试方法,对功能模块进行测试。

package cn.smbms.dao.bill;
import cn.smbms.pojo.Bill;
import org.apache.log4j.Logger;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.Date;
import static org.junit.Assert.*;
public class BillMapperImplTest {
    Logger logger=Logger.getLogger(BillMapperImplTest.class);
    BillMapper mapper=new BillMapperImpl();
    @Test
    public void add() {
        Bill bill=new Bill();
        bill.setBillCode("BILL2016_020");
        bill.setProductName("鞭炮");
        bill.setProductDesc("烟花炮竹");
        bill.setProductUnit("箱");
        bill.setProductCount(BigDecimal.valueOf(500));
        bill.setTotalPrice(BigDecimal.valueOf(1000));
        bill.setIsPayment(1);
        bill.setCreatedBy(1);
        bill.setCreationDate(new Date());
        bill.setProviderId(13);
        try {
            int row=mapper.add(bill);
            if (row>0){
                logger.info("成功插入一条商品信息");
            }else {
                logger.info("插入不成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Test
    public void getBillList() {
        try {
            logger.info(mapper.getBillList("6","油","2"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Test
    public void deleteBillById() {
        try {
            int row=mapper.deleteBillById("26");
            if (row>0){
                logger.info("删除成功");
            }else {
                logger.info("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Test
    public void getBillById() {
        try {
            logger.info(mapper.getBillById("1"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Test
    public void modify() {
        Bill bill=new Bill();
        bill.setId(14);
        bill.setBillCode("151654");
        bill.setProductName("西北香米");
        try {
            int row=mapper.modify(bill);
            if (row>0){
                logger.info("成功修改一条商品信息");
            }else {
                logger.info("修改不成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Test
    public void getBillCountByProviderId() {
        try {
            logger.info("查询供应商数"+mapper.getBillCountByProviderId("1"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


以上,便是采用MapperScannerConfigurer方式进行的MyBatis与Spring的整合!


目录
相关文章
|
19天前
|
SQL Java 数据库连接
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
110 29
|
30天前
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
56 2
|
1月前
|
SQL JavaScript Java
Spring Boot 3 整合 Mybatis-Plus 实现数据权限控制
本文介绍了如何在Spring Boot 3中整合MyBatis-Plus实现数据权限控制,通过使用MyBatis-Plus提供的`DataPermissionInterceptor`插件,在不破坏原有代码结构的基础上实现了细粒度的数据访问控制。文中详细描述了自定义注解`DataScope`的使用方法、`DataPermissionHandler`的具体实现逻辑,以及根据用户的不同角色和部门动态添加SQL片段来限制查询结果。此外,还展示了基于Spring Boot 3和Vue 3构建的前后端分离快速开发框架的实际应用案例,包括项目的核心功能模块如用户管理、角色管理等,并提供Gitee上的开源仓库
247 11
|
2月前
|
缓存 Java 数据库连接
深入探讨:Spring与MyBatis中的连接池与缓存机制
Spring 与 MyBatis 提供了强大的连接池和缓存机制,通过合理配置和使用这些机制,可以显著提升应用的性能和可扩展性。连接池通过复用数据库连接减少了连接创建和销毁的开销,而 MyBatis 的一级缓存和二级缓存则通过缓存查询结果减少了数据库访问次数。在实际应用中,结合具体的业务需求和系统架构,优化连接池和缓存的配置,是提升系统性能的重要手段。
147 4
|
2月前
|
SQL Java 数据库连接
spring和Mybatis的各种查询
Spring 和 MyBatis 的结合使得数据访问层的开发变得更加简洁和高效。通过以上各种查询操作的详细讲解,我们可以看到 MyBatis 在处理简单查询、条件查询、分页查询、联合查询和动态 SQL 查询方面的强大功能。熟练掌握这些操作,可以极大提升开发效率和代码质量。
166 3
|
3月前
|
Java 数据库连接 数据库
spring和Mybatis的逆向工程
通过本文的介绍,我们了解了如何使用Spring和MyBatis进行逆向工程,包括环境配置、MyBatis Generator配置、Spring和MyBatis整合以及业务逻辑的编写。逆向工程极大地提高了开发效率,减少了重复劳动,保证了代码的一致性和可维护性。希望这篇文章能帮助你在项目中高效地使用Spring和MyBatis。
112 1
|
3月前
|
Java Maven Spring
Spring 小案例体验创建对象的快感
本文介绍了如何在IDEA中创建一个Spring项目,包括项目创建、配置pom.xml文件以引入必要的依赖、编写实体类HelloSpring及其配置文件applicationContext.xml,最后通过测试类TestHelloSpring展示如何使用Spring的bean创建对象并调用方法。
44 0
|
前端开发 druid Java
SpringBoot 整合 MyBatis
文本是基于MVC前后端分离模式的一个SpringBoot整合MyBatis的项目,不过没有用到前端页面,使用了更方便的Apifox请求工具。SpringBoot+MyBatis使用起来更方便,更舒服。掌握SpingBoot整合MyBatis,要比Spring整合简单的多,少了很多繁琐的配置。......
242 0
SpringBoot 整合 MyBatis
|
XML 数据可视化 Java
Springboot整合mybatis(注解而且能看明白版本)
这篇文章主要讲解Springboot整合Mybatis实现一个最基本的增删改查功能,整合的方式有两种一种是注解形式的,也就是没有Mapper.xml文件,还有一种是XML形式的,我推荐的是使用注解形式,为什么呢?因为更加的简介,减少不必要的错误。
602 0
Springboot整合mybatis(注解而且能看明白版本)
|
Java 数据库连接 数据库
SpringBoot整合Mybatis
SpringBoot整合Mybatis