Springboot 整合 mybatis

本文详细介绍如何在SpringBoot项目中集成MyBatis框架,包括配置数据源、编写配置类、创建Mapper接口及XML文件等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springboot集成了springJDBC与JPA,但是没有集成mybatis,所以想要使用mybatis就要自己去集成。集成方式相当简单。

1、项目结构

这里写图片描述

2、pom.xml

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-parent</artifactId>  
        <version>1.4.3.RELEASE</version>  
    </parent>  

  <groupId>myboot</groupId>
  <artifactId>myboot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>myboot</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

   <dependencies>  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-web</artifactId>  
        </dependency>  
        <dependency>  
            <groupId>junit</groupId>  
            <artifactId>junit</artifactId>  
            <version>3.8.1</version>  
            <scope>test</scope>  
        </dependency>  
        <!--引入swagger  -->  
        <dependency>  
           <groupId>io.springfox</groupId>  
           <artifactId>springfox-swagger2</artifactId>  
           <version>2.2.2</version>  
        </dependency>  
        <dependency>  
           <groupId>io.springfox</groupId>  
           <artifactId>springfox-swagger-ui</artifactId>  
           <version>2.2.2</version>  
        </dependency>  
        <!--集成mybatis  -->  

        <!-- 与数据库操作相关的依赖 -->  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-jdbc</artifactId>  
        </dependency>  

        <!-- 使用数据源 -->  
        <dependency>  
            <groupId>com.alibaba</groupId>  
            <artifactId>druid</artifactId>  
            <version>1.0.14</version>  
        </dependency>  

        <!-- mysql -->  
        <dependency>  
            <groupId>mysql</groupId>  
            <artifactId>mysql-connector-java</artifactId>  
            <scope>runtime</scope>  
        </dependency>  

        <!-- mybatis -->  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis</artifactId>  
            <version>3.2.8</version>  
        </dependency>  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis-spring</artifactId>  
            <version>1.2.2</version>  
         </dependency>  
    </dependencies> 

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://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.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.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>
      </plugins>
    </pluginManagement>
  </build>
</project>

说明:

spring-boot-starter-jdbc:引入与数据库操作相关的依赖,例如daoSupport等
druid:阿里巴巴的数据源
mysql-connector-java:mysql连接jar,scope为runtime
mybatis + mybatis-spring:mybatis相关jar

3、application.properties

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull&amp;useUnicode=true&amp;characterEncoding=utf-8
jdbc.username = root
jdbc.password = 123456

mybatis.typeAliasesPackage=myboot.myboot.*
mybatis.mapperLocations=classpath:mapper/*.xml

说明:

mybatis.typeAliasesPackage:指定mapper类的基包,即指定其在*Mapper.xml文件中可以使用简名来代替全类名(看后边的UserMapper.xml介绍)
mybatis.mapperLocations:指定*Mapper.xml的位置

4、MyBatisConfig.java

package myboot.myboot.util;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSourceFactory;

/**
 * springboot集成mybatis的基本入口
 * 1)创建数据源
 * 2)创建SqlSessionFactory
 */
@Configuration    //该注解类似于spring配置文件
@MapperScan(basePackages="myboot.myboot.mapper")
public class MyBatisConfig {

    @Autowired
    private Environment env;

    /**
     * 创建数据源
     * @Primary 该注解表示在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让@autowire注解报错 
     */
    @Bean
    //@Primary
    public DataSource getDataSource() throws Exception{
        Properties props = new Properties();
        props.put("driverClassName", env.getProperty("jdbc.driverClassName"));
        props.put("url", env.getProperty("jdbc.url"));
        props.put("username", env.getProperty("jdbc.username"));
        props.put("password", env.getProperty("jdbc.password"));
        return DruidDataSourceFactory.createDataSource(props);
    }

