从零搭建SpringBoot后台框架(一)——框架搭建+集成mybatis

392 阅读3分钟

一、通过idea工具构建基础框架

  1. 打开idea,左上角File→New→Project,看到如下图的页面。选择本地jdk点击Next

image.png

  1. 选择存放路径、name、设置groupId:com.example,点击Finish

image.png

  1. 创建完成后,项目目录接口如下:

image.png

  1. 手动设置项目的maven路径、config文件、设置项目文件格式为utf8

image.png

其中config文件,设置了使用国内阿里云maven镜像

5.其中pom.xml文件如下所示,管理项目所有的依赖jar包

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

</project>
  1. pom添加spring boot父项目版本、依赖的包(myBatis、mysql、Spring Boot Web),刷新maven。
<?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 http://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.7.16</version>
        <relativePath/>
    </parent>
    <groupId>org.example</groupId>
    <artifactId>demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </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.3.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
    </dependencies>
</project>

注意:tag对应的代码是2.2.0,后面升级到了2.3.1(兼容问题);这里下载tag对应的代码建议直接手动改一下mybatis-spring-boot-starterversion

  1. 新建项目启动类DemoApplication.java、项目配置文件application.yml。

二、配置数据库信息

在application.yml添加如下数据库配置

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo?useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

三、创建数据库UserInfo表

CREATE TABLE `user_info` (
  `id` bigint(20) NOT NULL,
  `user_name` varchar(100) DEFAULT NULL,
  `password` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统用户表'

四、创建项目基本目录结构

按照以下结构,创建文件

image.png

Model

UserInfo.java

package com.example.demo.model;

public class UserInfo {
    /**
     * 主键
     */
    private Long id;
    /**
     * 用户名
     */
    private String userName;
    /**
     * 用户密码
     */
    private String password;

    public Long getId() {
        return id;
    }

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

    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;
    }
}

Mapper

<?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.demo.dao.UserInfoMapper">

    <resultMap id="BaseResultMap" type="com.example.demo.model.UserInfo">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <id column="user_name" jdbcType="VARCHAR" property="userName"/>
        <id column="password" jdbcType="VARCHAR" property="password"/>
    </resultMap>
    <sql id="Base_Column_List">
        id,user_name,password
    </sql>
    <select id="selectById" parameterType="java.lang.Long" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from user_info
        where id = #{id,jdbcType=INTEGER}
    </select>
</mapper>

DAO

package com.example.demo.dao;

import com.example.demo.model.UserInfo;
import org.apache.ibatis.annotations.Param;

public interface UserInfoMapper {
    UserInfo selectById(@Param("id") Long id);
}

Service

package com.example.demo.service;

import com.example.demo.model.UserInfo;

public interface UserInfoService {
    UserInfo selectById(Long id);
}

ServiceImpl

package com.example.demo.service.impl;

import com.example.demo.dao.UserInfoMapper;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Override
    public UserInfo selectById(Long id) {
        return userInfoMapper.selectById(id);
    }
}

Controller

package com.example.demo.controller;

import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("userInfo")
public class UserInfoController {
    @Resource
    private UserInfoService userInfoService;

    @PostMapping("/selectById")
    public UserInfo selectById(Long id){
        return userInfoService.selectById(id);
    }
}

@RestController 是由@Controller和@ResponseBody组成,表示返回JSON格式的数据

Config

  1. application.yml添加mybatis配置,设置mapper.xml文件位置及实体类
  2. 设置com.example.demo.dao的日志级别为debug,运行时可查看执行的SQL
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo?useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.demo.entity
logging:
  level:
    com.example.demo.dao: debug

DemoApplication.java添加@MapperScan("com.example.demo.dao"),添加完如下:

package com.example.demo;

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

@MapperScan("com.example.demo.dao")
@SpringBootApplication
public class DemoApplication {

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

}

五、运行项目

找到DemoApplication,右键选择Run 'DemoApplication' 控制台显示如下即为启动成功

2023-10-08 18:09:27.237  INFO 2724 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to 1 default profile: "default"
2023-10-08 18:09:27.992  INFO 2724 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2023-10-08 18:09:27.999  INFO 2724 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-10-08 18:09:27.999  INFO 2724 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.80]
2023-10-08 18:09:28.178  INFO 2724 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-10-08 18:09:28.179  INFO 2724 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 908 ms
2023-10-08 18:09:28.584  INFO 2724 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2023-10-08 18:09:28.591  INFO 2724 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 1.621 seconds (JVM running for 2.22)

六、测试接口

使用postman测试

image.png

2023-10-08 18:26:55.677 DEBUG 8388 --- [nio-8080-exec-2] c.e.demo.dao.UserInfoMapper.selectById   : ==>  Preparing: select id,user_name,password from user_info where id = ?
2023-10-08 18:26:55.692 DEBUG 8388 --- [nio-8080-exec-2] c.e.demo.dao.UserInfoMapper.selectById   : ==> Parameters: 1(Long)
2023-10-08 18:26:55.708 DEBUG 8388 --- [nio-8080-exec-2] c.e.demo.dao.UserInfoMapper.selectById   : <==      Total: 1

七、项目地址

gitee

PS:可以通过tag下载本文对应的代码版本

八、结尾

框架搭建,整合mybatis已完成,有问题可以联系chenzhenlindx@qq.com

九、参考文章

  1. 从零搭建自己的SpringBoot后台框架(一)