Spring和MYbatis整合数据库下划线转驼峰
时间: 2024-01-23 19:04:27 浏览: 189
spring和mybatis整合
在Spring和MyBatis整合的情况下,可以通过在MyBatis的配置文件中配置一个插件来实现下划线转驼峰。
具体操作如下:
1. 在MyBatis的配置文件中添加以下插件配置:
```
<plugins>
<plugin interceptor="org.apache.ibatis.plugin.Interceptor">
<property name="properties">
<property name="helperDialect" value="mysql"/>
<property name="offsetAsPageNum" value="true"/>
<property name="rowBoundsWithCount" value="true"/>
<property name="reasonable" value="true"/>
</property>
<property name="typeAliases">
<typeAlias type="com.example.domain.User" alias="User"/>
</property>
<property name="mapperLocations" value="classpath:com/example/mapper/*.xml"/>
</plugin>
</plugins>
```
2. 在Spring的配置文件中配置一个Bean,将上一步中配置的插件添加到SqlSessionFactory中:
```
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:com/example/mapper/*.xml"/>
<property name="plugins">
<array>
<bean class="com.example.plugin.CamelCaseInterceptor"/>
</array>
</property>
</bean>
```
3. 编写一个插件类,实现下划线转驼峰的逻辑:
```
public class CamelCaseInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
BoundSql boundSql = ms.getBoundSql(parameter);
String sql = boundSql.getSql();
// 下划线转驼峰
sql = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, sql);
BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(), boundSql.getParameterObject());
MappedStatement newMs = copyFromMappedStatement(ms, new BoundSqlSqlSource(newBoundSql));
args[0] = newMs;
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// do nothing
}
private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
builder.keyProperty(StringUtils.join(ms.getKeyProperties(), ","));
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
builder.resultMaps(ms.getResultMaps());
builder.cache(ms.getCache());
builder.useCache(ms.isUseCache());
return builder.build();
}
}
```
通过以上步骤,即可实现在Spring和MyBatis整合的情况下将数据库中下划线命名的字段转换为驼峰命名的字段。
阅读全文