MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提
高效率而生。
org.projectlombok
lombok
true
com.baomidou
mybatis-plus-boot-starter
3.0.5
mysql
mysql-connector-java
5.1.47
在MybatisPlus中,BaseMapper中定义了一些常用的CRUD方法,当我们自定义的Mapper接口继承BaseMapper
后即可拥有了这些方法
package cn.test.mybatisplus.mapper;
import cn.test.mybatisplus.pojo.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface UserMapper extends BaseMapper {
}
在启动类上添加注解
@MapperScan("cn.test.mybatisplus.mapper") //设置mapper接口的扫描包
引入spring boot测试依赖:
org.springframework.boot
spring-boot-starter-test
test
测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List userList = userMapper.selectList(null);
for (User user : userList) {
System.out.println(user);
}
}
}
文档链接 https://mp.baomidou.com/guide/wrapper.html#abstractwrapper
4
虽然在MybatisPlus中可以实现零配置,但是有些时候需要我们自定义一些配置,就需要使用Mybatis原生的一些配
置文件方式了
# 指定全局配置文件
mybatis-plus.config-location = classpath:mybatis-config.xml
# 指定mapper.xml文件
mybatis-plus.mapper-locations = classpath*:mybatis/*.xml
更多配置:https://mp.baomidou.com/guide/config.html#%E5%9F%BA%E6%9C%AC%E9%85%8D%E7%BD%AE
lombok 提供了简单的注解的形式来帮助我们简化消除一些必须有但显得很臃肿的 java 代码,尤其是针对pojo,在
MybatisPlus中使用lombok
官网:https://projectlombok.org/
引入依赖:
org.projectlombok
lombok
true
1.18.4
如果不安装插件,程序可以正常执行,但是看不到生成的一些代码,如:get、set方法
常用注解:
@Data:注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、
hashCode、toString 方法
@Setter:注解在属性上;为属性提供 setting 方法
@Getter:注解在属性上;为属性提供 getting 方法
@Slf4j:注解在类上;为类提供一个 属性名为log 的 slf4j日志对象
@NoArgsConstructor:注解在类上;为类提供一个无参的构造方法
@AllArgsConstructor:注解在类上;为类提供一个全参的构造方法
@Builder:使用Builder模式构建对象
使用了@Bulider和@Data注解后,就可以使用链式风格优雅地创建对象 列如:
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class People {
private String name;
private String sex;
private int age;
}
public class TestLombok {
@Test
public void testBuilderAnnotation(){
People luoTianyan = People.builder()
.sex("female")
.age(23)
.name("LuoTianyan")
.build();
System.out.println(luoTianyan.toString());
//People(name=LuoTianyan, sex=female, age=23)
People people = new People("LuoTianyan","female",23);
System.out.println(luoTianyan.equals(people));
//true
}
}
待续。。。。4