欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot集成Mybatis配置简单案例

程序员文章站 2022-05-26 08:53:57
...

准备工作:

编辑器: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、测试结果

SpringBoot集成Mybatis配置简单案例

 

9、结束