用织梦做的网站怎么管理,gta 买房网站建设中,做抖音seo排名软件是否合法,商城网站建设教程一、定义
MyBatis是一款优秀的持久层框架#xff0c;它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO#xff08;Plain Old Java O…一、定义
MyBatis是一款优秀的持久层框架它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJOPlain Old Java Objects普通老式 Java 对象为数据库中的记录。
官网https://mybatis.org/mybatis-3/zh_CN/index.html
二、核心概念
1、SqlSessionFactoryBuilder
2、SqlSessionFactory
3、SqlSession
4、插件
1定义
MyBatis允许通过使用插件在映射语句执行过程中的某一点进行拦截。
默认情况下MyBatis允许使用插件来拦截的方法调用有
A、Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)执行器拦截器 允许拦截和自定义MyBatis执行器的行为。例如可以添加缓存、日志记录或审计功能到执行器中。这些拦截器可以在MyBatis执行的不同阶段扩展或修改其行为。您可以通过实现MyBatis提供的相应接口并在MyBatis配置文件中进行配置来实现这些拦截器 B、ParameterHandler (getParameterObject, setParameters)参数拦截器 允许在将参数设置到SQL语句之前修改或验证它们。例如可以对作为参数传递的敏感信息进行加密或解密。 C、ResultSetHandler (handleResultSets, handleOutputParameters)结果集拦截器 可以在将结果集返回给应用程序之前修改或分析它们。例如可以对结果集数据进行转换或执行额外的计算。 D、StatementHandler (prepare, parameterize, batch, update, query)语句拦截器 可以在SQL语句执行之前修改或增强它们。例如可以向WHERE子句添加额外的条件或记录执行的语句。分页等 2自定义插件
在MyBatis中只需实现 Interceptor 接口并指定想要拦截的方法签名即可对某个方法进行拦截。
A、Executor方法的拦截
示例代码对query执行过程的拦截
Intercepts({Signature(type Executor.class,methodquery,args{MappedStatement.class, Object.class,RowBounds.class, ResultHandler.class })})
public class QueryExecutorPlugin implements Interceptor {Overridepublic Object intercept(Invocation invocation) throws Throwable {// 执行query方法Object objinvocation.proceed();// 修改执行结果ListObject list JSONUtil.parseArray(obj);list.add(new Category().setName(测试插件1));return list;}Overridepublic Object plugin(Object target) {// 包装目标对象的包装为目标对象创建一个代理对象return Interceptor.super.plugin(target);}Overridepublic void setProperties(Properties properties) {// 将插件注册时的property属性设置进来Interceptor.super.setProperties(properties);}
}
B、StatementHandler方法的拦截
示例代码对sql语句的修改
Intercepts({Signature(type StatementHandler.class,method prepare,args {Connection.class,Integer.class})})
public class StatementPlugin implements Interceptor {Overridepublic Object intercept(Invocation invocation) throws Throwable {StatementHandler statementHandler PluginUtils.realTarget(invocation.getTarget());MetaObject metaObject SystemMetaObject.forObject(statementHandler);BoundSql boundSql (BoundSql) metaObject.getValue(delegate.boundSql);String originSqlboundSql.getSql();System.out.println(原始sqloriginSql);// 对原始sql进行改写metaObject.setValue(delegate.boundSql.sql,originSql.replace(?,8888888));return invocation.proceed();}
}
或者
Intercepts({Signature(type StatementHandler.class,method prepare,args {Connection.class,Integer.class})})
public class StatementPlugin implements Interceptor {Overridepublic Object intercept(Invocation invocation) throws Throwable {StatementHandler statementHandler (StatementHandler) invocation.getTarget();BoundSql boundSql statementHandler.getBoundSql();String originSqlboundSql.getSql();System.out.println(原始sqloriginSql);// 直接对原始sql进行改写ReflectUtil.setFieldValue(boundSql,sql,originSql.replace(?,9878948));return invocation.proceed();}
}
C、ParameterHandler方法的拦截
Intercepts({Signature(type ParameterHandler.class, method setParameters, args PreparedStatement.class)})
public class ParameterPlugin implements Interceptor {Overridepublic Object intercept(Invocation invocation) throws Throwable {// 修改参数值return null;}
}
D、ResultSetHandler方法的拦截
Intercepts({Signature(type ResultSetHandler.class, method handleResultSets, args Statement.class)})
public class ResultSetPlugin implements Interceptor {Overridepublic Object intercept(Invocation invocation) throws Throwable {// 修改结果集return null;}
}
E、测试
a、添加插件
public class MyBatisConfig {Beanpublic SqlSessionFactory sqlSessionFactory(){DriverManagerDataSource dataSourcenew DriverManagerDataSource();dataSource.setUrl(jdbc:mysql://xxx:xxx/xxx?characterEncodingutf-8useSSLfalse);dataSource.setUsername(xxx);dataSource.setPassword(xxx);dataSource.setDriverClassName(com.mysql.jdbc.Driver);TransactionFactory transactionFactory new JdbcTransactionFactory();Environment environment new Environment(development, transactionFactory, dataSource);org.apache.ibatis.session.Configuration confignew org.apache.ibatis.session.Configuration(environment);config.addMapper(CategoryMapper.class);// 添加插件config.addInterceptor(new QueryExecutorPlugin());config.addInterceptor(new ParameterPlugin());config.addInterceptor(new StatementPlugin());return new SqlSessionFactoryBuilder().build(config);}
}
b、测试代码
public class TestMyBatis {public static void main(String[] args) {AnnotationConfigApplicationContext contextnew AnnotationConfigApplicationContext(MyBatisConfig.class);SqlSessionFactory factory (SqlSessionFactory) context.getBean(sqlSessionFactory);try(SqlSession sqlSessionfactory.openSession()){CategoryMapper categoryMappersqlSession.getMapper(CategoryMapper.class);categoryMapper.insert(new Category().setName(222222));ListCategory listcategoryMapper.selectList();System.out.println(JSONUtil.toJsonPrettyStr(list));sqlSession.commit();// 默认mybatis是不会自动提交的需要手动自动提交修改才会生效}}
} 5、类型转换器TypeHandler
1常用的TypeHandler
2自定义TypeHandler
可以通过继承BaseTypeHandler来自定义TypeHandler
三、使用
1、Spring使用MyBatis
0数据库中已存在category表 1引入依赖
!-- mybatis依赖 --dependencygroupIdorg.mybatis/groupIdartifactIdmybatis/artifactIdversion3.5.16/version/dependency
2编写配置类MyBatisConfig
ComponentScan(basePackages org.example.mybatis)
Configuration
public class MyBatisConfig {Beanpublic SqlSessionFactory sqlSessionFactory(){DriverManagerDataSource dataSourcenew DriverManagerDataSource();dataSource.setUrl(jdbc:mysql://xxx:xxx/xxx?characterEncodingutf-8useSSLfalse);dataSource.setUsername(xxx);dataSource.setPassword(xxx);dataSource.setDriverClassName(com.mysql.jdbc.Driver);TransactionFactory transactionFactory new JdbcTransactionFactory();Environment environment new Environment(development, transactionFactory, dataSource);org.apache.ibatis.session.Configuration confignew org.apache.ibatis.session.Configuration(environment);config.addMapper(CategoryMapper.class);return new SqlSessionFactoryBuilder().build(config);}
}
3编写测试类
public class TestMyBatis {public static void main(String[] args) {AnnotationConfigApplicationContext contextnew AnnotationConfigApplicationContext(MyBatisConfig.class);SqlSessionFactory factory (SqlSessionFactory) context.getBean(sqlSessionFactory);try(SqlSession sqlSessionfactory.openSession()){CategoryMapper categoryMappersqlSession.getMapper(CategoryMapper.class);categoryMapper.insert(new Category().setName(222222));ListCategory listcategoryMapper.selectList();System.out.println(JSONUtil.toJsonPrettyStr(list));sqlSession.commit();// 默认mybatis是不会自动提交的需要手动自动提交修改才会生效}}
} 四、原理 五、关于MyBatisPlus
1、定义
MyBatis-Plus (opens new window)简称 MP是一个 MyBatis (opens new window)的增强工具在 MyBatis 的基础上只做增强不做改变为简化开发、提高效率而生。
2、特性
无侵入只做增强不做改变引入它不会对现有工程产生影响如丝般顺滑损耗小启动即会自动注入基本 CURD性能基本无损耗直接面向对象操作强大的 CRUD 操作内置通用 Mapper、通用 Service仅仅通过少量配置即可实现单表大部分 CRUD 操作更有强大的条件构造器满足各类使用需求支持 Lambda 形式调用通过 Lambda 表达式方便的编写各类查询条件无需再担心字段写错支持主键自动生成支持多达 4 种主键策略内含分布式唯一 ID 生成器 - Sequence可自由配置完美解决主键问题支持 ActiveRecord 模式支持 ActiveRecord 形式调用实体类只需继承 Model 类即可进行强大的 CRUD 操作支持自定义全局通用操作支持全局通用方法注入 Write once, use anywhere 内置代码生成器采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码支持模板引擎更有超多自定义配置等您来使用内置分页插件基于 MyBatis 物理分页开发者无需关心具体操作配置好插件之后写分页等同于普通 List 查询分页插件支持多种数据库支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库内置性能分析插件可输出 SQL 语句以及其执行时间建议开发测试时启用该功能能快速揪出慢查询内置全局拦截插件提供全表 delete 、 update 操作智能分析阻断也可自定义拦截规则预防误操作