利用mybatis动态连接mysql

前言

不知到大家在开发中有没有遇到过需要动态连接数据库的问题,比如填写个数据库的账号密码和连接地址测试是否可以连接通、动态配置数据库取表格数据等等;我最近就遇到了这样一个问题需要动态配置连接数据库,并且能够在连接数据库时可以动态查询不同表格的数据。面对这个问题一般解决方案可以是直接利用jdbc连接并测试,但是面对容器化,orm框架的不断涌现,这种原生方案无疑是重复性造轮子,并且还未必有现有的框架好用,所以本文将介绍利用spring boot + mybatis-plus解决该问题。

解决思路

利用mybatis中SqlSessionFactoryBuilder这个类的方法动态构建SqlSessionFactory构建后通过该类不断创建SqlSession来实现sql语句的动态查询功能,为方便使用本文同时还根据前沿中所遇到的问题构建了一个mapper类。

具体实现

mapper构建工具类MySQLConnectUtil

/**
 * 数据库动态连接工具类
 * @author wsy
 */
public class MySQLConnectUtil {
    private static ThreadLocal<MySQLSession> currentSqlSession;

    static {
        currentSqlSession = new ThreadLocal<>();
    }

    /**
     * 获取session
     *
     * @param password 密码
     * @param url      地址
     * @param username 用户名
     * @param port     端口
     * @return MySQLLog
     */
    public static MySQLLogMapper getSession(String url, String username, String password, String databaseName, int port) {
        try {
            Properties properties = new Properties();
            properties.setProperty("jdbc.driver", "com.mysql.cj.jdbc.Driver");
            properties.setProperty("jdbc.url", String.format("jdbc:mysql://%s:%s/%s?useSSL=false",
                    url, port, databaseName));
            properties.setProperty("jdbc.username", username);
            properties.setProperty("jdbc.password", password);
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, properties);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            MySQLLogMapper mySQLLogMapper = sqlSession.getMapper(MySQLLogMapper.class);
            currentSqlSession.set(MySQLSession.build()
                    .setSqlSession(sqlSession).setSqlSessionFactory(sqlSessionFactory));
            return mySQLLogMapper;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取session
     * @param mySQLSession 会话对象
     * @return MySQLLog
     */
    public static MySQLLogMapper getSession(MySQLSession mySQLSession) {
        SqlSession sqlSession = mySQLSession.getSqlSessionFactory().openSession();
        mySQLSession.setSqlSession(sqlSession);
        return sqlSession.getMapper(MySQLLogMapper.class);
    }

    public static MySQLSession getMySQLSession() {
        return currentSqlSession.get();
    }


    /**
     * 关闭数据库连接
     * */
    public static void closeSqlSession() {
        currentSqlSession.get().getSqlSession().close();
    }

    /**
     * 关闭数据库连接
     * @param mySQLSession 会话对象
     * */
    public static void closeSqlSession(MySQLSession mySQLSession) {
        mySQLSession.getSqlSession().close();
    }
}

注:这里使用mapper接口时要留意sqlSession的一级缓存,如果不想受一级缓存影响导致脏数据的话,可以每次使用完关掉创建mapper对象的sqlSession类

mapper类MySQLLogMapper

/**
 * 通用数据查询mapper
 * @author wsy
 */
public interface MySQLLogMapper {
    /**
     * 根据表名统计数据
     * @param tableName 表名
     * @return int
     * */
    int count(@Param("tableName") String tableName);

    /**
     * 查询数据,最大为10w条
     * @param tableName 表名
     * @param cloum 表字段(一般用于查询游标)
     * @param cur 当前游标值
     * @return Map<String, Object>
     * */
    List<Map<String, Object>> selectData(@Param("tableName") String tableName, @Param("cloum") String cloum, @Param("cur") Object cur);

    /**
     * 获取某个表的主键
     * @param tableName 表名
     * @return List<Map<String, Object>>
     * */
    List<Map<String, Object>> selectPrimaryKey(@Param("tableName") String tableName);
}

mapper类关联的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.purplestorm.sendemail.mapper.MySQLLogMapper">


