Mybatis Plus
现在公司用的内部的mybatisGenerate生成工具,可以生成单表的CRUD的xml,domian,dto,cond(查询条件),但是存在一个问题,就是修改表字段的,那xml需要重新生成并替换,如果sql xml中有自定义的sql那容易被覆盖或遗漏,所有学习了下mybatis Plus
- 依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-boot-starter</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.3</version>
</dependency>
- application.properties
server.port=8080
#mysql
spring.datasource.url=jdbc:mysql://localhost:3306/wssll?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=rootroot
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatis-plus
mybatis-plus.mapper-locations=classpath:mybatis/mapper/*Dao.xml #在该xml中只写自定义的sql,如果没有特殊sql这行可以注了
mybatis-plus.type-aliases-package=io.ssss.wsssall.dal.dao
- Config配置(注解)
@Configuration
public class MybatisConfig {
@Bean
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(1000);
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
// 配置数据源
@Bean(name="dataSource")
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource(){
return new DruidDataSource();
}
// 配置事物管理器
@Bean(name="transactionManager")
public DataSourceTransactionManager transactionManager(){
return new DataSourceTransactionManager(dataSource());
}
}
- 启动类MapperScan
@SpringBootApplication
@MapperScan("io.mssnk.wsssall.dal.dao") //具体到dao的包
public class We1Application {
public static void main(String[] args) {
SpringApplication.run(We1Application.class, args);
}
}
- dao 接口
@Repository
public interface CartDao extends BaseMapper<Cart> {//BaseMapper是插件提供的一个通用接口,有很多方法
Integer getMax();//这个是我自定义的一个方法,BaseMapper中没有的
}
``
7. Service调用并测试
@Override
public Cart getById(Long id){
return cartDao.selectById(id); //这个是BaseMapper通用方法,id可以是Long,也可以是Integer
}
@Override
public List<Cart> findAll(Cart cart) {
EntityWrapper<Cart> tWrapper = new EntityWrapper<>() ;//
//条件查询1,直接entity
tWrapper.setEntity(cart);//可以接受一个domian对象作为查询条件
//条件查询2,指定属性
//tWrapper.eq("count",1).eq("status",0);//也可以自定义查询属性
return cartDao.selectList(tWrapper);//这也是BaseMapper的通用方法,
}
@Override
public Integer getMax() {
return cartDao.getMax();//这是我自定义的方法,需要在*Dao.xml中写具体sql实现
}
**是不是很方便,如果没有复杂sql,直接用mybatis plus就可以省去xml的配置,免得各种报错,而且数据库表字段修改了,不再修改xml中的数据了!
另外,**
**另外plus支持的条件查询,不仅有eq,还有gt,lt,这是很多自动生成sql插件不具备的**