Example of MyBatis

In reverse engineering, we can automatically produce mapper. Java, mapper. XML, po. Java, Poexample. Java required by MyBatis according to the tables of the database. We are familiar with the first three and haven’t used the poExample class until we recently encountered them in a project, so we summarize them here.

Example The Example class specifies how to build a dynamic WHERE clause. The columns of each table in a table can be included in the WHERE clause. Mainly used to simplify the writing of our SQL statements. The Example class contains an internal static class called Criteria, whose methods define the query Criteria after the SQL statement WHERE. Criteria objects can be created using the createCriteria method of the Example object.

To generate Example, note the configuration in generatorconfig.xml:

<table tableName="user" domainObjectName="User"> <! -- enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> --> </table>Copy the code

Common methods in Criteria

case

  1. Using the criteria:

    UserExample example =new UserExample(); Criteria = example.createcriteria (); criteria.setOrderByClause("id des"); / / according to the id field descending criteria. AndUsernameEqualTo (" zhangsan "); List<User> list = userMapper.selectByExample(example); // SQL: SELECT * from t_user where name=zhangsan order by ID desCopy the code
  2. Do not use criteria:

    UserExample example = new UserExample(); example.and() .andEqualTo("id", id) .andEqualTo("name", name); / / example. And () the underlying or return to the criteria of the List < User > List = userMapper. SelectByExample (example);Copy the code
  3. And and or

    UserExample example = new UserExample(); Criteria cri1 = example.createCriteria(); Criteria cri2 = example.createCriteria(); cri1.andIn("id", ids); cri2.orLike("des", "%" + des + "%"); cri2.orLike("name", "%" + name + "%"); example.and(cri2); //example.or(cri2); // where (id in ids) and (name like %des% or des like %name%)Copy the code