Mybatis检测mysql表是否存在

该代码示例展示了如何在Java中使用MyBatis的Mapper接口和XML配置文件,通过information_schema或SHOWTABLESSQL查询来检查数据库中表是否存在。CommonMapper接口提供了两个方法,一个依赖于information_schema表格,另一个使用SHOWTABLES命令。在CommonService类中,实现了检查表是否存在并处理异常的逻辑。

原文1
原文2

1、优先使用information_schema来检查,如果没有查询这个的权限则使用show tables来检查。

mapper:

package com.chenp.demo.dao;

import java.util.Map;
import org.apache.ibatis.annotations.Param;
 
/**
 * 通用的mapper
 * @author cp218
 * @data 2022/12/9 15:57
 *
 */
public interface CommonMapper {
	
    /**
     * 使用information_schema检查表是否存在
     * @param tableSchema
     * @param tableName
     * @return
     */
    Integer checkTableExistsWithSchema(@Param("tableSchema")String tableSchema, @Param("tableName")String tableName);
 
    /**
     * 使用show tables检查表是否存在
     * @param tableName
     * @return
     */
    Map<String, String> checkTableExistsWithShow(@Param("tableName")String tableName);
}

xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chenp.demo.mapper.CommonMapper">

    <select id="checkTableExistsWithSchema"
        resultType="java.lang.Integer">
        SELECT 
        	COUNT(1) 
        FROM information_schema.tables 
        WHERE
        	table_schema = #{tableSchema} 
        	AND table_name = #{tableName}
    </select>
 
    <select id="checkTableExistsWithShow"
        resultType="java.util.Map">
        show tables like #{tableName}
    </select>
    
</mapper>

通用service:

package com.chenp.demo.service;
 
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.yangzhilong.mapper.CommonMapper;
 
import lombok.extern.slf4j.Slf4j;
 
@Service
@Slf4j
public class CommonService {
	
    private static final String TABLE_SCHEMA = "cp_user";
    @Autowired
    private CommonMapper commonMapper;
 
    /**
     * 检查表是否存在
     * @param tableName
     * @return
     */
    public boolean checkTableExists(String tableName) {
        try {
            Integer count = commonMapper.checkTableExistsWithSchema(TABLE_SCHEMA, tableName);
            return count == 1;
        } catch (Exception e) {
            log.error("使用information_schema检测表失败", e);
            Map<String, String> list = commonMapper.checkTableExistsWithShow(tableName);
            if(!CollectionUtils.isEmpty(list)) {
                return true;
            }
        }
 
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值