89 lines
2.6 KiB
Java
89 lines
2.6 KiB
Java
|
|
package com.common.util;
|
|||
|
|
|
|||
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|||
|
|
import org.apache.ibatis.io.Resources;
|
|||
|
|
import org.apache.ibatis.session.SqlSession;
|
|||
|
|
import org.apache.ibatis.session.SqlSessionFactory;
|
|||
|
|
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
|
|||
|
|
import org.slf4j.Logger;
|
|||
|
|
import org.slf4j.LoggerFactory;
|
|||
|
|
|
|||
|
|
import java.io.IOException;
|
|||
|
|
import java.io.InputStream;
|
|||
|
|
import java.util.function.Function;
|
|||
|
|
import org.springframework.stereotype.Component;
|
|||
|
|
/**
|
|||
|
|
* MyBatis 工具类
|
|||
|
|
*/
|
|||
|
|
|
|||
|
|
|
|||
|
|
@Component
|
|||
|
|
public class MyBatisUtil {
|
|||
|
|
private static final Logger logger = LoggerFactory.getLogger(MyBatisUtil.class);
|
|||
|
|
private static SqlSessionFactory sqlSessionFactory;
|
|||
|
|
@Autowired
|
|||
|
|
private SqlSessionFactory autoWiredSqlSessionFactory;
|
|||
|
|
static {
|
|||
|
|
init();
|
|||
|
|
}
|
|||
|
|
private static void init() {
|
|||
|
|
try {
|
|||
|
|
String resource = "mybatis-config.xml";
|
|||
|
|
InputStream inputStream = Resources.getResourceAsStream(resource);
|
|||
|
|
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
|
|||
|
|
logger.info("MyBatis 初始化成功");
|
|||
|
|
} catch (IOException e) {
|
|||
|
|
logger.error("初始化MyBatis失败", e);
|
|||
|
|
throw new RuntimeException("初始化MyBatis失败", e);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
public static SqlSession getSqlSession() {
|
|||
|
|
return sqlSessionFactory.openSession();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public static SqlSessionFactory getSqlSessionFactory() {
|
|||
|
|
return sqlSessionFactory;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取 SqlSession(自动提交事务)
|
|||
|
|
*/
|
|||
|
|
public static SqlSession getSqlSessionAutoCommit() {
|
|||
|
|
return sqlSessionFactory.openSession(true);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 执行查询操作(自动管理资源)
|
|||
|
|
*/
|
|||
|
|
public static <T> T executeQuery(Function<SqlSession, T> function) {
|
|||
|
|
SqlSession sqlSession = getSqlSession();
|
|||
|
|
try {
|
|||
|
|
return function.apply(sqlSession);
|
|||
|
|
} finally {
|
|||
|
|
sqlSession.close();
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 执行更新操作(自动提交事务和管理资源)
|
|||
|
|
*/
|
|||
|
|
public static <T> T executeUpdate(Function<SqlSession, T> function) {
|
|||
|
|
SqlSession sqlSession = getSqlSession();
|
|||
|
|
try {
|
|||
|
|
T result = function.apply(sqlSession);
|
|||
|
|
sqlSession.commit();
|
|||
|
|
return result;
|
|||
|
|
} catch (Exception e) {
|
|||
|
|
sqlSession.rollback();
|
|||
|
|
throw new RuntimeException("数据库操作失败", e);
|
|||
|
|
} finally {
|
|||
|
|
sqlSession.close();
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
/**
|
|||
|
|
* 重新初始化(用于配置热更新)
|
|||
|
|
*/
|
|||
|
|
public static void reload() {
|
|||
|
|
init();
|
|||
|
|
}
|
|||
|
|
}
|