Mybatis-plus操作json字段实战

时光旅人 2024-09-12 ⋅ 5 阅读

简介

在实际的开发过程中,我们经常会遇到处理json字段的场景。Mybatis-plus是一个功能强大的持久层框架,它提供了丰富的API以及灵活的配置,可以轻松地操作数据库。本文将介绍如何使用Mybatis-plus来操作json字段,包括字段的插入、更新和查询等操作。

数据库准备

首先,我们需要准备一个支持json字段的数据库表。以MySQL为例,创建一个名为user的表,包含id、name和extra字段,其中extra字段类型为json。

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `extra` json,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

安装依赖

在开始之前,我们需要在项目中引入Mybatis-plus的相关依赖。在pom.xml中添加如下内容:

<dependencies>
  <!-- Mybatis-plus -->
  <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-boot-starter</artifactId>
      <version>3.4.3</version>
  </dependency>
  <!-- MySQL驱动 -->
  <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.27</version>
  </dependency>
</dependencies>

实体类定义

接下来,我们需要定义与数据库表对应的实体类,并使用注解来映射字段。以User类为例:

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

@Data
@TableName("user")
public class User {
    private Long id;
    private String name;
    private JsonNode extra;
}

上述代码中,通过@TableName注解指定了对应的数据库表名,同时使用了Lombok的@Data注解,省去了编写getter和setter方法的繁琐工作。

插入数据

现在,我们可以编写插入数据的代码了。通过Mybatis-plus提供的BaseMapper接口,我们可以很方便地进行数据库操作。首先,在UserMapper接口中添加一个insertUser方法:

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Insert;

public interface UserMapper extends BaseMapper<User> {

    @Insert("INSERT INTO user (name, extra) VALUES (#{name}, #{extra, jdbcType=JSON})")
    void insertUser(User user);
}

上述代码中,我们使用了@Insert注解,指定了对应的SQL语句。其中的#{extra, jdbcType=JSON}表示extra字段的类型为json。

接下来,在Service层中调用UserMapper的insertUser方法来插入数据:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public void insertUser(User user) {
        userMapper.insertUser(user);
    }
}

然后,在Controller层中调用UserService的insertUser方法来处理请求:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/users")
    public void createUser(@RequestBody User user) {
        userService.insertUser(user);
    }
}

至此,我们已经完成了插入数据的操作。

更新数据

接下来,我们来看一下如何更新json字段的数据。首先,在UserMapper接口中添加一个updateUser方法:

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Update;

public interface UserMapper extends BaseMapper<User> {

    @Update("UPDATE user SET name = #{name}, extra = #{extra, jdbcType=JSON} WHERE id = #{id}")
    void updateUser(User user);
}

在Service层中调用UserMapper的updateUser方法来更新数据:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public void updateUser(User user) {
        userMapper.updateUser(user);
    }
}

在Controller层中调用UserService的updateUser方法来处理请求:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PutMapping("/users/{id}")
    public void updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        userService.updateUser(user);
    }
}

至此,我们已经完成了更新数据的操作。

查询数据

最后,我们来看一下如何查询json字段的数据。在UserMapper接口中添加一个selectUser方法:

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.ibatis.annotations.Select;

public interface UserMapper extends BaseMapper<User> {

    @Select("SELECT * FROM user WHERE name = #{name}")
    User selectUser(String name);

    @Select("SELECT * FROM user WHERE extra->'$.age' > #{age}")
    List<User> selectUsersByAge(Integer age);
}

在Service层中调用UserMapper的selectUserselectUsersByAge方法来查询数据:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User selectUser(String name) {
        return userMapper.selectUser(name);
    }

    public List<User> selectUsersByAge(Integer age) {
        return userMapper.selectUsersByAge(age);
    }
}

在Controller层中调用UserService的selectUserselectUsersByAge方法来处理请求:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public User getUser(@RequestParam String name) {
        return userService.selectUser(name);
    }

    @GetMapping("/users/age")
    public List<User> getUsersByAge(@RequestParam Integer age) {
        return userService.selectUsersByAge(age);
    }
}

至此,我们已经完成了查询数据的操作。通过以上的代码示例,我们可以看到使用Mybatis-plus操作json字段非常简单和方便。

总结

本文介绍了如何使用Mybatis-plus来操作json字段,包括字段的插入、更新和查询等操作。通过Mybatis-plus提供的丰富API和灵活配置,我们可以轻松地处理json字段的数据。希望本文对您有所帮助!


全部评论: 0

    我有话说: