非spring项目使用mybatis-plus

非spring项目使用mybatis-plus
写在前面
初始化项目
项目最终结构如下
使用junit初始化数据源
编写测试代码
运行效果如下
构建mybatis-plus里面的SqlSessionFactoryBuilder对象
创建entity对象
创建mapper接口
创建mapper.xml
编写单元测试方法
添加after方法,用于方法执行完毕,关闭session
测试mybatis-plus的增删改查
selectList
insert
selectPage
updateById
deleteById
testFindAll
testFindAllPage
junit全部代码如下
sql
写在后面
写在前面
这里讲解如何在非spring项目下使用mybatis-plus,并集成mybatis-plus的特性,实现数据库的增删改查
1
初始化项目
项目由maven构建,并且使用junit做项目测试实验,pom配置如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lhstack.mybatis</groupId>
    <artifactId>mybatis-plus-test</artifactId>
    <version>0.0.1</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <mybatis-plus.version>3.4.3</mybatis-plus.version>
        <hikaricp.version>4.0.3</hikaricp.version>
        <mysql.version>8.0.23</mysql.version>
        <junit.version>4.13</junit.version>
        <slf4j.version>1.7.31</slf4j.version>
        <logback.version>1.2.3</logback.version>
    </properties>


    <dependencies>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-extension -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-extension</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>${hikaricp.version}</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**</include>
                </includes>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**</include>
                </includes>
            </testResource>
        </testResources>
    </build>

</project>



项目最终结构如下


使用junit初始化数据源
编写测试代码
    

@Test
    public void testDataSource() throws Exception {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://192.168.101.150:3306/cms?allowPublicKeyRetrieval=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&useUnicode=true");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setIdleTimeout(60000);
        dataSource.setAutoCommit(true);
        dataSource.setMaximumPoolSize(5);
        dataSource.setMinimumIdle(1);
        dataSource.setMaxLifetime(60000 * 10);
        dataSource.setConnectionTestQuery("SELECT 1");
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("show table status");
        ResultSet resultSet = preparedStatement.executeQuery();
        while(resultSet.next()){
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                String name = metaData.getColumnLabel(i);
                String field = resultSet.getString(i);
                System.out.printf("%s:%s\t",name,field);
            }
            System.out.println();
        }
    }



运行效果如下

 

 


构建mybatis-plus里面的SqlSessionFactoryBuilder对象
 

   @Before
    public void before() throws IOException {
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //这是mybatis-plus的配置对象,对mybatis的Configuration进行增强
        MybatisConfiguration configuration = new MybatisConfiguration();
        //这是初始化配置,后面会添加这部分代码
        initConfiguration(configuration);
        //这是初始化连接器,如mybatis-plus的分页插件
        configuration.addInterceptor(initInterceptor());
        //配置日志实现
        configuration.setLogImpl(Slf4jImpl.class);
        //扫描mapper接口所在包
        configuration.addMappers("com.lhstack.mybatis.mapper");
        //构建mybatis-plus需要的globalconfig
        GlobalConfig globalConfig = new GlobalConfig();
        //此参数会自动生成实现baseMapper的基础方法映射
        globalConfig.setSqlInjector(new DefaultSqlInjector());
        //设置id生成器
        globalConfig.setIdentifierGenerator(new DefaultIdentifierGenerator());
        //设置超类mapper
        globalConfig.setSuperMapperClass(BaseMapper.class);
        //给configuration注入GlobalConfig里面的配置
        GlobalConfigUtils.setGlobalConfig(configuration, globalConfig);
        //设置数据源
        Environment environment = new Environment("1", new JdbcTransactionFactory(), initDataSource());
        configuration.setEnvironment(environment);

        this.registryMapperXml(configuration, "mapper");
        //构建sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = builder.build(configuration);
        //创建session
        this.session = sqlSessionFactory.openSession();
    }
    /**
     * 初始化配置
     *
     * @param configuration
     */
    private void initConfiguration(MybatisConfiguration configuration) {
        //开启驼峰大小写转换
        configuration.setMapUnderscoreToCamelCase(true);
        //配置添加数据自动返回数据主键
        configuration.setUseGeneratedKeys(true);
    }
    
    /**
     * 初始化数据源
     *
     * @return
     */
    private DataSource initDataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://192.168.101.150:3306/cms?allowPublicKeyRetrieval=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&useUnicode=true");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setIdleTimeout(60000);
        dataSource.setAutoCommit(true);
        dataSource.setMaximumPoolSize(5);
        dataSource.setMinimumIdle(1);
        dataSource.setMaxLifetime(60000 * 10);
        dataSource.setConnectionTestQuery("SELECT 1");
        return dataSource;
    }
    /**
     * 初始化拦截器
     *
     * @return
     */
    private Interceptor initInterceptor() {
        //创建mybatis-plus插件对象
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //构建分页插件
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setDbType(DbType.MYSQL);
        paginationInnerInterceptor.setOverflow(true);
        paginationInnerInterceptor.setMaxLimit(500L);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }
    
    /**
     * 解析mapper.xml文件
     * @param configuration
     * @param classPath
     * @throws IOException
     */
    private void registryMapperXml(MybatisConfiguration configuration, String classPath) throws IOException {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        Enumeration<URL> mapper = contextClassLoader.getResources(classPath);
        while (mapper.hasMoreElements()) {
            URL url = mapper.nextElement();
            if (url.getProtocol().equals("file")) {
                String path = url.getPath();
                File file = new File(path);
                File[] files = file.listFiles();
                for (File f : files) {
                    FileInputStream in = new FileInputStream(f);
                    XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(in, configuration, f.getPath(), configuration.getSqlFragments());
                    xmlMapperBuilder.parse();
                    in.close();
                }
            } else {
                JarURLConnection urlConnection = (JarURLConnection) url.openConnection();
                JarFile jarFile = urlConnection.getJarFile();
                Enumeration<JarEntry> entries = jarFile.entries();
                while (entries.hasMoreElements()) {
                    JarEntry jarEntry = entries.nextElement();
                    if (jarEntry.getName().endsWith(".xml")) {
                        InputStream in = jarFile.getInputStream(jarEntry);
                        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(in, configuration, jarEntry.getName(), configuration.getSqlFragments());
                        xmlMapperBuilder.parse();
                        in.close();
                    }
                }
            }
        }
    }



