溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

mybatis plus中怎么自定義主鍵生成器IKeyGenerator

發(fā)布時(shí)間:2021-08-06 14:54:24 來(lái)源:億速云 閱讀:1681 作者:Leah 欄目:編程語(yǔ)言

本篇文章為大家展示了mybatis plus中怎么自定義主鍵生成器IKeyGenerator,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

1. 繼承IKeyGenerator

@Slf4j
@Component
public class MybatisKeyGenerator implements IKeyGenerator {
 
	@Value("${server.worker-id}")
	private Integer workerId;
 
	@Value("${server.data-center-id}")
	private Integer dataCenterId;
 
	@Override
	public String executeSql(String incrementerName) {
		log.info("mybatis plus keyGenerator: " + incrementerName + "(" + workerId + "," + dataCenterId + ")");
		long uid = new SnowflakeIdWorker(workerId, dataCenterId).nextId();
		return "select " + uid + " from dual";
	}
}

2. 定義entity, 需要有@KeySequence注解,和IdType.INPUT或者IdType.ID_WORKER

@Data
@TableName("test1")
@KeySequence("mybatisKeyGenerator")
public class Test {
	@TableId(type = IdType.INPUT)
	private Long id;
	private String name;
}

 3.測(cè)試:

@Autowired
private TestMapper testMapper;
@Override
public void run(String... args) throws Exception {
	Test test = new Test();
	test.setName("CCC"+ LocalDateTime.now());
	testMapper.insert(test);
	System.out.println(">>>> test:"+ test);
}

源碼查看:

1. com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration

// 從spring容器中獲取IKeyGenerator
//注入主鍵生成器
if (this.applicationContext.getBeanNamesForType(IKeyGenerator.class, false,
	false).length > 0) {
	IKeyGenerator keyGenerator = this.applicationContext.getBean(IKeyGenerator.class);
	globalConfig.getDbConfig().setKeyGenerator(keyGenerator);
}

2. 在掃描實(shí)體時(shí)候,會(huì)掃描KeySequence注解

/* 開啟了自定義 KEY 生成器 */
if (null != dbConfig.getKeyGenerator()) {
   tableInfo.setKeySequence(clazz.getAnnotation(KeySequence.class));
}

3. 插入數(shù)據(jù)時(shí):com.baomidou.mybatisplus.core.injector.methods.Insert

// 表包含主鍵處理邏輯,如果不包含主鍵當(dāng)普通字段處理
if (StringUtils.isNotEmpty(tableInfo.getKeyProperty())) {
	if (tableInfo.getIdType() == IdType.AUTO) {
		/** 自增主鍵 */
		keyGenerator = new Jdbc3KeyGenerator();
		keyProperty = tableInfo.getKeyProperty();
		keyColumn = tableInfo.getKeyColumn();
	} else {
 
        // 如果有注解,則獲取自定義的主鍵生成器
		if (null != tableInfo.getKeySequence()) {
            // 這里獲取的就是注入的生成器,執(zhí)行生成器接口executeSql,傳入值為注解里面的value
			keyGenerator = TableInfoHelper.genKeyGenerator(tableInfo, builderAssistant, sqlMethod.getMethod(), languageDriver);
			keyProperty = tableInfo.getKeyProperty();
			keyColumn = tableInfo.getKeyColumn();
		}
	}
}

4. 

    /**
     * <p>
     * 自定義 KEY 生成器
     * </p>
     */
    public static KeyGenerator genKeyGenerator(TableInfo tableInfo, MapperBuilderAssistant builderAssistant,
                                               String baseStatementId, LanguageDriver languageDriver) {
        IKeyGenerator keyGenerator = GlobalConfigUtils.getKeyGenerator(builderAssistant.getConfiguration());
        if (null == keyGenerator) {
            throw new IllegalArgumentException("not configure IKeyGenerator implementation class.");
        }
        String id = baseStatementId + SelectKeyGenerator.SELECT_KEY_SUFFIX;
        Class<?> resultTypeClass = tableInfo.getKeySequence().clazz();
        StatementType statementType = StatementType.PREPARED;
        String keyProperty = tableInfo.getKeyProperty();
        String keyColumn = tableInfo.getKeyColumn();
 
        // 執(zhí)行語(yǔ)句keyGenerator.executeSql(tableInfo.getKeySequence().value())
        SqlSource sqlSource = languageDriver.createSqlSource(builderAssistant.getConfiguration(),
            keyGenerator.executeSql(tableInfo.getKeySequence().value()), null);
        builderAssistant.addMappedStatement(id, sqlSource, statementType, SqlCommandType.SELECT, null, null, null,
            null, null, resultTypeClass, null, false, false, false,
            new NoKeyGenerator(), keyProperty, keyColumn, null, languageDriver, null);
        id = builderAssistant.applyCurrentNamespace(id, false);
        MappedStatement keyStatement = builderAssistant.getConfiguration().getMappedStatement(id, false);
        SelectKeyGenerator selectKeyGenerator = new SelectKeyGenerator(keyStatement, true);
        builderAssistant.getConfiguration().addKeyGenerator(id, selectKeyGenerator);
        return selectKeyGenerator;
    }

上述內(nèi)容就是mybatis plus中怎么自定義主鍵生成器IKeyGenerator,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI