mybatis逆向工程生成的xxxExample实例详解

在使用逆向工程生成代码时,可选择生成实体类和xxxExample类,xxxExample的作用是什么呢

1.Example实例解析

example用于添加条件,相当where后面的部分
例如

xxxExample example = new xxxExample();
Criteria criteria = new Example().createCriteria();

mybatis逆向工程生成的xxxExample实例详解_第1张图片

2.应用举例

逆向工程生成的文件XxxExample.java中包含一个static的内部类Criteria,Criteria中的方法是定义SQL 语句where后的查询条件。
1.查询

① selectByPrimaryKey()

User user = XxxMapper.selectByPrimaryKey(100); //相当于select * from user where id = 100

② selectByExample()

UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("wyw");    //where条件
criteria.andUsernameIsNull();					//where条件
example.setOrderByClause("username asc,email desc");
Listlist = XxxMapper.selectByExample(example);
//相当于:select * from user where username = 'wyw' and  username is null order by username asc,email desc

2.更新数据
updateByExample()

UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("admin");   //where条件
User user = new User();
user.setPassword("wyw");
XxxMapper.updateByPrimaryKeySelective(user,example);
//相当于:update user set password='wyw' where username='admin'

3.删除数据
deleteByExample()

UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("admin");
XxxMapper.deleteByExample(example);
//相当于:delete from user where username='admin'

4.查询数据数量
countByExample()

UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("wyw");
int count = XxxMapper.countByExample(example);
//相当于:select count(*) from user where username='wyw'

你可能感兴趣的:(mybatis)