mybatis-plus编程接口

简介

使用Java语言对数据库进行操作,通常需要继承一些依赖Spring容器的ORM框架。在后端项目中非常高效且稳定。但对于一些客户端或者一些临时任务,非Spring环境下想对数据库进行简单的CRUD通常需要使用JDBC来实现,这种方式要自己拼接SQL,效率低且容易出错。直接使用ORM框架的编程接口来进行数据库操作,可以弥补Java语言在客户端类任务的数据库操作短板。

使用步骤

下述示例介绍了使用mybatis-plus的接口来实现数据库的操作。

  1. 在application.properties中新增数据库相关配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://<DB_IP>:<DB_PORT>/<DB_NAME>?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=<USER_NAME>
spring.datasource.password=<PASSWORD>
  1. 引入相关依赖
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
	<version>3.5.5</version>
</dependency>
<dependency>
	<groupId>com.mysql</groupId>
	<artifactId>mysql-connector-j</artifactId>
	<version>8.3.0</version>
</dependency>
  1. 新建工具类:MybatisPlusUtil
public class MybatisPlusUtil {

    private static SqlSessionFactory sqlSessionFactory;

    public static <P, R> R getMapperAndExec(Class<P> clazz, Function<P, R> function) {
        if (sqlSessionFactory == null) {
            initSqlSessionFactory();
        }
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            R r = function.apply(sqlSession.getMapper(clazz));
            sqlSession.commit();
            return r;
        }
    }

    @SneakyThrows
    private static DataSource getDataSource() {
        Properties props = new Properties();
        props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties"));
        String url = props.getProperty("spring.datasource.url");
        String username = props.getProperty("spring.datasource.username");
        String password = props.getProperty("spring.datasource.password");
        String driver = props.getProperty("spring.datasource.driver-class-name");
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(url);
        config.setUsername(username);
        config.setPassword(password);
        config.setDriverClassName(driver);
        return new HikariDataSource(config);
    }

    private static synchronized void initSqlSessionFactory() {
        if (sqlSessionFactory == null) {
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            MybatisConfiguration configuration = new MybatisConfiguration();
            configuration.setMapUnderscoreToCamelCase(true);
            configuration.setUseGeneratedKeys(true);
            configuration.addInterceptor(getPageInterceptor());
            configuration.addMappers("<MAPPER_PACKAGE>");
            configuration.setEnvironment(new Environment("development", new JdbcTransactionFactory(), getDataSource()));
            sqlSessionFactory = builder.build(configuration);
        }
    }

    private static Interceptor getPageInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setDbType(DbType.MYSQL);
        paginationInnerInterceptor.setOverflow(true);
        paginationInnerInterceptor.setMaxLimit(500L);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }
}

测试

  1. 准备数据库表、Mapper以及Entity文件
// UserMapper.java
@MyBatisDao
public interface UserMapper extends BaseMapper<UserEntity>  {
  
}

// UserEntity.java
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_user")
public class UserEntity {

	@TableId(value = "id", type = IdType.AUTO)
    private Long id;
	
	private String username;
	private String password;
}
  1. 新建一个main方法用于测试
public static void main(String[] args) {
	UserEntity user = new UserEntity(null, "jack", "123456");
	MybatisPlusUtil.getMapperAndExec(UserMapper.class, mapper -> mapper.insert(user));
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值