    /**
     * 根据数据源创建SqlSessionFactory
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource ds) throws Exception{
        SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
        fb.setDataSource(ds);//指定数据源(这个必须有,否则报错)
        //下边两句仅仅用于*.xml文件,如果整个持久层操作不需要使用到xml文件的话(只用注解就可以搞定),则不加
        fb.setTypeAliasesPackage(env.getProperty("mybatis.typeAliasesPackage"));//指定基包
        fb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapperLocations")));//指定xml文件位置

        return fb.getObject();
    }

}

作用:mybatis与springboot集成的入口

说明:

类上边添加两个
@Configuration注解(该注解类似于spring的配置文件)
@MapperScan注解,指定扫描的mapper接口所在的包
在该类中,注入了Environment实例,使用该实例可以去读取类路径下application.properties文件中的内容,读取文件内容的三种方式,见第二章 第二个spring-boot程序
在该类中,使用druid数据源定义了数据源Bean,spring-boot默认使用的是tomcat-jdbc数据源,这是springboot官方推荐的数据源(性能和并发性都很好)
根据数据源生成SqlSessionFactory
值得注意的是,数据源是必须指定的,否则springboot启动不了
typeAliasesPackage和mapperLocations不是必须的,如果整个项目不需要用到*Mapper.xml来写SQL的话(即只用注解就可以搞定),那么不需要配
@Primary注解:指定在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让@Autowire注解报错(一般用于多数据源的情况下)
这样之后,在项目中再使用springboot就和在ssm中(配置完成后)使用一样了。

5、UserMapper.java

package myboot.myboot.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.mapstruct.Mapper;

import myboot.myboot.bean.User;

@Mapper
public interface UserMapper {

    @Insert("INSERT INTO tb_user(username, password) VALUES(#{username},#{password})")
    public int insertUser(@Param("username") String username, @Param("password")  String password);

    /**
     * 插入用户,并将主键设置到user中
     * 注意:返回的是数据库影响条数,即1
     */
    public int insertUserWithBackId(User user);
}

说明:该接口中有两个方法,

一个普通插入:直接用注解搞定
一个插入返回主键:需要使用xml来搞定

6、UserMapper.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">

<!-- 指定工作空间,要与接口名相同,源代码没有去看,猜测应该是通过"这里的namespace.下边方法的id"来定位方法的 -->
<mapper namespace="myboot.myboot.mapper.UserMapper">

    <!-- 若不需要自动返回主键,将useGeneratedKeys="true" keyProperty="id"去掉即可(当然如果不需要自动返回主键,直接用注解即可) -->
    <insert id="insertUserWithBackId" parameterType="myboot.myboot.bean.User" useGeneratedKeys="true" keyProperty="id" >
       <![CDATA[
       INSERT INTO tb_user 
       (
           username,
           password
       )
       VALUES
       (
           #{username, jdbcType=VARCHAR},
           #{password, jdbcType=VARCHAR}
       )
       ]]>
   </insert>

</mapper>

7、UserService.java

package myboot.myboot.service;

import myboot.myboot.bean.User;


public interface UserService  {

    boolean addUser(String username, String password);

    User addUserWithBackId(String username, String password);


}

8、UserServiceImpl.java

package myboot.myboot.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import myboot.myboot.bean.User;
import myboot.myboot.mapper.UserMapper;
import myboot.myboot.service.UserService;


@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;


    @Override
    public boolean addUser(String username, String password){
        return userMapper.insertUser(username, password)==1?true:false;
    }
    @Override
    public User addUserWithBackId(String username, String password){
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userMapper.insertUserWithBackId(user);//该方法后,主键已经设置到user中了
        return user;
    }


}

9、UserController.java

package myboot.myboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import myboot.myboot.bean.User;
import myboot.myboot.service.UserService;
@RestController
@RequestMapping("/user")
@Api("userController相关api")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("添加用户")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="query",name="username",dataType="String",required=true,value="用户的姓名",defaultValue="zhaojigang"),
        @ApiImplicitParam(paramType="query",name="password",dataType="String",required=true,value="用户的密码",defaultValue="wangna")
    })
    @ApiResponses({
        @ApiResponse(code=400,message="请求参数没填好"),
        @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
    })
    @RequestMapping(value="/addUser",method=RequestMethod.POST)
    public boolean addUser(@RequestParam("username") String username, 
                           @RequestParam("password") String password) {
        return userService.addUser(username,password);
    }

    @ApiOperation("添加用户且返回已经设置了主键的user实例")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="query",name="username",dataType="String",required=true,value="用户的姓名",defaultValue="zhaojigang"),
        @ApiImplicitParam(paramType="query",name="password",dataType="String",required=true,value="用户的密码",defaultValue="wangna")
    })
    @ApiResponses({
        @ApiResponse(code=400,message="请求参数没填好"),
        @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
    })
    @RequestMapping(value="/addUserWithBackId",method=RequestMethod.POST)
    public User addUserWithBackId(@RequestParam("username") String username, 
                                     @RequestParam("password") String password) {
        return userService.addUserWithBackId(username, password);
    }
}

10、User.java

package myboot.myboot.bean;

public class User {

     public String loginName;  
     public String password;
     public String username;
    public String getLoginName() {
        return loginName;
    }
    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }  

}

启动:
这里写图片描述

测试:post提交http://localhost:8080/user/addUser?username=ss&password=dd

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值