Spring boot 集成 通用 Mapper
问:什么是通用Mapper?
答:通用Mapper就是为了解决单表增删改查,基于Mybatis的插件。开发人员不需要编写SQL,不需要在DAO中增加方法,只要写好实体类,就能支持相应的增删改查方法。
1.pom.xml 添加依赖
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>RELEASE</version>
</dependency>
2.添加配置(application.properties)
#通用mapper的所在接口名称 不只是包名
mapper.mappers=tk.mybatis.mapper.common.Mapper
#数据库
mapper.identity=MYSQL
3.Spring Boot 启动类添加扫描包:
一定要注意注解@MapperScan 引入的包,否则会报错
4.继承方法:dao 层 继承 Mapper<T> (T为实体类)
5. 实体类
@Table(name="role")
public class Role implements Serializable {
@Id
@GeneratedValue(generator = "JDBC")//返回自增长主键
private Integer id;
@Column(name = "rolename")
private String rolename;
private String limits;
private String descr;
注解说明:
- 表名默认使用类名,驼峰转下划线(只对大写字母进行处理),如
UserInfo
默认对应的表名为user_info
。- 表名可以使用
@Table(name = "tableName")
进行指定,对不符合第一条默认规则的可以通过这种方式指定表名.- 字段默认和
@Column
一样,都会作为表字段,表字段默认为Java对象的Field名字驼峰转下划线形式.- 可以使用
@Column(name = "fieldName")
指定不符合第3条规则的字段名- 使用
@Transient
注解可以忽略字段,添加该注解的字段不会作为表字段使用.- 建议一定是有一个
@Id
注解作为主键的字段,可以有多个@Id
注解的字段作为联合主键.- 如果是MySQL的自增字段,加上
@GeneratedValue(generator = "JDBC")
即可,还可返回自增长的主键。
5.Mapper 包含的通用方法
Select
方法:List<T> select(T record);
说明:根据实体中的属性值进行查询,查询条件使用等号方法:
T selectByPrimaryKey(Object key);
说明:根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号方法:
List<T> selectAll();
说明:查询全部结果,select(null)方法能达到同样的效果方法:
T selectOne(T record);
说明:根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,查询条件使用等号方法:
int selectCount(T record);
说明:根据实体中的属性查询总数,查询条件使用等号Insert
方法:int insert(T record);
说明:保存一个实体,null的属性也会保存,不会使用数据库默认值方法:
int insertSelective(T record);
说明:保存一个实体,null的属性不会保存,会使用数据库默认值Update
方法:int updateByPrimaryKey(T record);
说明:根据主键更新实体全部字段,null值会被更新方法:
int updateByPrimaryKeySelective(T record);
说明:根据主键更新属性不为null的值Delete
方法:int delete(T record);
说明:根据实体属性作为条件进行删除,查询条件使用等号方法:
int deleteByPrimaryKey(Object key);
说明:根据主键字段进行删除,方法参数必须包含完整的主键属性Example方法
方法:List<T> selectByExample(Object example);
说明:根据Example条件进行查询
重点:这个查询支持通过Example
类指定查询列,通过selectProperties
方法指定查询列方法:
int selectCountByExample(Object example);
说明:根据Example条件进行查询总数方法:
int updateByExample(@Param("record") T record, @Param("example") Object example);
说明:根据Example条件更新实体record
包含的全部属性,null值会被更新方法:
int updateByExampleSelective(@Param("record") T record, @Param("example") Object example);
说明:根据Example条件更新实体record
包含的不是null的属性值方法:
int deleteByExample(Object example);
说明:根据Example条件删除数据