通过继承BaseMapper,然后使用其api完成数据库的CRUD。
BaseMapper会将字段名中的大写字母转为小写字母并在其前面补上"_",如"userName"=>"user_name"
表名一定要全小写
实体类注解
@TableName("t_user") 写于类之上,表示改类对应于数据库中的表"t_user"
@TableId(value="id",type = IdType.ASSIGN_ID) 写于字段之上,表示该属性为主键,对应于数据库表中的属性"id"
User:
package com.example.application.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
@Data
@TableName("t_user")
public class User {
@TableId(type = IdType.ASSIGN_ID)
String account; //账号(非空,非空格前后缀,首字母必须为大写,账号长度为8-16)
String password; //密码(非空,非空格前后缀,首字母必须为大写,账号长度为8-16)
String username; //用户名(长度为2-12)-
int Status = 0; //身份 1表示管理员,0表示普通用户(默认为普通用户)
String telephone; //手机号码
String email; //邮箱
public User() {
}
public User(String account, String password) {
this.account = account;
this.password = password;
}
}
Mapper:
package com.example.application.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.application.domain.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
QueryWrapper:
wrapper.like("col","%val%"); //where col like '%val%'
wrapper.eq("deleted", false); // where deleted = false
wrapper.gt("remain", 0); //where remain >0
wrapper.ge("remain", 0); //where remain >=0
wrapper.lt("remain", 10); //where remain < 10
wrapper.le("remain", 10); //where remain <= 10
BaseMapper:
selectOne(wrapper); //返回符合条件的第一个对象或null
selectById("id"); //根据主键返回单一对象
selectList(wrapper); //返回List<T>
updateById(t); //根据t的主键匹配对应元组,将t的其他属性注入该元组
insert(t); //将t作为元组插入表,主键重复则报错
delete(wrapper); //批量删除
deleteById(t) //根据t的主键匹配删除