赞
踩
SpringBoot:简化新Spring应用的初始搭建以及开发过程
SpringCloud:基于Spring Boot实现的云原生应用开发工具,SpringCloud使用的技术:(Spring Cloud Gateway、Spring Cloud Alibaba Nacos、Spring Cloud Alibaba Sentinel、Spring Cloud Alibaba Seata、Spring Cloud Task和Spring Cloud Feign等)
MyBatis-Plus:持久层框架
Redis:内存缓存
RabbitMQ:消息中间件
腾讯云:文件存储
腾讯云:视频点播
欢拓云直播:直播平台
微信支付
Nginx:负载均衡
Lombok
Mysql:关系型数据库
MybatisPlus单表
创建表
CREATE TABLE USER
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
NAME VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
插入数据
INSERT INTO USER (id, NAME, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
创建springboot工程
引入相关依赖
<?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.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.jq</groupId>
<artifactId>ggkt_mp_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ggkt_mp_demo</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</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok用来简化实体类-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
配置文件,配置数据库驱动,连接路径,用户名,密码
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
启动类
package com.jq.ggkt_mp_demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.jq.ggkt_mp_demo.mapper")
public class GgktMpDemoApplication {
public static void main(String[] args) {
SpringApplication.run(GgktMpDemoApplication.class, args);
}
}
实体类
package com.jq.ggkt_mp_demo.entity;
import lombok.Data;
@Data
public class user {
private Long id;
private String name;
private Integer age;
private String email;
}
@Data的作用: 生成 以下方法
创建mapper接口,使用MybatisPlus
package com.jq.ggkt_mp_demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jq.ggkt_mp_demo.entity.User;
public interface UserMapper extends BaseMapper<User> {
}
继承BaseMapper的原因是,BaseMapper把基本的CRUD操作方法封装好了,BaseMapper源码
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com.baomidou.mybatisplus.core.mapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
public interface BaseMapper<T> extends Mapper<T> {
int insert(T entity);
int deleteById(Serializable id);
int deleteByMap(@Param("cm") Map<String, Object> columnMap);
int delete(@Param("ew") Wrapper<T> wrapper);
int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);
int updateById(@Param("et") T entity);
int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);
T selectById(Serializable id);
List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
T selectOne(@Param("ew") Wrapper<T> queryWrapper);
Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);
List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);
List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);
<E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper);
<E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper);
}
public void addUser(){
//创建User对象,设置属性值,添加到数据库
User user =new User();
user.setName("mary");
user.setAge(18);
user.setEmail("aidisheng@qq.com");
int result = userMapper.insert(user);
System.out.println(result); //影响的行数
System.out.println(user); //id自动回填
}
在配置文件中,加入响应的配置即可
#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
输出日志,可以看到语句、参数、结果
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6f3f0fae] was not registered for synchronization because synchronization is not active
2022-07-21 10:28:46.740 INFO 19352 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-07-21 10:28:50.685 INFO 19352 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@720638621 wrapping com.mysql.cj.jdbc.ConnectionImpl@3a175162] will not be managed by Spring
==> Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
==> Parameters: 1549944444160147457(Long), maryuup(String), 18(Integer), aidisheng@qq.com(String)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6f3f0fae]
1
User(id=1549944444160147457, name=maryuup, age=18, email=aidisheng@qq.com)
比如主键id是怎么生成的
MyBatis-Plus默认的主键策略是:ID_WORKER 全局唯一ID
要想主键自增需要配置如下主键策略,需要在创建数据表的时候设置主键自增实体字段中配置 @TableId(type = IdType.AUTO)
在表对应实体类上面配置,在实体类作为主键属性上面添加注解
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
@Data
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
对于AUTO,主键id 在数据库中的设置
其它主键策略:分析 IdType 源码可知
public enum IdType {
/**
* 数据库ID自增
*/
AUTO(0),
/**
* 该类型为未设置主键类型
*/
NONE(1),
/**
* 用户输入ID
* 该类型可以通过自己注册自动填充插件进行填充
*/
INPUT(2),
/**
* 全局唯一ID
*/
ASSIGN_ID(3),
/**
* 全局唯一ID (UUID)
*/
ASSIGN_UUID(4),
/** @deprecated */
@Deprecated
ID_WORKER(3),
/** @deprecated */
@Deprecated
ID_WORKER_STR(3),
/** @deprecated */
@Deprecated
UUID(4);
private final int key;
private IdType(int key) {
this.key = key;
}
public int getKey() {
return this.key;
}
}
修改操作: 先查,后改
// 3.修改操作 ,先查,再改
@Test
public void updateUser(){
//根据id 查询
User user = userMapper.selectById(1);
//设置修改值
user.setName("jasddddd");
//调用方法实现修改
int rows = userMapper.updateById(user);
System.out.println(rows); //影响行数
}
MyBatis Plus自带分页插件,只要简单的配置即可实现分页功能
配置分页插件
package com.jq.ggkt_mp_demo.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MpConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
编写分页代码
/**
* 4.分页查询
* 创建Page对象,传递两个参数:当前页,每页显示的记录数
* 调用MybatisPlus中的方法实现分页
*/
@Test
public void findPage(){
//创建Page对象,传递两个参数:当前页,每页显示的记录数
Page<User> page =new Page<>(1,3);
//调用MybatisPlus中的方法实现分页
userMapper.selectPage(page,null);
List<User> list = page.getRecords();
System.out.println(list);//[User(id=1, name=jasddddd, age=18, email=test1@baomidou.com), User(id=2, name=Jack, age=20, email=test2@baomidou.com), User(id=3, name=Tom, age=28, email=test3@baomidou.com)]
System.out.println(page.getCurrent());
System.out.println(page.getPages());
System.out.println(page.getSize());
System.out.println(page.getTotal());
System.out.println(page.hasNext());
System.out.println(page.hasPrevious());
}
@Test
public void testDeleteById(){
int result = userMapper.deleteById(8L);
System.out.println(result);
}
@Test
public void testDeleteBatchIds() {
int result = userMapper.deleteBatchIds(Arrays.asList(8, 9, 10));
System.out.println(result);
}
ALTER TABLE `user` ADD COLUMN `deleted` boolean
package com.jq.ggkt_mp_demo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import lombok.Data;
@Data
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
//逻辑删除标志
@TableLogic
private Integer deleted;
}
mybatisPlus 默认 0没有删 1已删除,如果设置的和MybatisPlus一样则无需配置
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
ge
:>=gt
:>le
:<=lt
:<@Test
public void testSelect() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.ge("age", 28);
List<User> users = userMapper.selectList(queryWrapper);
System.out.println(users);
}
eq
: =
ne
: !=
注意:seletOne返回的是一条实体记录,当出现多条时会报错
@Test
public void testSelectOne() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", "Tom");
User user = userMapper.selectOne(queryWrapper);
System.out.println(user);
}
SELECT id,name,age,email,create_time,update_time,deleted,version FROM user WHERE deleted=0 AND name = ?
selectMaps返回Map集合列表
@Test
public void testSelectMaps() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper
.like("name", "e")
.likeRight("email", "t");
List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);//返回值是Map列表
maps.forEach(System.out::println);
}
SELECT id,name,age,email,create_time,update_time,deleted,version
FROM user WHERE deleted=0 AND name LIKE ? AND email LIKE ?
orderByDesc
:降序排序orderByAsc
:升序排序@Test
public void testSelectListOrderBy() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("id");
List<User> users = userMapper.selectList(queryWrapper);
users.forEach(System.out::println);
}
SELECT id,name,age,email,create_time,update_time,deleted,version
FROM user WHERE deleted=0 ORDER BY id DESC
@Test
public void testLambdaQuery() {
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getAge,30);
queryWrapper.like(User::getName,"张");
List<User> list = userMapper.selectList(queryWrapper);
System.out.println(list);
}
SELECT id,name,age,email,create_time,update_time,deleted,version
FROM user WHERE deleted=0 AND age = ? AND name LIKE ?
public interface UserService extends IService<User> {
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
@SpringBootTest
class TestApplicationTests {
//注入service
@Autowired
private UserService userService;
//查询表所有数据
@Test
public void findAll() {
List<User> userList = userService.list();
for (User user:userList) {
System.out.println(user);
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。