09_Mybatis-plus类型处理器示例,例如 json 字段对象转换

09_Mybatis-plus类型处理器示例,例如 json 字段对象转换_第1张图片

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 '邮箱',
	wallets VARCHAR(3000) NULL DEFAULT NULL COMMENT '钱包',
	other_info VARCHAR(3000) NULL DEFAULT NULL COMMENT '其他信息',
	PRIMARY KEY (id)
);

DELETE FROM user;

INSERT INTO user (id, name, age, email, wallets, other_info) VALUES
(1, 'Jone', 18, '[email protected]', '[{
    "name": "支付宝钱包",
    "currencyList": [{
        "type": "USD",
        "amount": 999.19
    },{
        "type": "RMB",
        "amount": 1000.19
    }]
},{
    "name": "微信钱包",
    "currencyList": [{
        "type": "USD",
        "amount": 888.18
    },{
        "type": "RMB",
        "amount": 1000.18
    }]
}]', '{
        "sex": "男",
        "city": "南昌"
}'),
(2, 'Jack', 20, '[email protected]', '[{
    "name": "银联钱包",
    "currencyList": [{
        "type": "USD",
        "amount": 888.18
    },{
        "type": "RMB",
        "amount": 1000.18
    }]
}]', '{
        "sex": "男",
        "city": "青岛"
}');
package com.zs.testmybatisplus;

import java.io.IOException;
import java.util.List;

import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.fasterxml.jackson.core.type.TypeReference;
import com.zs.testmybatisplus.entity.Wallet;

/**
 * 自定义复杂类型处理器
* 不要问我为什么要重写 parse 因为顶层父类是无法获取到准确的待转换复杂返回类型数据 */
public class WalletListTypeHandler extends JacksonTypeHandler { public WalletListTypeHandler(Class<?> type) { super(type); } @Override protected Object parse(String json) { try { /** * [{ * "name": "银联钱包", * "currencyList": [ * { * "type": "USD", * "amount": 888.18 * }, * { * "type": "RMB", * "amount": 1000.18 * } * ] * }] */ return getObjectMapper().readValue(json, new TypeReference<List<Wallet>>() { }); } catch (IOException e) { throw new RuntimeException(e); } } }
package com.zs.testmybatisplus.config;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

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;

/**
 * @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());
    }
}

1实体类

package com.zs.testmybatisplus.entity;

import java.util.List;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler;
import com.zs.testmybatisplus.WalletListTypeHandler;

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 = WalletListTypeHandler.class) private List<Wallet> wallets; @TableField(typeHandler = FastjsonTypeHandler.class) private OtherInfo otherInfo; }

package com.zs.testmybatisplus.entity;

import java.util.List;

import lombok.Data;

/**
 * 钱包
 */
@Data
public class Wallet {
    /**
     * 名称
     */
    private String name;
    /**
     * 各种货币
     */
    private List<Currency> currencyList;
}

package com.zs.testmybatisplus.entity;

import lombok.Data;

/**
 * 其他信息
 */
@Data
public class OtherInfo {
    /**
     * 性别
     */
    private String sex;
    /**
     * 居住城市
     */
    private String city;
}

package com.zs.testmybatisplus.entity;

import lombok.Data;

/**
 * 货币
 */
@Data
public class Currency {
    /**
     * 类型: 人民币 RMB , 美元 USD
     */
    private String type;
    /**
     * 金额
     */
    private Double amount;
}

2mapper

package com.zs.testmybatisplus.mapper;


import org.apache.ibatis.annotations.Mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zs.testmybatisplus.entity.User;

/**
 * 

* MP 支持不需要 UserMapper.xml 这个模块演示内置 CRUD 咱们就不要 XML 部分了 *

* * @author hubin * @since 2018-08-11 */
@Mapper public interface UserMapper extends BaseMapper<User> { }

3测试类

package com.zs.testmybatisplus;

import javax.annotation.Resource;

import org.junit.Assert;
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.zs.testmybatisplus.entity.User;
import com.zs.testmybatisplus.mapper.UserMapper;


/**
 * 

* 内置 类型处理器 演示 *

* * @author hubin * @since 2018-08-11 */
@RunWith(SpringRunner.class) @SpringBootTest public class SampleTest { @Resource private UserMapper userMapper; /** * 自定义类型处理器演示 */ @Test public void test(){ /** * SELECT id,name,age,email,wallets,other_info FROM user WHERE id=? * <== Columns: id, name, age, email, wallets, other_info * <== Row: 1, Jone, 18, [email protected], [{ * "name": "支付宝钱包", * "currencyList": [{ * "type": "USD", * "amount": 999.19 * },{ * "type": "RMB", * "amount": 1000.19 * }] * },{ * "name": "微信钱包", * "currencyList": [{ * "type": "USD", * "amount": 888.18 * },{ * "type": "RMB", * "amount": 1000.18 * }] * }], { * "sex": "男", * "city": "南昌" * } */ /** * [{ * "name": "银联钱包", * "currencyList": [ * { * "type": "USD", * "amount": 888.18 * }, * { * "type": "RMB", * "amount": 1000.18 * } * ] * }] */ /** * { * "sex": "男", * "city": "南昌" * } */ User Jone = userMapper.selectById(1); Assert.assertEquals("Jone", Jone.getName()); Assert.assertEquals(2, Jone.getWallets().size()); Assert.assertEquals("微信钱包", Jone.getWallets().get(1).getName()); User Jack = userMapper.selectById(2); Assert.assertEquals("Jack", Jack.getName()); Assert.assertEquals(1, Jack.getWallets().size()); Assert.assertEquals("银联钱包", Jack.getWallets().get(0).getName()); } }

你可能感兴趣的:(MybatisPlus,json,java,开发语言)