【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的整合!


目录
相关文章
|
8月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
453 0
|
5月前
|
Java 数据库连接 数据库
Spring boot 使用mybatis generator 自动生成代码插件
本文介绍了在Spring Boot项目中使用MyBatis Generator插件自动生成代码的详细步骤。首先创建一个新的Spring Boot项目,接着引入MyBatis Generator插件并配置`pom.xml`文件。然后删除默认的`application.properties`文件,创建`application.yml`进行相关配置,如设置Mapper路径和实体类包名。重点在于配置`generatorConfig.xml`文件,包括数据库驱动、连接信息、生成模型、映射文件及DAO的包名和位置。最后通过IDE配置运行插件生成代码,并在主类添加`@MapperScan`注解完成整合
1001 1
Spring boot 使用mybatis generator 自动生成代码插件
|
5月前
|
Java 数据库连接 API
Java 对象模型现代化实践 基于 Spring Boot 与 MyBatis Plus 的实现方案深度解析
本文介绍了基于Spring Boot与MyBatis-Plus的Java对象模型现代化实践方案。采用Spring Boot 3.1.2作为基础框架,结合MyBatis-Plus 3.5.3.1进行数据访问层实现,使用Lombok简化PO对象,MapStruct处理对象转换。文章详细讲解了数据库设计、PO对象实现、DAO层构建、业务逻辑封装以及DTO/VO转换等核心环节,提供了一个完整的现代化Java对象模型实现案例。通过分层设计和对象转换,实现了业务逻辑与数据访问的解耦,提高了代码的可维护性和扩展性。
227 1
|
4月前
|
SQL Java 数据库连接
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
155 0
|
5月前
|
SQL Java 数据库
解决Java Spring Boot应用中MyBatis-Plus查询问题的策略。
保持技能更新是侦探的重要素质。定期回顾最佳实践和新技术。比如,定期查看MyBatis-Plus的更新和社区的最佳做法,这样才能不断提升查询效率和性能。
235 1
|
8月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
680 0
|
8月前
|
Java 数据库连接 数据库
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
1100 0
|
10月前
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
457 2
|
Java 数据库连接 Maven
mybatis使用一:springboot整合mybatis、mybatis generator,使用逆向工程生成java代码。
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和MyBatis Generator,使用逆向工程来自动生成Java代码,包括实体类、Mapper文件和Example文件,以提高开发效率。
597 2
mybatis使用一:springboot整合mybatis、mybatis generator,使用逆向工程生成java代码。
|
SQL JSON Java
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和PageHelper进行分页操作,并且集成Swagger2来生成API文档,同时定义了统一的数据返回格式和请求模块。
514 1
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块

热门文章

最新文章

下一篇
oss云网关配置