Simplify development and use of general Mapper [2]

The previous chapter has finished the simple method of general mapper. This chapter will talk about how to configure the combined SQL easily.

1. First look at the Example class, first look at the properties inside

public class Example implements IDynamicTableName {
    
    
    protected String orderByClause;
    protected boolean distinct;
    protected boolean exists;
    protected boolean notNull;
    protected boolean forUpdate;
    protected Set<String> selectColumns;
    protected String countColumn;
    protected List<Example.Criteria> oredCriteria;
    protected Class<?> entityClass;
    protected EntityTable table;
    protected Map<String, EntityColumn> propertyMap;
    protected String tableName;
    protected Example.OrderBy ORDERBY;
    
    public Example(Class<?> entityClass) {
    
    
        this(entityClass, true);
    }

    public Example(Class<?> entityClass, boolean exists) {
    
    
        this(entityClass, exists, false);
    }

orderByClause: single-condition sorting (multi-conditional sorting is also possible, but manual spelling is required)
ORDERBY: multi-conditional sorting
distinct: deduplication, needs to be used in conjunction with selectColumns
exists: judges whether the attribute exists, if true, throws an exception if the attribute does not exist , when false, if it does not exist, the condition of the attribute is not used
notNull: whether the condition is null, the attribute is not null when true, and the value of the attribute is null when false
forUpdate: row-level lock
selectColumns: column name, used with other attributes
countColumn: summary
tableName: table name (you can leave it blank, the default is the table name injected into the entity @Table(name = "table name")) entityClass
: entity class
oredCriteria: the internal class collection of Example, used to splice the conditions behind where , each object is a condition, and the object array formed by it is a set of conditions

2. The role of attributes is probably these, let’s talk about how to use them in detail

Compared with the built-in CRUD methods, the biggest advantage of Example is that it is more flexible and changeable, just like writing SQL, and can be dynamically spliced ​​according to your needs

Let’s talk about the filter conditions behind where first, which is about Criteria. Criteria provides many screening methods, as shown in the following
insert image description here
figure
. Table(name = "user")

Briefly speaking, there are a few methods in it, similar to
the andEqualTo method, which is equivalent to adding an and condition, and user_id = '123', here you only need to pass in the field name of the entity, and the general mapper will automatically convert it for you into the database field name

        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId","123");

The andCondition method is more flexible. You can put together the query conditions yourself, and you can splice all the SQL you want, such as subqueries, outer joins, grouping, etc., but you need to ensure that there is no problem with the SQL spelling, otherwise an exception will be thrown

        criteria.andCondition("user_id > 50 and user_id < 100");

andIn (subquery) The value in this method is an array, it will splice the array you pass in according to the conditions of the subquery:
and user_id in ('1','2','3' )
andNotIn() result: and user_id not in ('1','2','3')

		List<String> ids= userList.stream().map(User::getUserId).collect(Collectors.toList());
        criteria.andIn("userId",ids);

andLike (fuzzy query), here is also the field name of the incoming entity

        criteria.andLike("name","%测试%");

One is equivalent to name is not null and the other is equivalent to name is null

        criteria.andIsNotNull("name");
        criteria.andIsNull("name");

Seeing this, everyone must be very confused. Most of the conditions are met. Why is there no or? There is no direct or method in Criteria, so it will be a bit troublesome to use or. The following code connects two Criteria with or

        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIsNull("name");

        Example.Criteria criteria2 = example.createCriteria();
        criteria.andIsNotNull("name");
        example.or(criteria2);

If you find it troublesome, there is another simple method, which is the andCondition method. You can directly spell it into it, which is much simpler.

        criteria.andCondition("name = '测试' or name = '测试2'");

The commonly used methods in Criteria are probably finished.

3. Let’s talk about the method in Example:

The two methods orderByClause and orderBy:

        Example example = new Example(User.class);
        example.setOrderByClause("user_id asc");

orderByClause can be sorted by single attribute or multi-attribute, but it needs to be spliced ​​by yourself, and the attributes in it must be consistent with the attribute names in the table, and you can convert camelcase by yourself

        example.setOrderByClause("user_id asc,phone desc");

If you feel troublesome, you can use orderBy:

        example.orderBy("userId");

It is enough to directly write the attribute name in the entity here, and there are 3 methods behind, asc, desc, orderBy
insert image description here
multi-conditional sorting

        example.orderBy("userId").asc();
        example.orderBy("phone").desc();

The getSelectColumns method can get all the attribute names of the incoming entity, and use it as needed

        Set<String> columns = example.getSelectColumns();

distinct deduplication, can be single or multiple, need to be used together with selectProperties (selectProperties: fields that need to be deduplicated, can be one, or multiple)

        example.setDistinct(true);
        example.selectProperties("name");
        example.selectProperties(new String[]{
    
    "name","phone"});

count an attribute

        example.setCountProperty("name");

Enable row-level locks

        example.setForUpdate(true);

clear all conditions

        example.clear();

get table name

        example.getDynamicTableName();

Let’s talk about the modification method here. There are two modification methods:

The first one is modified by ID:

According to the ID modification, you must have @Id annotation in your entity, similar to the following code

insert image description here

        User user = new User();
        user.setUserId("111");
        user.setUsername("李四");
        userMapper.updateByPrimaryKeySelective(user);

equivalent to sql

update user set username = '李四' where user_id = '111'

The second is modified according to the conditions:

This is the case where you modify based on other conditions besides ID:

        // set的值
        User user = new User();
        user.setPhone("1111111");

        // where后的条件
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", "李四");
        
        userMapper.updateByExampleSelective(user, example);

equivalent to sql

update user set phone= '1111111' where username= '李四'

Most of the basic methods in the example are finished. Each is a small method, which can be combined with each other according to the needs. Most simple SQL should be able to be combined. You may not be used to it at the beginning. You can use it a few times. It will be handy. If you feel that this set is also troublesome, you can package your own CRUD based on the general Mapper

I simply encapsulated a set of CRUD, just find a way to see it:

    /**
     * description 模糊查询
     *
     * @param t
     * @version 1.0
     * @date 2020/6/15 14:24
     */
    @Override
    public List<T> like(T t) throws IllegalAccessException {
    
    
        StringBuilder sql = new StringBuilder();
        sql.append("1!=1 ");
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields) {
    
    
            field.setAccessible(true);
            if (field.get(t) != null) {
    
    
                String name = NameUtil.underscoreName(field.getName());
                sql.append("or " + name + " like '%" + field.get(t) + "%'");
            }
        }
        Example example = new Example(t.getClass());
        example.createCriteria().andCondition(sql.toString());
        return this.mapper.selectByExample(example);
    }

Commonly used methods like fuzzy query are really comfortable to use when encapsulated

That's about it, I'll add more if necessary.

Guess you like

Origin blog.csdn.net/qq_39486119/article/details/114529508