1.场景
查询测试环境数据库与生产环境数据库时,sql中的schema一致
1.1@TableName
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "role",schema = "test", autoResultMap = true)
public class SysRole {
@TableId(type = IdType.ASSIGN_ID)
private String roleId;
private String deptId;
private String roleName;
private String parentId;
private String createTime;
private String createUserId;
private String updateTime;
private String updateUserId;
private String roleDesc;
private String status;
}
@TableName注解详情:注解用来将指定的数据库表和 JavaBean 进行映射。
该注解属性如下:
属性名称 | 属性含义 | 备注 |
value | 字符串类型,不是必填,用来指定数据表名称 | 上面实例中,将 role数据表和 SysUserBean 实体进行映射。 |
shcema | 属性用来指定模式名称。如果你使用的是 mysql 数据库,则指定数据库名称。如果你使用的是 oracle,则为 schema | 上面实例中,schema="test",其中:test就是 oracle 中的 schema。例如: |
keepGlobalPrefix | 是否保持使用全局的 tablePrefix 的值,如果设置了全局 tablePrefix 且自行设置了 value 的值。 | |
resultMap | 对应 Mapper XML 文件中 <resultMap> 标签的 id 属性的值。用法见 “autoResultMap” 属性 | |
autoResultMap | 控制是否自动构建 resultMap 并使用它 |
2.解决方案:
上述方案适合测试与生产环境一致时,如果不一致则需要上线前进行修改
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory zocrmSqlSessionFactory(@Qualifier("dataSource") DataSource dataSource)
throws Exception {
GlobalConfig config = new GlobalConfig();
//多数据源,自增主键生成配置要单独配
config.setDbConfig(new GlobalConfig.DbConfig().setKeyGenerators(Collections.singletonList(new OracleKeyGenerator())));
//多数据源分页拦截器也要单独配置
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.ORACLE));
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setJdbcTypeForNull(JdbcType.NULL);
//配置动态schema
DynamicTableNameInnerInterceptor innerInterceptor = new DynamicTableNameInnerInterceptor();
innerInterceptor.setTableNameHandler((sql, tableName) -> schema + "." + tableName);
interceptor.addInnerInterceptor(innerInterceptor);
bean.setConfiguration(configuration);
bean.setGlobalConfig(config);
bean.setPlugins(interceptor);
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/**/*.xml"));
return bean.getObject();
}
注:Mapping.selectPage(page, queryWrapper)时不生效