20. Springboot与mybatis整合

20. Springboot与mybatis整合

1. 搭建项目

在这里插入图片描述

p.s 选择项目需要的依赖

在这里插入图片描述

2. 完善pom.xml

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.exSpring</groupId>
    <artifactId>demospring</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demospring</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <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.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.yml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3. 删除application.properties,新增application.yml与application-dev.yml

p.s 每个环境的参数不同,我们就可以把每个环境的参数配置到yml文件中,这样在想用哪个环境的时候只需要在主配置文件中将用的配置文件写上就行如application.yml

application-dev.yml:开发环境

application-test.yml:测试环境

application-prod.yml:生产环境

3.1 application.yml
spring:
  profiles:
    active: dev
3.2 application-dev.yml

p.s

mybatis.mapper-locations:用于将配置路径下的 * .xml 文件加载到 mybatis 中,可配置多个路径;

type-aliases-package:指定POJO扫描包来让 mapper.xml 文件的 resultType 自动扫描到自定义POJO,这样就不用每次指定完全限定名;

server:
  port: 8090

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai
    username: root
    password: 123456

mybatis:
  mapper-locations: classpath:/mapping/*.xml,classpath:mapper/user/*.xml
  type-aliases-package: com.example.entity

4. 项目结构

在这里插入图片描述

5. 在mybatis库中创建表user

CREATE TABLE `user` (
 `id` INT NOT NULL AUTO_INCREMENT,
 `name` VARCHAR(50) COLLATE utf8mb4_general_ci DEFAULT NULL,
 `age` INT DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci

6. 编写代码

1. User.java
package com.example.entity;

public class User {

    private int id;
    private String username;
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", age=" + age +
                '}';
    }
}
2. UserMapper.java
package com.example.mapper;

import com.example.entity.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserMapper {

    public List<User> queryAllUser() ;

    public User selectUserById(@Param(value = "id") Integer id) ;

}
3. UserMapper.xml

p.s 根据yml配置,创建在resources/mapping下

<?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.mapper.UserMapper">
    <resultMap id="User" type="com.example.entity.User">
        <result column="id" jdbcType="INTEGER" property="id" />
        <result column="username" property="username" />
        <result column="age" property="age" />
    </resultMap>

    <select id="queryAllUser" resultMap="User">
        select
            id ,
            name as username ,
            age
        from user
    </select>

    <select id="selectUserById" resultMap="User" parameterType="java.lang.Integer">
        select
            id ,
            name as username ,
            age
        from user
        where id = #{id}
        limit 1
    </select>



</mapper>
4. UserService.java
package com.example.service;

import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper ;

    public List<User> queryAllUser() {
        return userMapper.queryAllUser() ;
    }

    public User selectUserById(Integer id) {
        return userMapper.selectUserById(id) ;
    }

}
5. UserController.java
package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService ;

    @RequestMapping(value = "/queryAllUser", method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> queryAllUser() {
        Map<String,Object> map = new HashMap<String,Object>() ;
        List<User> list = userService.queryAllUser() ;
        map.put("list", list) ;
        return map;
    }

    @RequestMapping(value = "/selectUserById", method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> selectUserById(@RequestParam("id") int id) {
        Map<String,Object> map = new HashMap<String,Object>() ;
        User user = userService.selectUserById(id) ;
        map.put("user", user) ;
        return map;
    }


}
7. 修改启动类

p.s

@MapperScan 意思是扫描com.example.mapper下的所有mapper类作为Mapper映射文件,就不用每个mapper类注解@Mapper;

scanBasePackages:添加扫描包列表(如果启动类在包里就不用配置)

package com.exspring.demospring;

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

@MapperScan("com.example.mapper")
@SpringBootApplication(scanBasePackages = "com.example")
public class DemospringApplication {

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

}
8. 运行项目

p.s 启动项目并访问以下链接

http://localhost:8090/user/queryAllUser

http://localhost:8090/user/selectUserById?id=15892

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值