简介
使用Java语言对数据库进行操作,通常需要继承一些依赖Spring容器的ORM框架。在后端项目中非常高效且稳定。但对于一些客户端或者一些临时任务,非Spring环境下想对数据库进行简单的CRUD通常需要使用JDBC来实现,这种方式要自己拼接SQL,效率低且容易出错。直接使用ORM框架的编程接口来进行数据库操作,可以弥补Java语言在客户端类任务的数据库操作短板。
使用步骤
下述示例介绍了使用mybatis-plus的接口来实现数据库的操作。
- 在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>
- 引入相关依赖
<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>
- 新建工具类: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;
}
}
测试
- 准备数据库表、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;
}
- 新建一个main方法用于测试
public static void main(String[] args) {
UserEntity user = new UserEntity(null, "jack", "123456");
MybatisPlusUtil.getMapperAndExec(UserMapper.class, mapper -> mapper.insert(user));
}