mysql8+mybatis-plus 查询json格式数据

本文介绍了一个包含JSON字段的SQL表的创建与操作方法,并通过Spring Boot应用演示了如何使用MyBatis Plus进行JSON数据的增删改查。具体涵盖了表结构定义、数据插入、更新、查询等关键步骤。

sql 测试json表

CREATE TABLE `testjson` (
  `id` int NOT NULL AUTO_INCREMENT,
  `json_obj` json DEFAULT NULL,
  `json_arr` json DEFAULT NULL,
  `json_str` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

INSERT INTO test2.testjson
(id, json_obj, json_arr, json_str)
VALUES(1, '{"age": "1", "sex": "123"}', '[1, 2, 4]', '12');
INSERT INTO test2.testjson
(id, json_obj, json_arr, json_str)
VALUES(2, '{"age": "1", "sex": "123"}', '[1, 2, 4]', '12');
INSERT INTO test2.testjson
(id, json_obj, json_arr, json_str)
VALUES(3, '{"age": "1", "sex": "123"}', '[1, 2, 4]', '12');
INSERT INTO test2.testjson
(id, json_obj, json_arr, json_str)
VALUES(4, '{"age": "1", "sex": "123"}', '[1, 2, 4]', '12');
INSERT INTO test2.testjson
(id, json_obj, json_arr, json_str)
VALUES(5, '{"age": "1", "sex": "123"}', '[1, 2, 4]', '12');

后台springboot 文件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.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot-test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <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>

application.yml

spring:
    dataSource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        password: root
        url: jdbc:mysql://localhost:3307/test2?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
        username: root

实体类User.java

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import lombok.Data;

import java.io.Serializable;

@Data
@TableName(value = "testjson", autoResultMap=true)
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    @TableField(typeHandler = JacksonTypeHandler.class)
    private JsonObj jsonObj;
    private String jsonArr;
    private String jsonStr;



}

JsonObj,java

@Data
public class JsonObj {
    private String sex;
    private Integer age;
}

UserMapper.java

@Mapper
public interface UserMapper extends BaseMapper<User> {

    User selectById(Long id);
    User selectByLike(String sex);
<?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.springboot.mapper.UserMapper">

    <resultMap id="BaseResultMap" type="com.springboot.entity.User">
        <id column="id" property="id"/>
        <result column="json_obj" property="jsonObj"
        typeHandler="com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler"/>
        <result column="json_arr" property="jsonArr"/>
        <result column="json_str" property="jsonStr"/>
    </resultMap>

    <select id="selectById" resultMap="BaseResultMap">
        select *from testjson where `id`=#{id}
    </select>

    <select id="selectByLike" resultMap="BaseResultMap">
       select * from testjson where json_obj->'$.sex' like '%'+#{sex}'+%'
    </select>

</mapper>
import com.springboot.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    UserMapper userMapper;

   

    @GetMapping("/testJson")
    public String testJson(){
        return "User===:"+userMapper.selectById(1L);
    }
    @GetMapping("/testJsonLike")
    public String testJsonLike(){
        return "User===:"+userMapper.selectByLike("123");
    }
}

备注:常用JSON函数

//插入和更新

JSON_SET和JSON_INSERT区别:set key存在会覆盖value,insert只会插入新的key,value

UPDATE testjson SET json_obj = JSON_SET(json_obj,'$.age','localhost','$.url','www.muscleape.com') WHERE id = 2;

UPDATE testjson SET json_obj = JSON_INSERT(json_obj,'$.url','www.test.com') WHERE id = 3;

//remove元素

UPDATE testjson SET json_obj = json_remove(json_obj, '$.age') WHERE id = 5;

//模糊查询

select * from testjson where json_obj->'$.url' like '%muscleape%'

