添加依赖:
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
springboot配置文件
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis-plus.mapper-locations=classpath*:mapper/**/*.xml
mybatis-plus.type-aliases-package=com.wuf.swagger.pojo
参考官方文档的配置
业务代码:
创建实体
@TableName("user")
@ApiModel(value = "用户",description = "用户信息")
public class User extends Model<User> {
@ApiModelProperty(value = "主键")
@TableId(type= IdType.AUTO)
private Integer id;
@ApiModelProperty(value = "用户名")
private String username;
@ApiModelProperty(value = "用户密码")
private String password;
@ApiModelProperty(value = "年龄")
private Integer age;
@ApiModelProperty(value = "用户邮箱")
private String email;
@ApiModelProperty(value = "用户联系方式")
private String phone;
@ApiModelProperty(value = "找回密码问题")
private String question;
@ApiModelProperty(value = "找回密码问题答案")
private String answer;
@ApiModelProperty(value = "用户身份")
private Integer role;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
public User() {
super();
}
public User(Integer id, String username, String password,Integer age, String email, String phone, String question, String answer, Integer role, Date createTime, Date updateTime) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
this.email = email;
this.phone = phone;
this.question = question;
this.answer = answer;
this.role = role;
this.createTime = createTime;
this.updateTime = updateTime;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question == null ? null : question.trim();
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer == null ? null : answer.trim();
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
", question='" + question + '\'' +
", answer='" + answer + '\'' +
", role=" + role +
", createTime=" + createTime +
", updateTime=" + updateTime +
'}';
}
}
其中:
注解 | 作用 |
---|---|
@TableName | 实体类的类名和数据库表名不一致 |
@TableId | 实体类的主键名称和表中主键名称不一致 |
@TableField | 实体类中的成员名称和表中字段名称不一致 |
@TableId(type= IdType.AUTO)主键采用自增长形式
@TableField(fill = FieldFill.INSERT)创建时间和修改时间采用系统直接获取操作时的时间,此外还需配置填充器,由于我用的是springboot,我直接用@Component载入。
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", new Date(),metaObject);
this.setFieldValByName("updateTime", new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", new Date(),metaObject);
}
}
排除实体类中非表字段
- 使用transient关键字修饰非表字段
- 使用static关键字
- 使用@TableField(exist = false)注解
实体类创建完成后在dao包中创建mapper接口继承BaseMapper
public interface UserMapper extends BaseMapper<User> {
}
Basemapper类代码如下
/**
* Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
* <p>这个 Mapper 支持 id 泛型</p>
*
* @author hubin
* @since 2016-01-23
*/
public interface BaseMapper<T> extends Mapper<T> {
/**
* 插入一条记录
*
* @param entity 实体对象
*/
int insert(T entity);
/**
* 根据 ID 删除
*
* @param id 主键ID
*/
int deleteById(Serializable id);
/**
* 根据 columnMap 条件,删除记录
*
* @param columnMap 表字段 map 对象
*/
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根据 entity 条件,删除记录
*
* @param wrapper 实体对象封装操作类(可以为 null)
*/
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
/**
* 删除(根据ID 批量删除)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 根据 ID 修改
*
* @param entity 实体对象
*/
int updateById(@Param(Constants.ENTITY) T entity);
/**
* 根据 whereEntity 条件,更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
/**
* 根据 ID 查询
*
* @param id 主键ID
*/
T selectById(Serializable id);
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 查询(根据 columnMap 条件)
*
* @param columnMap 表字段 map 对象
*/
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根据 entity 条件,查询一条记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询总记录数
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
在springboot启动类添加@MapperScan扫描dao层接口
@MapperScan("com.wuf.swagger.dao")
之后就可以正常使用
测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisPlusTests {
@Autowired
private UserMapper userMapper;
@Test
public void insert(){
User user = new User();
user.setUsername(IDUtil.genImageName());
user.setPassword("123456");
user.setEmail("cc@163.com");
user.setPhone("12345678910");
user.setQuestion("1");
user.setAnswer("2");
user.setRole(1);
int insert = userMapper.insert(user);
assert insert == 1;
}
@Test
public void selectByWrapperAllEq(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
Map<String, Object> map = new HashMap<>();
map.put("username","admin");
map.put("role",1);
queryWrapper.allEq(true,map,false);
List<User> userList = userMapper.selectList(queryWrapper);
for(User u:userList){
System.out.println(u);
}
}
@Test
public void selectByWrapperEq(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("role",1).ne("username","lisi").in("question","1","问题").eq("answer",2);
List<User> userList = userMapper.selectList(queryWrapper);
for(User u:userList){
System.out.println(u.getUsername());
}
}
@Test
public void selectByWrapperApply(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.apply("username={0}","admin");
List<User> userList = userMapper.selectList(queryWrapper);
for(User u:userList){
System.out.println(u.getUsername());
}
}
@Test
public void selectByWrapperUser(){
User user = new User();
user.setUsername("zhangsan");
user.setRole(2);
QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
List<User> userList = userMapper.selectList(queryWrapper);
for(User u:userList){
System.out.println(u.getUsername());
}
}
}
条件构造器
条件构造器官网
QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
今天看的时候想到java和数据库的命名不一致,那要怎么映射,上网找了下找到一个
mybatisplus的驼峰命名配置是在MP全局配置中完成的
<!-- MP 全局配置 -->
<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
<!-- 全局的主键策略 -->
<property name="idType" value="0"/>
<!--映射数据库下划线字段名到数据库实体类的驼峰命名的映射-->
<property name="dbColumnUnderline" value="true"/>
</bean>
关闭驼峰映射(未验证)
在application.properties添加一行配置,关闭驼峰到下划线的映射即可
mybatis-plus.configuration.map-underscore-to-camel-case=false