Mybatis工具类

前提:已经配置好mybatis的环境。(核心配置文件、mapper映射、实体类、数据库、mapper接口)

工具类:

java 复制代码
public class MybatisUtil {

    private static SqlSessionFactory sqlSessionFactory = null;
    private static String xmlPath = "";//mybatis核心配置文件

    private MybatisUtil(){}

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream(xmlPath);
            sqlSessionFactory  = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static SqlSession openSession(){
        return  sqlSessionFactory.openSession();
    }//手动提交事务,默认。

    public static SqlSession openSession(Boolean flag){
        return  sqlSessionFactory.openSession(flag);
    }//自动提交事务

    public static void closeSqlSession(SqlSession sqlSession){
        if (sqlSession!=null){
            sqlSession.close();
        }
    }//自动提交事务,true时为自动开启事务

    public static void dateRoolBack(SqlSession sqlSession){
        if (sqlSession!=null){
            sqlSession.rollback();
        }
    }

       public static void dateCommit(SqlSession sqlSession){
        if (sqlSession!=null){
            sqlSession.commit();
        }
    }
}

使用:

java 复制代码
 SqlSession sqlSession= MybatisUtil.openSession();
Mapper接口  mapper接口对象 =  sqlSession.getMapper(Mapper接口.class);
······
相关推荐
Nturmoils3 小时前
订单列表慢查询,先看 WHERE、ORDER BY 和 LIMIT
数据库
渣波7 小时前
拒绝 SQL 焦虑!手把手带你用 NestJS + Prisma + DTO 写出“防弹”级后端代码
javascript·数据库·后端
倔强的石头_1 天前
KingbaseES 新版MySQL 兼容版体验:旧版迁移 + 功能实测
数据库
倔强的石头_4 天前
《Kingbase护城河》——数据库存储空间全景探测与精细化瘦身实战
数据库
冬奇Lab5 天前
每日一个开源项目(第134篇):Zvec - 阿里开源的嵌入式向量数据库,向量搜索界的 SQLite
数据库·人工智能·llm
ClouGence5 天前
Oracle CDC 架构优化:从主库直连到 DataGuard 备库同步
数据库·后端·oracle
无响应de神5 天前
三、用户与权限管理
数据库·mysql
麦聪聊数据6 天前
数据服务化时代:企业数据能力输出的核心路径
数据库
shushangyun_6 天前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化