创建entity对象

package com.lhstack.mybatis.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.util.Date;

@TableName(value = "t_user")
public class User {

    @TableId(type = IdType.AUTO)
    private Integer id;

    private Date createTime;

    private String description;

    private String email;

    private Boolean enable;

    private String name;

    private String password;

    private String pic;

    private String salt;

    private Date updateTime;

    private String username;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Boolean getEnable() {
        return enable;
    }

    public void setEnable(Boolean enable) {
        this.enable = enable;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", createTime=" + createTime +
                ", description='" + description + '\'' +
                ", email='" + email + '\'' +
                ", enable=" + enable +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", pic='" + pic + '\'' +
                ", salt='" + salt + '\'' +
                ", updateTime=" + updateTime +
                ", username='" + username + '\'' +
                '}';
    }
}


创建mapper接口

package com.lhstack.mybatis.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lhstack.mybatis.entity.User;

import java.util.List;

public interface UserMapper extends BaseMapper<User> {

    List<User> findAll();
}


创建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.lhstack.mybatis.mapper.UserMapper">
    <select id="findAll" resultType="com.lhstack.mybatis.entity.User">
        SELECT * FROM t_user
    </select>
</mapper>



编写单元测试方法
添加after方法,用于方法执行完毕,关闭session

    @After
    public void after() {
        this.session.commit();
        this.session.close();
    }


测试mybatis-plus的增删改查
selectList

    @Test
    public void testSelectList() {
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> users = mapper.selectList(new QueryWrapper<>());
        System.out.println(users);
    }


insert

    @Test
    public void testInsert(){
        User user = new User();
        user.setCreateTime(new Date());
        user.setDescription("test");
        user.setPassword("123456");
        user.setUsername("test");
        user.setEnable(true);
        user.setEmail("xxx@qq.com");
        user.setUpdateTime(new Date());
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.insert(user);
        System.out.println(user);
    }


selectPage

    @Test
    public void testSelectPage(){
        UserMapper mapper = session.getMapper(UserMapper.class);
        Page<User> pageResult = mapper.selectPage(new Page<>(1, 1), new QueryWrapper<>());
        System.out.println(pageResult.getTotal());
        System.out.println(pageResult.getPages());
        System.out.println(pageResult.getRecords());
    }

    @Test
    public void testSelectPage(){
        UserMapper mapper = session.getMapper(UserMapper.class);
        Page<User> pageResult = mapper.selectPage(new Page<>(2, 1), new QueryWrapper<>());
        System.out.println(pageResult.getTotal());
        System.out.println(pageResult.getPages());
        System.out.println(pageResult.getRecords());
    }


