MyBatis的Example类学习
原文链接:MyBatis的Example类详解
关于Example类的定义?
mybatis-generator会为每个字段产生Criterion,为底层的mapper.xml创建动态sql。如果表的字段比较多,产生的example类会十分庞大。理论上通过example类可以构造你想到的任何筛选条件。
在mybatis-generator中加以配置,配置数据表的生成操作就可以自动生成example了。这里对定义类型的不再过多解释,直接上干货。
1、查询:
- selectByPrimaryKey
1 User user = UserMapper.selectByPrimaryKey("1001"); 2 等同于:select * from user where id = "1001"
- selectByExample (and条件)
1 Example example = new Example(User.class); 2 example.createCriteria().andEqualTo("id", "1001" ) 3 .andEqualTo("userName", "小李"); 4 User user = UserMapper.selectByExample(example); 5 6 等同于:select * from user where id = "1001" and username = '小李'
- selectByExample (or条件)
1 Example example = new Example(User.class); 2 example.or.andEqualTo("id", "1001" ) 3 example.or.andEqualTo("userName", "小李"); 4 User user = UserMapper.selectByExample(example); 5 6 等同于:select * from user where id = "1001" or username = '小李'
- selectByExample (and+or多条件查询)
1 Example example = new Example(User.class); 2 example.createCriteria().andEqualTo("id", "1" ) 3 .andEqualTo("userId", "1001"); 4 example.and().orEqualTo("userName","小李") 5 .orEqualTo("passWord","123"); 6 List<User> user = UserMapper.selectByExample(example); 7 8 等同于: 9 SELECT id,user_id,user_name,pass_word FROM user WHERE ( id = "1" and user_id = "1001" ) and ( user_name = "小李" or pass_word = "123" )
2、插入:
1 User user = new User(); 2 user.setId("2"); 3 user.setUserId("1002"); 4 user.setUserName("小王"); 5 user.setPassWord("666") 6 UserMapper.insert(user); 7 等同于:insert into user(id,user_id ,user_name,pass_word) values ('2','1002','小王','666');
3、更新:
- updateByPrimaryKey
1 User user = new User(); 2 user.setId("2"); 3 user.setUserId("1002"); 4 user.setUserName("小王"); 5 user.setPassWord("666") 6 UserMapper.updateByPrimaryKey(user); 7 等同于:update user set user_id = "1002" user_name='小王', pass_word='666' where id='2'
- updateByExampleSelective
1 注意:updateByExample()更新所有的字段,包括字段为null的,建议使用 updateByExampleSelective()更新需要更新的字段 2 3 Example example = new Example(User.class); 4 example.createCriteria().andEqualTo("id","2"); 5 6 User user = new User(); 7 user.setUserName("小王"); 8 9 UserMapper.updateByExampleSelective(user,example); 10 11 等同于:update user set user_name='小王' where id='2'
4、删除:
- deleteByPrimaryKey
1 UserMapper.deleteByPrimaryKey("1"); //相当于:delete from user where id="1"
- deleteByExample
1 Example example = new Example(User.class); 2 example.createCriteria().andEqualTo("userId","1002"); 3 UserMapper.deleteByExample(example); 4 等同于:delete from user where userId='1002'
5、查询数量:
1 Example example = new Example(User.class); 2 example.createCriteria().andEqualTo("id", "1001" ) 3 4 UserMapper.countByExample(example); 5 等同于:select count(*) from user where id='1001'