MyBatis generator generated Example file usage

MyBatis generator generates time code data with a database table, in addition to generating entity outside POJO, it will also generate documents Example, and in Example sql statement generated in mapper.xml.

Example class contains an internal static class Criteria, Criteria we can take advantage of dynamically generated sql where the words according to their needs in the class, we do not own and then modify mapper file to add or modify the sql statement, can save a lot of time to write sql.

The following describes several commonly used methods (see above Bowen, then there is no summary):

1. Fuzzy Search Username:

String name = “明”;
UserExample ex = new UserExample();
ex.createCriteria().andNameLike(’%’+name+’%’);
List userList = userDao.selectByExample(ex);

2. Sort through a field:

String orderByClause = "id DESC";
UserExample ex = new UserExample();
ex.setOrderByClause(orderByClause);
List<User> userList = userDao.selectByExample(ex);

3. Search conditions, the number of uncertain conditions:

UserExample ex = new UserExample();
Criteria criteria = ex.createCriteria();
if(StringUtils.isNotBlank(user.getAddress())){
    criteria.andAddressEqualTo(user.getAddress());
}
if(StringUtils.isNotBlank(user.getName())){
    criteria.andNameEqualTo(user.getName());
}
List<User> userList = userDao.selectByExample(ex);

4. Page Search List:

pager.setPageNum(1);
pager.setPageSize(5);
UserExample ex = new UserExample();
ex.setPage(pager);
List<User> userList = userDao.selectByExample(ex);

Guess you like

Origin www.cnblogs.com/dekevin/p/12301824.html