mybatis中一些自帶常用的方法
① selectByPrimaryKey()
User user = userDAO.selectByPrimaryKey(100); 相當於select * from user where id = 100
② selectByExample() 和 selectByExampleWithBLOGs()
UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("joe");
criteria.andUsernameIsNull();
example.setOrderByClause
List<?>list = userDAO.selectByExample(example);
相當於:select * from user where username = 'joe' and username is null order by username asc,email desc
注:在iBator 生成的檔案UserExample.java中包含一個static 的內部類 Criteria ,在Criteria中有很多方法,主要是定義SQL 語句where後的查詢條件。
③ insert()
User user = new
user.setId(101);
user.setUsername("test");
user.setPassword("123")
user.setEmail("");
userDAO.insert(user);
相當於:insert into user(ID,username,password,email) values(101,'test','123','');
④ updateByPrimaryKey() 和 updateByPrimaryKeySelective()
User user =new User();
user.setId(101);
user.setUsername("joe
user.setPassword("joe");
user.setEmail("");
userDAO.updateByPrimaryKey(user);
相當於:update user set username='joe',password='joe',email='' where id=101
User user = new User();
user.setId(101);
user.setPassword("joe");
userDAO.updateByPrimaryKeySelective(user);
相當於:update user set password='joe' where id=101
⑤updateByExample() 和 updateByExampleSelective()
UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("joe");
User user = new User();
user.setPassword("123");
userDAO.updateByPrimaryKeySelective(user,example);
相當於:update user set password='123' where username='joe'
⑥deleteByPrimaryKey()
userDAO.deleteByPrimaryKey(101); 相當於:delete from user where id=101
⑦ deleteByExample()
UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("joe");
userDAO.deleteByExample(example);
相當於:delete from user where username='joe'
⑧ countByExample()
UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("joe");
int count = userDAO.countByExample(example);
相當於:select count(*) from user where username='joe'