实战!Mybatis-plus操作json字段实战

后端动态列设计与实现三部曲,这是最后一步,使用java语言,结合mybatis-plus神技操作json字段。

简单介绍下mybatis-plus,大厂中mybatis使用的非常多,而mybatis-plus是基于mybatis做了扩展,进一步增强,在不影响数据存储的情况下,简化操作方式。有兴趣的朋友可以去官网了解:https://www.baomidou.com/

1、架构图

2、功能

3、表结构

DROP TABLE IF EXISTS user;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 '邮箱',  wallet VARCHAR(3000) NULL DEFAULT NULL COMMENT '钱包',  other_info VARCHAR(3000) NULL DEFAULT NULL COMMENT '其他信息',  PRIMARY KEY (id));
INSERT INTO user (id, name, age, email, wallet, other_info) VALUES(1, 'Jone', 18, '[email protected]', '{"name": "支付宝钱包","currencyList": [{"type": "USD","amount": 999.19},{"type": "RMB","amount": 1000.19}]}', '{"sex": "男","city": "南昌"}'),(2, 'Jack', 20, '[email protected]', '{"name": "微信钱包","currencyList": [{"type": "USD","amount": 888.18},{"type": "RMB","amount": 1000.18}]}', '{"sex": "男","city": "青岛"}');

4、实体定义 

package com.baomidou.mybatisplus.samples.typehandler.entity;

import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableName;import com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler;import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import lombok.Data;import lombok.experimental.Accessors;
/**用户实体对应表 user * @author hubin * @since 2018-08-11 */@Data@Accessors(chain = true)@TableName(autoResultMap = true)public class User {
   
       private Long id;    private String name;    private Integer age;    private String email;
    /**     * 注意!!必须开启映射注解     *     * @TableName(autoResultMap = true)     *     * 以下两种类型处理器,二选一 也可以同时存在     *     * 注意!!选择对应的 JSON 处理器也必须存在对应依赖包     */    @TableField(typeHandler = JacksonTypeHandler.class)    private Wallet wallet;
    @TableField(typeHandler = FastjsonTypeHandler.class)    private OtherInfo otherInfo;}
package com.baomidou.mybatisplus.samples.typehandler.entity;
import java.util.List;
import lombok.Data;
/** * 钱包 */@Datapublic class Wallet {
   
       /**     * 名称     */    private String name;    /**     * 各种货币     */    private List<Currency> currencyList;}

​​​​​​​

package com.baomidou.mybatisplus.samples.typehandler.entity;
import lombok.Data;
/** * 货币 */@Datapublic class Currency {
   
       /**     * 类型: 人民币 RMB , 美元 USD     */    private String type;    /**     * 金额     */    private Double amount;}​​​​​​​
package com.baomidou.mybatisplus.samples.typehandler.entity;
import lombok.Data;
/** * 其他信息 */@Datapublic class OtherInfo {
   
       /**     * 性别     */    private String sex;    /**     * 居住城市     */    private String city;}

5、Dao定义 ​​​​​​​

package com.baomidou.mybatisplus.samples.typehandler.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.baomidou.mybatisplus.samples.typehandler.entity.User;
/** * <p> * MP 支持不需要 UserMapper.xml 这个模块演示内置 CRUD 咱们就不要 XML 部分了 * </p> * * @author hubin * @since 2018-08-11 */public interface UserMapper extends BaseMapper<User> {
   
   }

6、类型转换器​​​​​​​

package com.baomidou.mybatisplus.samples.typehandler.config;
import com.baomidou.mybatisplus.extension.handlers.GsonTypeHandler;import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;import com.fasterxml.jackson.databind.ObjectMapper;import com.google.gson.Gson;import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
/** * @author miemie * @since 2019-11-28 */@Componentpublic class MpJsonConfig implements CommandLineRunner {
   
   
    /**     * 可以set进去自己的     */    @Override    public void run(String... args) throws Exception {
   
           JacksonTypeHandler.setObjectMapper(new ObjectMapper());        GsonTypeHandler.setGson(new Gson());    }}

 7、测试

​​​​​​​

package com.baomidou.mybatisplus.samples.typehandler;
import javax.annotation.Resource;
import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;
import com.baomidou.mybatisplus.samples.typehandler.entity.User;import com.baomidou.mybatisplus.samples.typehandler.mapper.UserMapper;
/** * <p> * 内置 类型处理器 演示 * </p> * * @author hubin * @since 2018-08-11 */@RunWith(SpringRunner.class)@SpringBootTestpublic class SampleTest {
   
   
    @Resource    private UserMapper userMapper;
    /**     * 自定义类型处理器演示参考 mybatis-plus-sample-deluxe 模块     */    @Test    public void test() {
   
           User Jone = userMapper.selectById(1);        System.out.println(Jone);        System.err.println(Jone.getName());
        User Jack = userMapper.selectById(1);        System.err.println(Jack.getName());    }}

结果如下:​​​​​​​

2020-11-22 12:46:58.164  INFO 3168 --- [           main] c.b.m.samples.typehandler.SampleTest     : Started SampleTest in 4.125 seconds (JVM running for 5.707)2020-11-22 12:46:58.477 DEBUG 3168 --- [           main] c.b.m.s.t.mapper.UserMapper.selectById   : ==>  Preparing: SELECT id,name,age,email,wallet,other_info FROM user WHERE id=?2020-11-22 12:46:58.509 DEBUG 3168 --- [           main] c.b.m.s.t.mapper.UserMapper.selectById   : ==> Parameters: 1(Integer)2020-11-22 12:46:58.713 DEBUG 3168 --- [           main] c.b.m.s.t.mapper.UserMapper.selectById   : <==      Total: 1User(id=1, name=Jone, age=18, [email protected], wallet=Wallet(name=支付宝钱包, currencyList=[Currency(type=USD, amount=999.19), Currency(type=RMB, amount=1000.19)]), otherInfo=OtherInfo(sex=男, city=南昌))2020-11-22 12:46:58.715 DEBUG 3168 --- [           main] c.b.m.s.t.mapper.UserMapper.selectById   : ==>  Preparing: SELECT id,name,age,email,wallet,other_info FROM user WHERE id=?2020-11-22 12:46:58.715 DEBUG 3168 --- [           main] c.b.m.s.t.mapper.UserMapper.selectById   : ==> Parameters: 2(Integer)2020-11-22 12:46:58.716 DEBUG 3168 --- [           main] c.b.m.s.t.mapper.UserMapper.selectById   : <==      Total: 1User(id=2, name=Jack, age=20, [email protected], wallet=Wallet(name=微信钱包, currencyList=[Currency(type=USD, amount=888.18), Currency(type=RMB, amount=1000.18)]), otherInfo=OtherInfo(sex=男, city=青岛))2020-11-22 12:46:58.736  INFO 3168 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...2020-11-22 12:46:58.747  INFO 3168 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

总结,使用mybatis-plus可以提高应用程序操作数据库的效率,让开发人员专注于业务逻辑实现。在使用mybatis-plus操作json字段的要点主要有:

1、在需要处理的字段上使用@TableField(typeHandler = JacksonTypeHandler.class),同时实体开启@TableName(autoResultMap = true)

2、注册工具类,MpJsonConfig.

mybatis-plus 还有许多很好用的功能,感兴趣的朋友可以自己去官网上下看,也可能从github或者gitee上拉取最新代码,了解它的工作原理,结合自己的业务做一些增强。欢迎留言交流或者关注以下公众号二维码交流。

猜你喜欢

转载自blog.csdn.net/yelangkingwuzuhu/article/details/109943552