下面就来详细讲解“mybatis逆向工程与分页在springboot中的应用及遇到坑”的完整攻略:
Mybatis逆向工程
Mybatis逆向工程可以快速生成Mybatis的mapper.xml、mapper.java和pojo,提升开发效率。下面是使用Mybatis逆向工程的步骤:
- 首先在pom.xml中添加Mybatis Generator的依赖:
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
- 在resources目录下创建generatorConfig.xml文件,并在其中配置数据库连接信息、生成规则等。以下是一个简单的示例:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 配置数据库连接 -->
<context id="mybatis-generator" targetRuntime="MyBatis3">
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test"
userId="root"
password="root">
</jdbcConnection>
<!-- 配置要生成的pojo、mapper、mapper.xml的包路径 -->
<javaModelGenerator targetPackage="com.example.model"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<sqlMapGenerator targetPackage="mapper"
targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.example.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 配置要生成的表名,%为通配符,表示所有表。可以在该标签内添加多个table子标签,配置多个表名 -->
<table schema="test" tableName="%">
<!-- 配置生成的Mapper的名称,%为通配符,表示表名 -->
<generatedKey column="id" sqlStatement="Mysql"/>
</table>
</context>
</generatorConfiguration>
- 然后在maven项目中运行Mybatis Generator插件,生成对应的文件。
在IDEA中,可以在Maven Projects面板中找到你的项目,展开Plugins,找到mybatis-generator,双击mybatis-generator:generate执行即可。
Mybatis分页
Mybatis官方并没有提供原生分页支持,但可以通过拦截器来实现。下面是一个简单的分页拦截器示例:
@Intercepts({
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
public class PageInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
BoundSql boundSql = statementHandler.getBoundSql();
Object parameterObject = boundSql.getParameterObject();
if (parameterObject instanceof Pager) {
Connection connection = (Connection) invocation.getArgs()[0];
Pager pager = (Pager) parameterObject;
String sql = boundSql.getSql();
String countSql = "select count(*) from (" + sql + ") as countSql";
PreparedStatement countStatement = connection.prepareStatement(countSql);
BoundSql countBoundSql = new BoundSql(statementHandler.getConfiguration(), countSql, boundSql.getParameterMappings(), parameterObject);
setParameters(countStatement, countBoundSql, parameterObject);
ResultSet rs = countStatement.executeQuery();
int totalCount = 0;
if (rs.next()) {
totalCount = rs.getInt(1);
}
rs.close();
countStatement.close();
pager.setTotalCount(totalCount);
String pageSql = getLimitString(sql, pager);
ReflectUtil.setFieldValue(boundSql, "sql", pageSql);
}
return invocation.proceed();
}
private void setParameters(PreparedStatement ps, BoundSql boundSql, Object parameterObject) throws SQLException {
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if (parameterMappings != null) {
Configuration configuration = boundSql.getConfiguration();
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(parameterObject);
for (int i = 0; i < parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
if (metaObject == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;
} else {
value = metaObject.getValue(propertyName);
}
TypeHandler typeHandler = parameterMapping.getTypeHandler();
if (typeHandler == null) {
throw new IllegalArgumentException("Parameter mapping " + parameterMapping.getProperty() +
" cannot be null, cause: " + boundSql.getSql());
} else {
typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
}
}
}
}
}
private String getLimitString(String sql, Pager pager) {
StringBuilder builder = new StringBuilder(sql);
builder.append(" limit ").append(pager.getStartIndex()).append(",").append(pager.getPageCount());
return builder.toString();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
上述代码中,我们新建了一个PageInterceptor类,并实现了Mybatis的Interceptor接口。在intercept方法中,我们先获取statementHandler和boundSql,再判断参数对象是否是Pager类型,如果是则执行分页操作。然后我们根据原始sql语句生成获取总数的sql语句,拼接成countSql,并执行。然后从查询结果中获取总行数,设置到Pager对象中。 最后根据pager中的参数生成新的分页sql,将分页sql设置到boundSql中。除此之外,我们还要在Mybatis的配置文件中注册我们的拦截器:
<plugins>
<plugin interceptor="com.example.interceptor.PageInterceptor"></plugin>
</plugins>
Mybatis逆向工程与分页在Spring Boot中的应用
在Spring Boot中使用Mybatis逆向工程生成Mapper等代码和使用Mybatis分页拦截器非常简单,只需要按照上述步骤生成代码和配置分页拦截器即可。下面为大家提供一个完整的Spring Boot工程示例:
- 首先,我们需要添加依赖,包括Spring Boot、Mybatis和MySQL Driver,可以在pom.xml中加入以下依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
</dependencies>
- 然后,我们需要在application.properties中添加数据库连接和Mybatis配置:
# 数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Mybatis配置
mybatis.type-aliases-package=com.example.model
mybatis.mapper-locations=classpath:mapper/*.xml
- 接下来,我们就可以生成Mybatis Mapper等代码,打开终端,进入项目所在目录,运行命令Mybatis Generator插件的generate方法:
mvn mybatis-generator:generate
-
之后,我们就可以按照上述内容实现Mybatis分页拦截器。PageInterceptor类可以放在任意目录下。
-
最后,我们需要为分页参数新建一个Pager类:
public class Pager {
private int pageNumber;
private int pageSize;
private int totalCount;
public int getPageNumber() {
return pageNumber;
}
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getStartIndex() {
return (pageNumber - 1) * pageSize;
}
public int getPageCount() {
return pageSize;
}
}
完整的示例代码可以参考以下链接:https://github.com/lsq1995/mybatis-springboot-pagination
注意,如果你使用的是Spring Boot 2.x版本,Mybatis Generator的xml配置文件需要使用标签替代<!DOCTYPE>,如下:
<link rel="stylesheet" type="text/css" href="http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
以上就是Mybatis逆向工程与分页在Spring Boot中的应用的完整攻略。希望对大家有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:mybatis逆向工程与分页在springboot中的应用及遇到坑 - Python技术站