亲宝软件园·资讯

展开

Mybatis-plus操作json字段实战教程

夜郎king 人气:0

后端动态列设计与实现三部曲,这是最后一步,使用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, 'test1@baomidou.com', '{"name": "支付宝钱包","currencyList": [{"type": "USD","amount": 999.19},{"type": "RMB","amount": 1000.19}]}', '{"sex": "男","city": "南昌"}'),
(2, 'Jack', 20, 'test2@baomidou.com', '{"name": "微信钱包","currencyList": [{"type": "USD","amount": 888.18},{"type": "RMB","amount": 1000.18}]}', '{"sex": "男","city": "青岛"}');
INSERT INTO user (id, name, age, email, wallet, other_info) VALUES
(1, 'Jone', 18, 'test1@baomidou.com', '{"name": "支付宝钱包","currencyList": [{"type": "USD","amount": 999.19},{"type": "RMB
(2, 'Jack', 20, 'test2@baomidou.com', '{"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;

/**
 * 钱包
 */
@Data
public class Wallet {
    /**
     * 名称
     */
    private String name;
    /**
     * 各种货币
     */
    private List<Currency> currencyList;
}
package com.baomidou.mybatisplus.samples.typehandler.entity;

import lombok.Data;

/**
 * 货币
 */
@Data
public class Currency {
    /**
     * 类型: 人民币 RMB , 美元 USD
     */
    private String type;
    /**
     * 金额
     */
    private Double amount;
}
package com.baomidou.mybatisplus.samples.typehandler.entity;
import lombok.Data;

/**
 * 其他信息
 */
@Data
public 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
 */
@Component
public 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)
@SpringBootTest
public 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: 1
User(id=1, name=Jone, age=18, email=test1@baomidou.com, 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: 1
User(id=2, name=Jack, age=20, email=test2@baomidou.com, 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 c

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

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

2、注册工具类,MpJsonConfig.

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

加载全部内容

相关教程
猜你喜欢
用户评论