updateById

    @Test
    public void testUpdate(){
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = mapper.selectById(5);
        user.setName("test");
        user.setUpdateTime(new Date());
        user.setPassword("654321");
        user.setDescription("update");
        mapper.updateById(user);
        System.out.println(user);
    }


deleteById

    @Test
    public void testDelete(){
        UserMapper mapper = session.getMapper(UserMapper.class);
        int result = mapper.deleteById(5);
        System.out.println(result);
        this.testSelectList();
    }


testFindAll
junit

    @Test
    public void testFindAll(){
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> list = mapper.findAll();
        System.out.println(list);
    }




UserMapper.java

List<User> findAll();

UserMapper.xml

    <select id="findAll" resultType="com.lhstack.mybatis.entity.User">
        SELECT * FROM t_user
    </select>


testFindAllPage
junit

    @Test
    public void testFindAllPage(){
        UserMapper mapper = session.getMapper(UserMapper.class);
        this.testInsert();
        Page<User> pageResult = mapper.findAllPage(new Page<>(1, 1));
        System.out.println(pageResult.getTotal());
        System.out.println(pageResult.getPages());
        System.out.println(pageResult.getRecords());
    }



UserMapper.java

    Page<User> findAllPage(Page<User> page);



UserMapper.xml

 

   <select id="findAllPage" resultType="com.lhstack.mybatis.entity.User">
        SELECT * FROM t_user
    </select>



junit全部代码如下

package com.lhstack.mybatis;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lhstack.mybatis.entity.User;
import com.lhstack.mybatis.mapper.UserMapper;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

@RunWith(JUnit4.class)
public class MybatisPlusApplicationTests {

    private SqlSession session;

    @Before
    public void before() throws IOException {
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        MybatisConfiguration configuration = new MybatisConfiguration();
        initConfiguration(configuration);
        configuration.addInterceptor(initInterceptor());
        //扫描mapper接口所在包
        configuration.addMappers("com.lhstack.mybatis.mapper");
        //配置日志实现
        configuration.setLogImpl(Slf4jImpl.class);
        //构建mybatis-plus需要的globalconfig
        GlobalConfig globalConfig = new GlobalConfig();
        //此参数会自动生成实现baseMapper的基础方法映射
        globalConfig.setSqlInjector(new DefaultSqlInjector());
        //设置id生成器
        globalConfig.setIdentifierGenerator(new DefaultIdentifierGenerator());
        //设置超类mapper
        globalConfig.setSuperMapperClass(BaseMapper.class);

        //给configuration注入GlobalConfig里面的配置
        GlobalConfigUtils.setGlobalConfig(configuration, globalConfig);
        //设置数据源
        Environment environment = new Environment("1", new JdbcTransactionFactory(), initDataSource());
        configuration.setEnvironment(environment);

        this.registryMapperXml(configuration, "mapper");
        //构建sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = builder.build(configuration);
        this.session = sqlSessionFactory.openSession();

    }

    @After
    public void after() {
        this.session.commit();
        this.session.close();
    }

    /**
     * 初始化配置
     *
     * @param configuration
     */
    private void initConfiguration(MybatisConfiguration configuration) {
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setUseGeneratedKeys(true);
    }