### 使用 Spring、MyBatis-PlusMySQL 和 Vue3 构建图书管理系统的教程 构建一个完整的图书管理系统涉及前后端分离架构的设计。以下是关于如何使用 **Spring Boot**(后端)、**MyBatis-Plus**(持久层框架)、**MySQL**(数据库)和 **Vue3**(前端)来完成这一目标的具体说明。 #### 1. 后端开发 (Spring Boot + MyBatis-Plus) ##### 创建 Spring Boot 项目 可以通过 Spring Initializr 或者手动创建一个 Maven/Gradle 的 Spring Boot 项目,确保引入以下依赖项: ```xml <dependencies> <!-- Spring Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MySQL Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- MyBatis-Plus Starter --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.5</version> </dependency> <!-- Lombok for simplifying code --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies> ``` ##### 配置 `application.yml` 文件 设置数据库连接和其他必要的参数[^3]: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/library_system?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC username: root password: your_password driver-class-name: com.mysql.cj.jdbc.Driver mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl ``` ##### 定义实体类 假设有一个名为 `Book` 的表,其字段包括 `id`, `title`, `author`, 和 `publish_date`: ```java package com.library.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; @Data @TableName("book") public class Book { @TableField(value = "id") private Long id; @TableField(value = "title") private String title; @TableField(value = "author") private String author; @TableField(value = "publish_date") private java.sql.Date publishDate; } ``` ##### Mapper 接口 定义用于访问数据库的 Mapper 接口,并继承 `BaseMapper<Book>` 来获得 CRUD 方法的支持[^4]: ```java package com.library.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.library.entity.Book; import org.apache.ibatis.annotations.Mapper; @Mapper public interface BookMapper extends BaseMapper<Book> {} ``` ##### Service 层 编写服务逻辑以封装业务处理功能: ```java package com.library.service.impl; import com.library.entity.Book; import com.library.mapper.BookMapper; import com.library.service.IBookService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; @Service public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements IBookService { // 自定义方法可在此处扩展 } ``` ##### Controller 层 提供 RESTful API 支持客户端请求交互: ```java package com.library.controller; import com.library.entity.Book; import com.library.service.IBookService; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; @RestController @RequestMapping("/books") public class BookController { @Resource private IBookService bookService; @GetMapping("") public List<Book> getAllBooks() { return bookService.list(); } @PostMapping("") public Boolean addBook(@RequestBody Book book) { return bookService.save(book); } @PutMapping("/{id}") public Boolean updateBook(@PathVariable Long id, @RequestBody Book updatedBook) { updatedBook.setId(id); return bookService.updateById(updatedBook); } @DeleteMapping("/{id}") public Boolean deleteBook(@PathVariable Long id) { return bookService.removeById(id); } } ``` --- #### 2. 前端开发 (Vue3) ##### 初始化 Vue3 项目 使用 Vue CLI 或 Vite 工具快速搭建 Vue3 应用程序环境。 安装 Axios 作为 HTTP 请求工具: ```bash npm install axios ``` ##### 编写组件 设计简单的页面结构展示书籍列表并允许增删改查操作。 ###### 示例代码:`BookList.vue` ```vue <template> <div> <h1>图书管理系统</h1> <button @click="addNewBook">新增图书</button> <table border="1"> <thead> <tr> <th>ID</th> <th>Title</th> <th>Author</th> <th>Publish Date</th> <th>Action</th> </tr> </thead> <tbody> <tr v-for="(book, index) in books" :key="index"> <td>{{ book.id }}</td> <td>{{ book.title }}</td> <td>{{ book.author }}</td> <td>{{ formatDate(book.publishDate) }}</td> <td> <button @click="editBook(book)">编辑</button> <button @click="deleteBook(book.id)">删除</button> </td> </tr> </tbody> </table> </div> </template> <script> import axios from 'axios'; export default { data() { return { books: [], }; }, methods: { fetchBooks() { axios.get('http://localhost:8080/books').then((response) => { this.books = response.data.map(item => ({ ...item, publishDate: new Date(item.publishDate), })); }); }, addNewBook() { const newBook = { title: '新书', author: '作者名', publishDate: new Date().toISOString() }; axios.post('http://localhost:8080/books', newBook).then(() => { this.fetchBooks(); }); }, editBook(book) { console.log(`正在编辑 ${JSON.stringify(book)}`); // TODO: 实现更新逻辑 }, deleteBook(id) { axios.delete(`http://localhost:8080/books/${id}`).then(() => { this.fetchBooks(); }); }, formatDate(dateObj) { return dateObj.toLocaleDateString(); }, }, mounted() { this.fetchBooks(); }, }; </script> ``` --- #### 总结 以上展示了如何通过组合技术栈实现一个基础版本的图书管理系统。实际应用中可能还需要考虑更多细节,比如分页加载、动态权限控制等高级特性[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java斗罗

请作者健身

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值