在使用逆向工程生成代码时,可选择生成实体类和xxxExample类,xxxExample的作用是什么呢
Example实例解析
example用于添加条件,相当where后面的部分
xxxExample example = new xxxExample(); Criteria criteria = new Example().createCriteria();
应用举例
逆向工程生成的文件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"); List<?>list = 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'