SpringBoot中使用MyBatis


背景:在用到Mybatis时经常忘记要如何使用,所以记录下来以备不时之需。
注意:@MapperScan(“com.example.simplemybatisspringboot.dao”)要加在启动类中,这样才能扫描dao包,当然有其他方法代替
创建项目
名称
选择jar包
项目结构

application.properties

# 应用名称
spring.application.name=simple-mybatis-springboot
# 应用服务 WEB 访问端口
server.port=8080
#下面这些内容是为了让MyBatis映射
#指定Mybatis的Mapper文件
mybatis.mapper-locations=classpath:mappers/*xml
#指定Mybatis的实体目录
mybatis.type-aliases-package=com.example.simplemybatisspringboot.entity
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/test_mybatis?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=root
spring.datasource.password=12345

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>simple-mybatis-springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>simple-mybatis-springboot</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.example.simplemybatisspringboot.SimpleMybatisSpringbootApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Person

package com.example.simplemybatisspringboot.entity;

import lombok.Data;

@Data
public class Person {
    private String name;
}

TestDao

package com.example.simplemybatisspringboot.dao;

import com.example.simplemybatisspringboot.entity.Person;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public interface TestDao {
    public Person getInfoByName(String name);
    public List<Person> getInfos();
    public void addPerson(Person person);
}

TestService

package com.example.simplemybatisspringboot.service;

import com.example.simplemybatisspringboot.dao.TestDao;
import com.example.simplemybatisspringboot.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TestService {
    @Autowired
    TestDao testDao;

    /**
     * 通过名字查
     * @param name
     * @return
     */
    public Person getInfoByName(String name){
        return testDao.getInfoByName(name);
    }

    /**
     * 查所有person
     * @return
     */
    public List<Person> getInfos(){
        return testDao.getInfos();
    }

    /**
     * 添加person
     * @param person
     */
    public void addPerson(Person person){
        testDao.addPerson(person);
    }
}

TestController

package com.example.simplemybatisspringboot.controller;

import com.example.simplemybatisspringboot.entity.Person;
import com.example.simplemybatisspringboot.service.TestService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class TestController {
    @Autowired
    TestService testService;

    @GetMapping("/info/{name}")
    @ResponseBody
    public String getInfo(@PathVariable String name) throws JsonProcessingException {
        Person person = testService.getInfoByName(name);
        ObjectMapper jsonUtil = new ObjectMapper();
        return jsonUtil.writeValueAsString(person);
    }

    @GetMapping("/infos")
    @ResponseBody
    public String getInfos() throws JsonProcessingException {
        List<Person> infos = testService.getInfos();
        ObjectMapper jsonUtil = new ObjectMapper();
        return jsonUtil.writeValueAsString(infos);
    }

    @GetMapping("/addition")
    @ResponseBody
    public String addPerson(){
        for (int i = 0; i < 10; i++) {
            Person p = new Person();
            p.setName("personName:" + i);
            testService.addPerson(p);
        }
        return "Success";
    }
}

TestDao.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="com.example.simplemybatisspringboot.dao.TestDao">
    <select id="getInfoByName"  parameterType="java.lang.String" resultType="Person">
        select name from person where name = #{name}
    </select>

    <select id="getInfos"   resultType="Person">
        select name from person
    </select>

    <insert id="addPerson" parameterType="Person">
        insert into person (name) values(#{name})
    </insert>
</mapper>

SimpleMybatisSpringbootApplication

package com.example.simplemybatisspringboot;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.simplemybatisspringboot.dao")
public class SimpleMybatisSpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SimpleMybatisSpringbootApplication.class, args);
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值