《穿越SpringBoot 》 第三章-SpringBoot 访问数据库 | 第3节- SpringBoot 整合MyBatis-Plus

前题

基于:IntelliJ IDEAMaven构建工具JDK1.8SpringBoot 2.3.4编写。

官人如需使用 Maven 请阅读教程:Maven 构建工具的下载与安装

官人如需使用 IDEA 请阅读教程:IntelliJ IDEA

更多干货

请阅读:《穿越SpringBoot》系列文章

请参考:Java学习资料

官网

官网地址:http://mybatis.plus/
在这里插入图片描述

使用

目录结构

在这里插入图片描述

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.3.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>mybatisplus</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>mybatisplus</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>

		<!--mybatis-plus-->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.0</version>
		</dependency>
<!--mysql-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
			<version>5.1.39</version>
		</dependency>
<!--thymeleaf-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
<!--web-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
<!--lombok-->
		<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>

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

</project>

application.properties 配置文件

连接数据库:

spring.datasource.url=jdbc:mysql:///test?characterEncoding=utf-8&useSSL=false
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root

#mysql
#spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#spring.datasource.url=jdbc:mysql:///tset?serverTimezone=Hongkong&useUnicode=true&characterEncoding=utf8
#spring.datasource.username=root
#spring.datasource.password=password
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.datasource.dbcp2.min-idle=5
#spring.datasource.dbcp2.initial-size=5
#spring.datasource.dbcp2.max-total=5
#spring.datasource.dbcp2.max-wait-millis=200

#mybatis-plus
# 如果是放在src/main/java目录下 classpath:/com/example/*/mapper/*Mapper.xml
# 如果是放在resource目录 classpath:/mapper/*Mapper.xml
# mybatis-plus.mapper-locations=classpath:/com/springboot/study/mapper/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
# mybatis-plus.type-aliases-package=com.springboot.study.entity
#主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
# mybatis-plus.global-config.id-type=3
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
#mybatis-plus.global-config.field-strategy=2
#驼峰下划线转换
#mybatis-plus.global-config.db-column-underline=true
#mp2.3+ 全局表前缀 mp_
#mybatis-plus.global.table-prefix: mp_
#刷新mapper 调试神器
#mybatis-plus.global-config.refresh-mapper=true
#数据库大写下划线转换
# mybatis-plus.global-config.capital-mode=true
# Sequence序列接口实现类配置
# mybatis-plus.global-config.key-generator=com.example.mybatisplus.incrementer.OracleKeyGenerator
#逻辑删除配置(下面3个配置)
#mybatis-plus.global-config.logic-delete-value=1
#mybatis-plus.global-config.logic-not-delete-value=0
#mybatis-plus.global-config.sql-injector=com.example.springboot.MyMetaObjectHandler
#配置返回数据库(column下划线命名&&返回java实体是驼峰命名),自动匹配无需as(没开启这个,SQL需要写as: select user_id as userId)
mybatis-plus.configuration.map-underscore-to-camel-case=true
#mybatis-plus.configuration.cache-enabled=false
#配置JdbcTypeForNull, oracle数据库必须配置
#mybatis-plus.configuration.jdbc-type-for-null=null

更多 CRUD操作访问:http://mybatis.plus/guide/crud-interface.html#service-crud-%E6%8E%A5%E5%8F%A3

编写实体类

@Data
@TableName(“user”) //对应数据库表名称
@TableId(“id”)//指定主键
@TableField(“s_sex”)指定表字段和该变量对应

package com.example.mybatisplus.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName("user") //对应数据库表名称
public class User {
    
    

    @TableId("id")//指定主键
    private Integer id;
    private String name;
    private String password;
    private Integer age;
    //指定表字段和该变量对应
    //@TableField("s_sex")
}

编写mapper接口

@Mapper注解
继承mybatisplus提供的 BaseMapper< User > 需指定实体对象类型

package com.example.mybatisplus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.mybatisplus.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {
    
    
}

编写service

继承IService< User >

package com.example.mybatisplus.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.mybatisplus.entity.User;
import org.springframework.stereotype.Service;
@Service
public interface UserService extends IService<User> {
    
    
}

继承 ServiceImpl< UserMapper, User> 指定mapper对象和要操作的对象

package com.example.mybatisplus.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mybatisplus.entity.User;
import com.example.mybatisplus.mapper.UserMapper;
import com.example.mybatisplus.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    
}

编写controller

package com.example.mybatisplus.controller;

import com.example.mybatisplus.entity.User;
import com.example.mybatisplus.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import javax.annotation.Resource;
import java.util.List;

@Controller
public class DemoController {
    
    
    @Resource
    private UserService userService;

    @GetMapping("/demo1")
    public  String demo1(Model model){
    
    
        List<User> users = userService.list();
        model.addAttribute("user",users);
        System.out.println(users);
        return "index";
    }
}

编写index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<link rel="stylesheet" href="style.css">
<body>
<h1>测试SpringBoot 整合mybatis-plus</h1>
    <ul>
        <li th:each="u : ${user}" th:object="${u}">
            <div>
                <span th:text="*{name}"></span>
                <span th:text="${u.age}"></span>
            </div>
        </li>
    </ul>
</body>
</html>

测试

浏览器访问:http://localhost:8080/demo1

在这里插入图片描述

总结

待完善…

本教程基于最新的spring-boot-starter-parent:2.3.4RELEASE编写,目前很多大佬都写过关于SpringBoot的教程了,如有雷同,请多多包涵.

猜你喜欢

转载自blog.csdn.net/weixin_47371330/article/details/109186718