    /**
     * 初始化数据源
     *
     * @return
     */
    private DataSource initDataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://192.168.101.150:3306/cms?allowPublicKeyRetrieval=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&useUnicode=true");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setIdleTimeout(60000);
        dataSource.setAutoCommit(true);
        dataSource.setMaximumPoolSize(5);
        dataSource.setMinimumIdle(1);
        dataSource.setMaxLifetime(60000 * 10);
        dataSource.setConnectionTestQuery("SELECT 1");
        return dataSource;
    }

    /**
     * 初始化拦截器
     *
     * @return
     */
    private Interceptor initInterceptor() {
        //创建mybatis-plus插件对象
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //构建分页插件
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setDbType(DbType.MYSQL);
        paginationInnerInterceptor.setOverflow(true);
        paginationInnerInterceptor.setMaxLimit(500L);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }


    /**
     * 解析mapper.xml文件
     *
     * @param configuration
     * @param classPath
     * @throws IOException
     */
    private void registryMapperXml(MybatisConfiguration configuration, String classPath) throws IOException {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        Enumeration<URL> mapper = contextClassLoader.getResources(classPath);
        while (mapper.hasMoreElements()) {
            URL url = mapper.nextElement();
            if (url.getProtocol().equals("file")) {
                String path = url.getPath();
                File file = new File(path);
                File[] files = file.listFiles();
                for (File f : files) {
                    FileInputStream in = new FileInputStream(f);
                    XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(in, configuration, f.getPath(), configuration.getSqlFragments());
                    xmlMapperBuilder.parse();
                    in.close();
                }
            } else {
                JarURLConnection urlConnection = (JarURLConnection) url.openConnection();
                JarFile jarFile = urlConnection.getJarFile();
                Enumeration<JarEntry> entries = jarFile.entries();
                while (entries.hasMoreElements()) {
                    JarEntry jarEntry = entries.nextElement();
                    if (jarEntry.getName().endsWith(".xml")) {
                        InputStream in = jarFile.getInputStream(jarEntry);
                        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(in, configuration, jarEntry.getName(), configuration.getSqlFragments());
                        xmlMapperBuilder.parse();
                        in.close();
                    }
                }
            }
        }
    }

    @Test
    public void testInsert() {
        User user = new User();
        user.setCreateTime(new Date());
        user.setDescription(UUID.randomUUID() + "test");
        user.setPassword(UUID.randomUUID() + "123456");
        user.setUsername(UUID.randomUUID().toString());
        user.setEnable(true);
        user.setEmail(UUID.randomUUID() + "xxx@qq.com");
        user.setUpdateTime(new Date());
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.insert(user);
        System.out.println(user);
    }

    @Test
    public void testSelectPage() {
        UserMapper mapper = session.getMapper(UserMapper.class);
        Page<User> pageResult = mapper.selectPage(new Page<>(2, 1), new QueryWrapper<>());
        System.out.println(pageResult.getTotal());
        System.out.println(pageResult.getPages());
        System.out.println(pageResult.getRecords());
    }

    @Test
    public void testDelete() {
        UserMapper mapper = session.getMapper(UserMapper.class);
        int result = mapper.deleteById(5);
        System.out.println(result);
        this.testSelectList();
    }

    @Test
    public void testUpdate() {
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = mapper.selectById(5);
        user.setName("test");
        user.setUpdateTime(new Date());
        user.setPassword("654321");
        user.setDescription("update");
        mapper.updateById(user);
        System.out.println(user);
    }

    @Test
    public void testSelectList() {
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> users = mapper.selectList(new QueryWrapper<>());
        System.out.println(users);
    }

    @Test
    public void testFindAll() {
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> list = mapper.findAll();
        System.out.println(list);
    }

    @Test
    public void testFindAllPage() {
        UserMapper mapper = session.getMapper(UserMapper.class);
        this.testInsert();
        Page<User> pageResult = mapper.findAllPage(new Page<>(1, 1));
        System.out.println(pageResult.getTotal());
        System.out.println(pageResult.getPages());
        System.out.println(pageResult.getRecords());
    }


    @Test
    public void testDataSource() throws Exception {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://192.168.101.150:3306/cms?allowPublicKeyRetrieval=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&useUnicode=true");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setIdleTimeout(60000);
        dataSource.setAutoCommit(true);
        dataSource.setMaximumPoolSize(5);
        dataSource.setMinimumIdle(1);
        dataSource.setMaxLifetime(60000 * 10);
        dataSource.setConnectionTestQuery("SELECT 1");
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("show table status");
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                String name = metaData.getColumnLabel(i);
                String field = resultSet.getString(i);
                System.out.printf("%s:%s\t", name, field);
            }
            System.out.println();
        }
    }

}





sql

CREATE TABLE `t_user`  (
  `id` int(0) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `create_time` datetime(6) NULL DEFAULT NULL COMMENT '日期',
  `description` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `email` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `enable` bit(1) NULL DEFAULT NULL,
  `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `password` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `pic` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `salt` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  `update_time` datetime(6) NULL DEFAULT NULL,
  `username` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `idx_username`(`username`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = 'aa' ROW_FORMAT = Dynamic;

1


写在后面
以上就是如何在非spring的项目环境下使用mybatis-plus,理论上这种写法也可以用在android上面
 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值