1、相关配置
1.1 maven依赖
1 | <!--引入通用mapper--> |
1.2 application.properties配置
1 | MYSQL = |
1.3 spring启动配置scan
1 |
使用import tk.mybatis.spring.annotation.MapperScan;
来扫描
2、使用通用mapper
2.1 创建顶层的BaseDao
1 | public interface BaseDao<T> extends Mapper, MySqlMapper<T> { |
主要是起到一个模板的作用
2.2 创建自己的DAO层
实现BaseDao
1 |
|
其中的User是实体对象
1 |
|
@Table中映射到数据库中对应的数据表
@Id@GeneratedValue是用来确定相关的主键的标识的
@Column是和数据表中相关的字段相对应。
2.3 使用UserDao
在service层引入
1 |
|
简单的增删该查的函数
- 新增用户 insert(Object)
1
2
3
4public int insert(User user) {
// 添加用户
return userDao.insert(user);
} - 删除用户 deleteByPrimaryKey(Integer id)
1
2
3
4
5public int deleteUser(Integer id) {
// 使用id删除用户
int row = userDao.deleteByPrimaryKey(id);
return row;
} - 修改(更新)用户 updateByPrimaryKey(EntityObject)
1
2
3public int updateByPrimaryKey(User user) {
return userDao.updateByPrimaryKey(user);
} - 根据id查询用户selectByPrimaryKey(Integer id)
1
2
3public User queryById(Integer id) {
return (User)userDao.selectByPrimaryKey(id);
} - 查询所有的用户 selectAll()
1
2
3
4public List<User> queryUserList() {
// 返回所有的用户
return userDao.selectAll();
}2.4 其它常用函数
2.4.1 查询类
List<T> select(T entity)
说明:根据传进来的实体记录找出符合条件的数据列表,使用的and查询。满足传入的属性T selectOne(T entity)
说明: 根据传进来的实体,从数据库中查找出一条记录。如果找到多个值会抛出异常。使用and查询List<T> selectAll()
等价于select(null)
int selectCount(T entity)
根据实体属性返回查询到的数据个数2.4.2 新增类
int insert(T entity)
说明:向数据库中插入一条数据,entity中null值会保存。不会使用数据库的默认值int insertSelective(T entity)
说明:向数据库中插入一条数据,entity中的null值会使用数据库中的默认值进行填充2.4.3 删除类
int deleteByPrimaryKey(Object key)
说明: 根据主键进行删除数据int delete(T entity)
说明: 根据传进来的实体的属性删除满足的字段2.4.4 更新类
int updateByPrimaryKey(T entity)
说明: 根据传进来的实体id更新数据库相应的数据,null值会被更新int updateByPrimaryKeySelective(T entity)
说明: 根据传进来的实体更新属性不为空的值2.5 使用Example
examples能够更加灵活的用来进行查询2.5.1 获得某个实体类的样本example
Example example = new Example(User.class);
2.5.2 获得这个样本的criteria
Example.Criteria criteria = example.createCriteria();
2.5.3 使用这个criteria来设定相应的条件
可以调用相应的函数来构建相应的条件。这就是将本来是要写sql语句的部分封装成函数。只要传入相应的属性和调用相应的方法便可以完成某些条件的查询。1
2criteria.andEqualTo("account","long1532");
criteria.andNotEqualTo("nickname","long153222");2.5.4 使用example来增删改查相应的数据
List<User> userList = userDao.selectByExample(example);
3、整合pageHelper实现模糊查询和分页
3.1 分页的和查询可以一起共用一个接口
查询和分页可以共用一个接口,因为查询出来的数据可能有很多条数据。这时候有分页的请求。初始加载的时候将查询条件置空便可以获得所有的数据,然后经过的分页插件便可以进行业务上的分页了。3.2 引入分页插件
1
2
3
4
5
6<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pagehelper.starter.version}</version>
</dependency>3.3 通用mapper的模糊查询
criteria
对象函数andLike()实现模糊查询andLike(String property, String value)
接收两个参数
1、property是对应实体的属性。
2、value 是模糊查询传进来的值
对于时间对象的模糊查询可以使用andLessThanOrEqualTo
andGreaterThanOrEqualTo
3.4 使用PageHelper完成分页
核心是PageHelper.startPage(pageNum,pageSize)
1 | PageInfo<xxxEntity> pageInfo = PageHelper.startPage(pageNum, pageSize) |
其中的example是设置了模糊查询的查询exmaple
获得分页的数据
1 | list = pageInfo.getList(); |