SpringBoot集成Mybatis配置简单案例

本文介绍了如何在SpringBoot项目中集成Mybatis,包括配置pom.xml、application.yml,创建数据库表,定义实体类、DAO接口、Mapper XML文件,实现Service层并编写测试用例,最终成功运行并展示测试结果。
摘要由CSDN通过智能技术生成

准备工作:

编辑器:InterlliJ IDEA 2018.3

jdk:1.8

maven:3.6.0

springboot:2.1.3

mysql:5.6.42

 

 

一、pom.xml文件。

<dependency> 
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId> 
    <exclusions> 
        <!--排除默认的tomcat-jdbc--> 
        <exclusion> 
            <groupId>org.apache.tomcat</groupId> 
            <artifactId>tomcat-jdbc</artifactId> 
        </exclusion> 
    </exclusions> 
</dependency> 

<!--已经包含hikari依赖--> 
<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-jdbc</artifactId> 
</dependency> 

<!--mybatis依赖-->
<dependency> 
    <groupId>org.mybatis.spring.boot</groupId> 
    <artifactId>mybatis-spring-boot-starter</artifactId>
     <version>1.3.2</version> 
</dependency> 

<!--mysql驱动包-->
<dependency> 
    <groupId>mysql</groupId> 
    <artifactId>mysql-connector-java</artifactId> 
    <version>5.1.38</version> 
</dependency> 
<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-tomcat</artifactId> 
    <scope>provided</scope> 
</dependency> 
<dependency> 
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope> 
</dependency>

 

二、修改application.yml配置文件。

spring:
  datasource:
    username: root   #数据库用户名
    url: jdbc:mysql://localhost:3306/demo?useSSL=false&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
    password: ****** #数据库密码
    type: com.zaxxer.hikari.HikariDataSource  #连接池类型,可以不指定 2.0之后默认就是这个
    driver-class-name: com.mysql.jdbc.Driver  #jdbc驱动类


    hikari:
      minimum-idle: 5
      maximum-pool-size: 15
      auto-commit: true
      idle-timeout: 30000
      pool-name: DatebookHikariCP
      max-lifetime: 1800000
      connection-timeout: 30000
      connection-test-query: SELECT 1

mybatis:
  mapper-locations: classpath:mapper/*.xml   #mapper位置
  type-aliases-package: cn.zhoujl.enterprisems.pojo #别名设置

 

三、配置完成,写案例测试

1、建表

CREATE TABLE `tb_user`(
	`userId` Int NOT NULL PRIMARY KEY AUTO_INCREMENT,
	`userName` VARCHAR(25) NOT NULL,
	`password` VARCHAR(25) NOT NULL,
)
ENGINE = INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=`utf8`;

2、新建实体类 以User举例

public class User {
    private String userId;
    private String userName;
    private String password;

    @Override
    public String toString() {
        return "user{" +
                "userId='" + userId + '\'' +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

 

3、新建dao层接口类 UserDaoMapper

import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserDaoMapper {
    int insert (User domain);
    void deleteById(int userId);
    void update(User domain);
    List<User> queryAll();
}

 

4、在resource下新建mapper文件夹,并在文件夹内新建UserDaoMapper.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的值是dao层接口的全类名
<mapper namespace="cn.zhoujl.enterprisems.dao.login.UserDaoMapper" >
    <sql id="BASE_TABLE">
        tb_user
    </sql>
    <sql id="BASE_COLUMN">
        userId,userName,password
    </sql>
    -- parameterType的值是参数类型的全类名
    <insert id="insert" parameterType="cn.zhoujl.enterprisems.pojo.login.User">
        INSERT INTO <include refid="BASE_TABLE"/>
        <trim prefix="(" suffix=")" suffixOverrides=",">
            userName,password,
        </trim>
        <trim prefix="VALUES(" suffix=")" suffixOverrides=",">
            #{userName,jdbcType = VARCHAR},
            #{password,jdbcType = VARCHAR},
        </trim>
    </insert>
    <delete id="deleteById">
        DELETE FROM <include refid="BASE_TABLE"/>
        WHERE
        `userId` = #{userId,jdbcType = INTEGER}
    </delete>
    <update id="update" parameterType="cn.zhoujl.enterprisems.pojo.login.User">
        UPDATE <include refid="BASE_TABLE"/>
        <set>
            <if test="userName != null">
                `userName` = #{userName,jdbcType = VARCHAR},
            </if>
            <if test="password != null">
                `password` = #{password,jdbcType = VARCHAR},
            </if>
        </set>
        <where>
            `userId` =  #{userId,jdbcType = INTEGER}
        </where>
    </update>
    <select id="queryAll" resultType="cn.zhoujl.enterprisems.pojo.login.User">
        SELECT <include refid="BASE_COLUMN"/>
        FROM <include refid="BASE_TABLE"/>
    </select>
</mapper>

 

5、service层新建UserServerI接口

import cn.zhoujl.enterprisems.pojo.login.User;

import java.util.List;

public interface UserServiceI {
    int insert(User domain);
    void update(User domain);
    List<User> queryAll();
    void deleteById(int userId);
}

 

6、service层新建UserServerImpl实现UserServerI接口

import cn.zhoujl.enterprisems.dao.login.UserDaoMapper;
import cn.zhoujl.enterprisems.pojo.login.User;
import cn.zhoujl.enterprisems.service.serviceI.login.UserServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserServiceI {
    @Autowired
    private UserDaoMapper userDaoMapper;
    @Override
    public int insert(User domain) {
        return userDaoMapper.insert(domain);
    }

    @Override
    public void update(User domain) {
        userDaoMapper.update(domain);
    }

    @Override
    public List<User> queryAll() {
        return userDaoMapper.queryAll();
    }

    @Override
    public void deleteById(int userId) {
        userDaoMapper.deleteById(userId);
    }
}

 

7、新建测试类,测试结果

import org.junit.runner.RunWith;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@MapperScan("cn.zhoujl.enterprisems.dao")
public class EnterprisemsApplicationTests {

//    @Test
//    public void contextLoads() {
//
//    }

}
import cn.zhoujl.enterprisems.EnterprisemsApplicationTests;
import cn.zhoujl.enterprisems.pojo.login.User;
import cn.zhoujl.enterprisems.service.serviceI.login.UserServiceI;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

public class UserServiceT extends EnterprisemsApplicationTests {
    @Autowired
    private UserServiceI userService;

    @Test
    public void testInsert(){
        User domain = new User();
        domain.setUserName("abc");
        domain.setPassword("123456");
        int insert = userService.insert(domain);
        System.out.println("insert:"+insert);
    }

    @Test
    public void testDelete(){
        userService.deleteById(1001);
        userService.deleteById(1002);
    }
}

 

 

 

8、测试结果

 

9、结束

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值