一、什么是example类
mybatis-generator会为每个字段产生如上的Criterion,如果表的字段比较多,产生的Example类会十分庞大。理论上通过example类可以构造你想到的任何筛选条件。在mybatis-generator中加以配置,配置数据表的生成操作就可以自动生成example了。
下面是mybatis自动生成example的使用。
二、mapper接口中的方法解析
public interface AdminuserMapper {
int countByExample(AdminuserExample example);
int deleteByExample(AdminuserExample example);
int deleteByPrimaryKey(Integer uid);
int insert(Adminuser record);
int insertSelective(Adminuser record);
List<Adminuser> selectByExample(AdminuserExample example);
Adminuser selectByPrimaryKey(Integer uid);
int updateByExampleSelective(@Param("record") Adminuser record, @Param("example") AdminuserExample example);
int updateByExample(@Param("record") Adminuser record, @Param("example") AdminuserExample example);
int updateByPrimaryKeySelective(Adminuser record);
int updateByPrimaryKey(Adminuser record);
}
三、example实例解析
public class UserExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
protected abstract static class GeneratedCriteria
{.....}
public static class Criterion {.....}
四、example使用前的准备
比如我的 example 是根据 user 表生成的,UserMapper属于 dao 层,UserMapper.xml 是对应的映射文件
UserMapper接口:
long countByExample(CompetingStoreExample example);
List<CompetingStore> selectByExample(CompetingStoreExample example);
在我们的测试类里:
UserExample example = new UserExample();
UserExample.Criteria criteria = example.createCriteria();
五、查询用户数量
long count = UserMapper.countByExample(example);
类似于:select count(*) from user
六、where条件查询或多条件查询
example.setOrderByClause("age asc");
example.setDistinct(false);
if(!StringUtils.isNotBlank(user.getName())){
Criteria.andNameEqualTo(user.getName());
}
if(!StringUtils.isNotBlank(user.getSex())){
Criteria.andSexEqualTo(user.getSex());
}
List<User> userList = userMapper.selectByExample(example);
类似于:select * from user where name={#user.name} and sex={#user.sex} order by age asc;
UserExample.Criteria criteria1 = example.createCriteria();
UserExample.Criteria criteria2 = example.createCriteria();
if(!StringUtils.isNotBlank(user.getName())){
Criteria1.andNameEqualTo(user.getName());
}
if(!StringUtils.isNotBlank(user.getSex())){
Criteria2.andSexEqualTo(user.getSex());
}
Example.or(criteria2);
List<User> userList=userMapper.selectByExample(example);
类似于:select * from user where name={#user.name} or sex={#user.sex} ;
七、模糊查询
if(!StringUtils.isNotBlank(user.getName())){
criteria.andNameLIke(‘%’+name+’%’);
}
List<User> userList=userMapper.selectByExample(example);
类似于:select * from user where name like %{#user.name}%
八、分页查询
int start = (currentPage - 1) * rows;
example.setPageSize(rows);
example.setStartRow(start);
List<User> userList=userMapper.selectByExample(example);
类似于:select * from user limit start to rows
如果有收获!!! 希望老铁们来个三连,点赞、收藏、转发。
创作不易,别忘点个赞,可以让更多的人看到这篇文章,顺便鼓励我写出更好的博客
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)