    <select id="count" resultType="java.lang.Integer">
        select count(*) from ${tableName} <where>
            <if test="cur != null and cloum != null">
                ${cloum} > #{cur}
            </if>
        </where>;
    </select>

    <select id="selectData" resultType="java.util.LinkedHashMap">
        select * from ${tableName}
            <where>
              <if test="cur != null and cloum != null">
                 ${cloum} > #{cur}
              </if>
            </where>
            limit <if test="cur != null and cloum == null">
                 #{cur},
            </if>10000;
    </select>
    <select id="selectPrimaryKey" resultType="java.util.LinkedHashMap">
        SHOW INDEX FROM ${tableName} where Key_name = 'PRIMARY';
    </select>
</mapper>

会话连接类MySQLSession

/**
 * 连接会话类
 * @author wsy
 */
public class MySQLSession {

    public static MySQLSession build() {
        return new MySQLSession();
    }

    /**
     * 会话连接
     * */
    private SqlSession sqlSession;

    public SqlSession getSqlSession() {
        return sqlSession;
    }

    public MySQLSession setSqlSession(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
        return this;
    }

    public SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    public MySQLSession setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
        return this;
    }

    /**
     * 会话连接生产工厂
     * */
    private SqlSessionFactory sqlSessionFactory;

    public void closeSession() {
        this.sqlSession.close();
    }
}

mybatis-config.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- 控制台打印sql语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!-- 开启驼峰命名自动映射配置 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--关闭一级缓存 -->
        <setting name="cacheEnabled" value="false"/>
        <!-- 设置一级缓存的作用范围是一条sql语句执行期间,执行完毕清空一级缓存-->
        <setting name="localCacheScope" value="STATEMENT"/>
    </settings>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/MySQLLogMapper.xml"/>
    </mappers>

</configuration>

xml文件放置位置

在这里插入图片描述
注:如果mapper.xml未生效可以尝试clean后再install后启动项目,如果还未生效请检查mybatis-plus.mapper-locations配置是否为classpath:/mapper/*Mapper.xml

结语

对于如上解决方案可能并非最优解,仅供大家参考学习,如有不妥之处或问题欢迎评论区留言或私信。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中整合MyBatis并使用MySQL实现主键UUID的方法如下: 1. 首先,在MySQL数据库中创建一个表,其中包含一个varchar类型的字段用于存储UUID。示例表结构如下: ``` CREATE TABLE `example_table` ( `id` varchar(36) NOT NULL, `name` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` 2. 在Spring Boot的配置文件(application.properties或application.yml)中,配置数据库连接信息。 ``` spring.datasource.url=jdbc:mysql://localhost:3306/example_database spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3. 创建一个实体类Example,表示数据库中的表。 ```java public class Example { private String id; private String name; // getter和setter方法省略... } ``` 4. 创建一个Mapper接口ExampleMapper,用于执行数据库操作。 ```java public interface ExampleMapper { void insertExample(Example example); Example selectExampleById(String id); // 其他数据库操作方法... } ``` 5. 创建一个Mapper的XML文件ExampleMapper.xml,定义对应的SQL语句。 ```xml <mapper namespace="com.example.mapper.ExampleMapper"> <insert id="insertExample" parameterType="com.example.entity.Example"> INSERT INTO example_table(id, name) VALUES (#{id}, #{name}) </insert> <select id="selectExampleById" parameterType="java.lang.String" resultType="com.example.entity.Example"> SELECT * FROM example_table WHERE id = #{id} </select> <!-- 其他SQL语句定义... --> </mapper> ``` 6. 在Spring Boot的主类中使用@MapperScan注解扫描Mapper接口所在的包。 ```java @SpringBootApplication @MapperScan("com.example.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 7. 然后就可以在代码中使用ExampleMapper接口进行数据库操作了。在需要插入数据的地方,使用UUID生成一个唯一的ID,并将其设置到实体类中,然后调用insertExample方法插入数据。 ```java @Autowired private ExampleMapper exampleMapper; public void insertExample() { Example example = new Example(); example.setId(UUID.randomUUID().toString()); example.setName("example name"); exampleMapper.insertExample(example); } ``` 通过以上步骤,就可以在Spring Boot项目中通过MyBatisMySQL实现主键UUID的方式进行数据操作了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值