MyBatis-Plus配置
官方配置文档
- 这只是很少一部分的配置,其他配置类似参考官方文档进行配置
基本配置
configLocation (自定义的mybatis配置)
- MyBatis 配置文件位置,如果您有单独的 MyBatis 配置,请将其路径配置到 configLocation
- Spring Boot项目
- Spring MVC
mapperLocation (自定义mapper)
- MyBatis Mapper 所对应的 XML 文件位置,如果您在 Mapper 中有自定义方法(XML 中有自定义实现),需要进行该配置,告诉 Mapper 所对应的 XML 文件位置
一般用来写一些比较复杂的sql语句
- Spring boot
- mapper接口
public User findById(Long id);
- mapper.xml
<select id="findById" resultType="com.ssc.mp.pojo.User">
select * from tb_user where id = #{id}
</select>
- 测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestUserMapper {
@Autowired
private UserMapper userMapper;
@Test
public void testFindById(){
User user = this.userMapper.findById(1L);
System.out.println(user);
}
}
- Spring MVC
typeAliasesPackage (别名)
- MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在 Mapper 对应的 XML 文件中可以直接使用类名,而不用使用全限定的类名(即 XML 中调用的时候不用包含包名)
- spring boot
# 扫描实体类包,并起一个别名
mybatis-plus.type-aliases-package= com.ssc.mp.pojo
- mapper.xml 中resultType可以直接使用User别名
<select id="findById" resultType="User">
select * from tb_user where id = #{id}
</select>
进阶配置
- 本部分(Configuration)的配置大都为 MyBatis 原生支持的配置,这意味着您可以通过 MyBatis XML 配置文件的形式进行配置。
mapUnderscoreToCamelCase (驼峰命名)
- 是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN(下划线命名) 到经典 Java 属性名 aColumn(驼峰命名) 的类似映射。
注意
此属性在 MyBatis 中原默认值为 false,在 MyBatis-Plus 中,此属性也将用于生成最终的 SQL 的 select body
如果您的数据库命名符合规则无需使用 @TableField 注解指定数据库字段名
# 禁用自动驼峰
# 该参数不能和 mybatis-plus.config-location 同时存在
mybatis-plus.configuration.map-underscore-to-camel-case = false
cacheEnabled (二级缓存)
- 开启Mybatis二级缓存,默认为 true。
# 禁用缓存 默认开启
mybatis-plus.configuration.cache-enabled=false
DB策略配置
idType(主键类型)
- 全局默认主键类型
- spring boot
# 全局的id生成策略
mybatis-plus.global-config.db-config.id-type=auto
- spring mvc (
applicationContext.xml
)
<!--这里使用MP提供的sqlSessionFactory,完成了Spring与MP的整合-->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="globalConfig">
<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
<property name="dbConfig">
<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
<property name="idType" value="AUTO"/>
</bean>
</property>
</bean>
</property>
</bean>
tablePrefix(表名前缀)
- 可以取消实体类上的@TableName注解
- spring boot
# 全局表名前缀
mybatis-plus.global-config.db-config.table-prefix=tb_
- spring mvc
<!--这里使用MP提供的sqlSessionFactory,完成了Spring与MP的整合-->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="globalConfig">
<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
<property name="dbConfig">
<bean class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
<property name="tablePrefix" value="tb_"/>
</bean>
</property>
</bean>
</property>
</bean>