位运算在权限管理(配合枚举转换器)的应用(类似linux里面的文件权限管理)

12 篇文章 1 订阅

1.按位取反或者二进制补码:~

把1变为0,把0变为1

2.按位与 :&

任何位与0组合都为0,任何位与1组合都为本身

应用:关闭位(清空位)需要打开一个值中的特定位,同时保持其他位不变(所有位为0)

把1变为0,其余位不变。假设有一个二进制数00011010 ,从左到右的第4位1表示开关,现在要关闭开关(置为0)。而其余的位表示其他功能,这些功能不变。所以此时你只能改变第四位。于是可以与一个二进制数11101111结果为00001010.只有第四位变了。

应用2:检查某一位是否为1.比如检查flag中的第一位是否为1.可以用if((flag & 1000) == 1000)printf(“Yes!”);注意不能用if(flag == 1000),printf(“yes!”);

应用3:掩码。与0不管什么位结果都是0,相当于把值覆盖了,你不知道那个值是什么。与1的话,不管什么位结果都是那个值的位,相当于把那个值暴露出来了。

3.按位或: |

任何位与1组合都为1,任何位与0组合都为本身

应用:打开位(设置位) 需要打开一个值中的特定位,同时保持其他位不变。

再进一步讲,打开位是把0变为1(习惯上0为关闭,1为打开)不变的位与0组合,要变的位与1组合。可参考与去思考

4.按位异或:^

相同为0,不同为1

应用:相同为0不同为1也可以解释为假设一个位为b,0b是b。所以用0可以不改变原值。用1去异或取决与原值是什么。如果是0,10为1,如果是1,1^1为0.基于这种特性,可以用作切换位。假设原值为00001111,你有两个开关分别用从左往右第三位和第五位来表示,那么异或的那个值的第三位和第五位用1.其余用0表示不变(不会改变其他位的功能)所以用00101000,结果为00100111。结果显示只有第三位(将0变为1)和第五位(将1变为0)变了。所以是切换位。

5 左移 <<

左移n位,在保持位数不变的情形下,最左边的n位移除了,其余位依次往左移,最后用0填充最右边空出的n个位置。

int s = 1;   s <<=2;  将2变为二进制数为0001,左移2位为0100 ,0100 转化为十进制是4.

6.右移 >>

右移n位,在保持位数不变的情形下,最右边的n位移除了,其余位依次往右移,最后用0填充最左边空出的n个位置

最后要注意的是& | 和&& ||的区别。前者操作的是位,后者操作的是整个值。

结论
首先,关于正数,结论:
1、一个数左移n位,就相当于乘以了2的n次方;
2、一个数右移n位,就相当于除以了2的n次方。但是负数就不是了。那么这个-4 到底怎么算的呢?
第一,我们要知道,负数的二进制是可以通过它整数的二进制的反码、再对反码补码(+1)的出的。
第二,14的二进制为00000000 00000000 00000000 00001110,
反码为11111111 11111111 11111111 11110001 ,
(+1) 补码为11111111 11111111 11111111 11110010
所以-14的二进制为11111111 11111111 11111111 11110010
第三,-14>>2,负数右移,左补1,得:
11111111 11111111 11111111 11111100, -1得
11111111 11111111 11111111 11111011,反码得
00000000 00000000 00000000 00000100------十进制为4,所以
11111111 11111111 11111111 11111100是-4
————————————————

位运算在权限管理的实践

思路 角色枚举数据转换成int类型存储到数据库
ViewWidget.java

package com.xy.tasty.dao.core.entity;

import com.xy.common.dao.Entity;
import com.xy.tasty.dao.core.dict.RoleEnum;
import com.xy.tasty.dao.core.dict.WidgetSceneEnum;
import com.xy.tasty.dao.core.dict.WidgetTypeEnum;

import java.util.Date;
import java.util.List;

/**
 * 视图控件
 *
 * @author YJX
 * @since 2019-08-13 10:31:27
 */
public class ViewWidget extends Entity {

    private String                name;             //模块名
    private String                code;         //功能代码
    private String                url;        //连接
    private String                icon;         //图标
    private WidgetTypeEnum        type;          //类型,0:通用,1:视图,2:功能
    private List<WidgetSceneEnum> sceneMask;         //所属终端,掩码顺序:(pc端,移动端)。 表示:该功能模块可分配至哪些
    private Boolean               enabled;      //是否可用 ,默认可用
    private String                hierarchy;     //层级关系
    private List<RoleEnum>        roleMask;    //所属角色,掩码顺序:(管理,代理,组织,个体)。 表示:该功能模块可分配至哪些角色
    private String                descr;        //描述
    private Integer               rank;          //排序号
    private Date                  createTime;       //创建时间
    private Date                  updateTime;       //更新时间
    private ViewWidget            parent;         //父级模块
    private List<ViewWidget>      child;          //子级模块

    public ViewWidget() {
    }

    public ViewWidget(Long Id) {
        super(Id);
    }

}
package com.yjx.common.util;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 数值二进制工具
 *
 * @author YJX
 * @date 2018/6/1 9:06
 */
public final class BinaryUtils {

    private BinaryUtils() {
    }

    /**
     * 将参数按二进制位数的最高位分解 <br>
     * 如 : 7 ->  [1,2,4] <br>
     * 如 : 9 -> [1,8]
     *
     * @param arg
     * @return
     */
    public static List<Long> resolve(long arg) {
        if (arg < 0) {
            throw new IllegalArgumentException("参数不为空,且必须>=0");
        } else if (arg == 0) {
            return new ArrayList<>(0);
        }
        String bit = Long.toBinaryString(arg);
        Set<Long> result = new HashSet<>(10);
        for (int j = 0; j < bit.length(); j++) {
            if (bit.charAt(j) == '0') {
                continue;
            }
            result.add((long) (1 << (bit.length() - j - 1)));
        }

        return new ArrayList<>(result);
    }

}

WidgetSceneEnum.java枚举

package com.xy.tasty.dao.core.dict;

import com.xy.common.util.BinaryUtils;
import com.xy.common.verify.Asserts;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.util.*;

/**
 * @author Canaan
 * @date 2019/8/20 9:58
 */
public enum WidgetSceneEnum {

    PC(1, "PC端"),

    MOBILE(2, "移动端"),;

    private final int    value;
    private final String descr;

    WidgetSceneEnum(int value, String descr) {
        this.value = value;
        this.descr = descr;
    }

    public static WidgetSceneEnum valueOf(int value) {
        for (WidgetSceneEnum type : WidgetSceneEnum.values()) {
            if (value == type.getValue()) {
                return type;
            }
        }
        throw new IllegalStateException("WidgetSceneEnum值【" + value + "】无法转");
    }

    /**
     * 将枚举掩码转成对应枚举
     *
     * @param mark
     * @return
     */
    public static List<WidgetSceneEnum> mark(int mark) {
        int valueMax = Arrays.stream(WidgetSceneEnum.values()).mapToInt(WidgetSceneEnum::getValue).reduce(0,Integer::max);

        Asserts.state(mark >= 0 && mark <=  ((valueMax << 1) - 1), "WidgetSceneEnum掩码取值异常");

        List<Long> list = BinaryUtils.resolve(mark);

        if (list.isEmpty()) {
            return Collections.emptyList();
        }
        List<WidgetSceneEnum> result = new ArrayList<>();
        for (Long item : list) {
            result.add(valueOf(Math.toIntExact(item)));
        }
        return result;
    }
    
    /**
     * 可能包含的值
     *
     * @return
     */
    public static Set<Integer> includeSet(WidgetSceneEnum role) {
        Asserts.notNull(role);
        Set<Integer> data = new HashSet<>();
        int size = Long.toBinaryString(role.getValue()).length();
        //获取WidgetSceneEnum最大的value
        int valueMax = Arrays.stream(WidgetSceneEnum.values()).mapToInt(WidgetSceneEnum::getValue).reduce(0,Integer::max);
        //valueMax*2
        for (int i = 0; i < valueMax << 1; i++) {
            String bit = Long.toBinaryString(i);
            if (bit.length() < size) {
                continue;
            }
            if (bit.charAt(bit.length() - size) == '0') {
                continue;
            }
            data.add(i);
        }

        return data;
    }

    /**
     * 将多个枚举,转成枚举掩码
     *
     * @param role
     * @return
     */
    public static int toMark(WidgetSceneEnum... role) {
        if (ArrayUtils.isEmpty(role)) {
            return 0;
        }
        return Arrays.stream(role).distinct().mapToInt(WidgetSceneEnum::getValue).reduce(0, Integer::sum);
    }

    /**
     * 将多个枚举,转成枚举掩码
     *
     * @param scenes
     * @return
     */
    public static int toMark(List<WidgetSceneEnum> scenes) {
        if (CollectionUtils.isEmpty(scenes)) {
            return 0;
        }
        return toMark(scenes.toArray(new WidgetSceneEnum[scenes.size()]));
    }


    public int getValue() {
        return value;
    }

    public String getDescr() {
        return descr;
    }


}


RoleEnum.java

package com.xy.tasty.dao.core.dict;

import com.xy.common.util.BinaryUtils;
import com.xy.common.verify.Asserts;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.util.*;

/**
 * 角色信息
 *
 * @author Canaan
 * @date 2019/6/14 21:24
 */
public enum RoleEnum {

    /**
     * 系统管理员
     */
    ADMIN(1, "管理员"),

    /**
     * 代理
     */
    AGENCY(2, "代理"),

    /**
     * 集团
     */
    BLOC(4, "集团"),

    /**
     * 品牌
     */
    BRAND(8, "品牌"),

    /**
     * 【个体户】如:门店
     */
    STORE(32, "门店"),
    ;

    private final int    value;
    private final String descr;

    RoleEnum(int value, String descr) {
        this.value = value;
        this.descr = descr;
    }

    public static RoleEnum valueOf(int value) {
        for (RoleEnum type : RoleEnum.values()) {
            if (value == type.getValue()) {
                return type;
            }
        }
        throw new IllegalStateException("值【" + value + "】无法转");
    }

    /**
     * 将角色掩码转成对应角色
     *
     * @param mark
     * @return
     */
    public static List<RoleEnum> mark(int mark) {
        int valueMax = Arrays.stream(RoleEnum.values()).mapToInt(RoleEnum::getValue).reduce(0,Integer::max);

        Asserts.state(mark >= 0 && mark <= ((valueMax << 1) - 1), "角色掩码取值异常");

        List<Long> list = BinaryUtils.resolve(mark);

        if (list.isEmpty()) {
            return Collections.emptyList();
        }
        List<RoleEnum> result = new ArrayList<>();
        for (Long item : list) {
            result.add(valueOf(Math.toIntExact(item)));
        }
        return result;
    }

    /**
     * 可能包含的值
     *
     * @return
     */
    public static Set<Integer> includeSet(RoleEnum role) {
        Asserts.notNull(role);
        Set<Integer> data = new HashSet<>();
        int size = Long.toBinaryString(role.getValue()).length();
        //获取RoleEnum最大的value
        int valueMax = Arrays.stream(RoleEnum.values()).mapToInt(RoleEnum::getValue).reduce(0,Integer::max);
        //valueMax*2
        for (int i = 0; i < valueMax << 1; i++) {
            String bit = Long.toBinaryString(i);
            if (bit.length() < size) {
                continue;
            }
            if (bit.charAt(bit.length() - size) == '0') {
                continue;
            }
            data.add(i);
        }

        return data;
    }

    /**
     * 将多个角色,转成角色掩码
     *
     * @param roles
     * @return
     */
    public static int toMark(List<RoleEnum> roles) {
        if (CollectionUtils.isEmpty(roles)) {
            return 0;
        }
        return toMark(roles.toArray(new RoleEnum[roles.size()]));
    }

    /**
     * 将多个角色,转成角色掩码
     *
     * @param role
     * @return
     */
    public static int toMark(RoleEnum... role) {
        if (ArrayUtils.isEmpty(role)) {
            return 0;
        }
        return Arrays.stream(role).distinct().mapToInt(RoleEnum::getValue).reduce(0, Integer::sum);
    }

    public int getValue() {
        return value;
    }

    public String getDescr() {
        return descr;
    }
}


ViewWidgetPagingCriteria.java mybatis的入参

package com.xy.tasty.dao.core.criteria;

import com.xy.common.dao.PagingAbleCriteria;
import com.xy.tasty.dao.core.dict.RoleEnum;
import com.xy.tasty.dao.core.dict.WidgetSceneEnum;
import com.xy.tasty.dao.core.dict.WidgetTypeEnum;
import com.xy.tasty.dao.core.entity.ViewWidget;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 功能模块(表示系统的一个功能点,或视图)(AuthRoleView)查询
 *
 * @author YJX
 * @since 2019-08-13 10:39:13
 */
public class ViewWidgetPagingCriteria extends PagingAbleCriteria<ViewWidget> {

    private static final long serialVersionUID = 284221823720383669L;

    /**
     * id = ??
     *
     * @param id
     * @return
     */
    public ViewWidgetPagingCriteria idEQ(Long id) {
        this.appendParam("id_eq", id);
        return this;
    }

    /**
     * enabled = ??
     *
     * @param enabled
     * @return
     */
    public ViewWidgetPagingCriteria enabledEQ(Boolean enabled) {
        this.appendParam("enabled_eq", enabled);
        return this;
    }

    /**
     * id in (??)
     *
     * @param ids
     * @return
     */
    public ViewWidgetPagingCriteria idIN(List<Long> ids) {
        if (ids == null) {
            return this;
        } else if (ids.size() == 1) {
            return idEQ(ids.get(0));
        }
        this.appendParam("id_in", ids);
        return this;
    }
    /**
     * parentIds in (??)
     *
     * @author YJX
     * @date 2019-08-22 11:15
     */
    public ViewWidgetPagingCriteria parentIdIN(List<Long> parentIds) {
        if (CollectionUtils.isEmpty(parentIds)) {
            return this;
        }
        if (parentIds.size() == 1) {
            return this.parentIdEQ(parentIds.get(0));
        }
        this.appendParam("parentId_in", parentIds);
        return this;
    }

    /**
     * id in (??)
     *
     * @param ids
     */
    public ViewWidgetPagingCriteria idIN(Long... ids) {
        if (ids == null) {
            return this;
        } else if (ids.length == 1) {
            return idEQ(ids[0]);
        }
        this.appendParam("id_in", ids);
        return this;
    }

    /**
     * parent_id  is null
     *
     * @return
     */
    public ViewWidgetPagingCriteria parentIsNull() {
        this.appendParam("parent_IsNull", true);
        return this;
    }

    /**
     * code = ??
     *
     * @return
     */
    public ViewWidgetPagingCriteria codeEQ(String code) {
        this.appendParam("code_eq", code);
        return this;
    }

    /**
     * parent_id = ??
     *
     * @param parentId
     * @return
     */
    public ViewWidgetPagingCriteria parentIdEQ(Long parentId) {
        this.appendParam("parentId_eq", parentId);
        return this;
    }

    /**
     * name = ??
     *
     * @param name
     * @return
     */
    public ViewWidgetPagingCriteria nameEQ(String name) {
        this.appendParam("name_eq", name);
        return this;
    }

    /**
     * name like 'xx%'
     *
     * @return
     */
    public ViewWidgetPagingCriteria nameLike(String name) {
        this.like("name_lk", name);
        return this;
    }

    /**
     * type  = ??
     *
     * @return
     */
    public ViewWidgetPagingCriteria typeEQ(WidgetTypeEnum type) {
        this.appendParam("type_eq", type);
        return this;
    }

    /**
     * authWidgetIds in (??) <br>
     * 根据权限,获取其所配置的模块
     *
     * @return
     */
    public ViewWidgetPagingCriteria authWidgetIdIN(List<Long> authWidgetIds) {
        this.appendParam("authWidgetIds_in", authWidgetIds);
        return this;
    }

    /**
     * authWidgetId = ?? <br>
     * <p>
     * 根据权限,获取其所配置的模块
     *
     * @return
     */
    public ViewWidgetPagingCriteria authWidgetIdEQ(Long authWidgetId) {
        this.appendParam("authWidgetId_eq", authWidgetId);
        return this;
    }

    /**
     * role in (??)
     *
     * @param roles
     * @return
     */
    public ViewWidgetPagingCriteria roleIN(List<RoleEnum> roles) {
        if (CollectionUtils.isEmpty(roles)) {
            return this;
        }
        Set<Integer> set = new HashSet<>();
        for (RoleEnum role : roles) {
            set.addAll(RoleEnum.includeSet(role));
        }
        this.appendParam("roles_in", set);
        return this;
    }

    /**
     * role in (??)
     *
     * @param roles
     * @return
     */
    public ViewWidgetPagingCriteria roleIN(RoleEnum... roles) {
        if (ArrayUtils.isEmpty(roles)) {
            return this;
        }
        Set<Integer> set = new HashSet<>();
        for (RoleEnum role : roles) {
            set.addAll(RoleEnum.includeSet(role));
        }
        this.appendParam("roles_in", set);
        return this;
    }

    /**
     * scene in (??)
     *
     * @param scenes
     * @return
     */
    public ViewWidgetPagingCriteria sceneIN(List<WidgetSceneEnum> scenes) {
        if (CollectionUtils.isEmpty(scenes)) {
            return this;
        }
        Set<Integer> set = new HashSet<>();
        for (WidgetSceneEnum scene : scenes) {
            set.addAll(WidgetSceneEnum.includeSet(scene));
        }
        this.appendParam("scenes_in", set);
        return this;
    }
    /**
     * scene in (??)
     *
     * @param scenes
     * @return
     */
    public ViewWidgetPagingCriteria sceneIN(WidgetSceneEnum... scenes) {
        if (ArrayUtils.isEmpty(scenes)) {
            return this;
        }
        Set<Integer> set = new HashSet<>();
        for (WidgetSceneEnum scene : scenes) {
            set.addAll(WidgetSceneEnum.includeSet(scene));
        }
        this.appendParam("scenes_in", set);
        return this;
    }

}

WidgetSceneEnumListHandler.java枚举转换器定义

/*
 * Copyright 2019 Wicrenet, Inc. All rights reserved.
 */
package com.xy.tasty.dao.core.handler;

import com.xy.tasty.dao.core.dict.WidgetSceneEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 【】
 *
 * @author YJX
 * Created on 2019-08-23 16:42
 */
public class WidgetSceneEnumListHandler extends BaseTypeHandler<List<WidgetSceneEnum>> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<WidgetSceneEnum> item, JdbcType jdbcType) throws SQLException {
        if (item != null) {
            preparedStatement.setInt(i, WidgetSceneEnum.toMark(item));
        }
    }

    @Override
    public List<WidgetSceneEnum> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return to(resultSet.getObject(s));
    }

    @Override
    public List<WidgetSceneEnum> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return to(resultSet.getObject(i));
    }

    @Override
    public List<WidgetSceneEnum> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return to(callableStatement.getObject(i));
    }

    private List<WidgetSceneEnum> to(Object value) {
        if (value == null) {
            return null;
        }

        Integer intVal = (Integer) value;
        return WidgetSceneEnum.mark(intVal);
    }
}

RoleEnumListHandler.java 枚举转换器定义

/*
 * Copyright 2019 Wicrenet, Inc. All rights reserved.
 */
package com.xy.tasty.dao.core.handler;

import com.xy.tasty.dao.core.dict.RoleEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 【】
 *
 * @author YJX
 * Created on 2019-08-23 16:54
 */
public class RoleEnumListHandler extends BaseTypeHandler<List<RoleEnum>> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<RoleEnum> item, JdbcType jdbcType) throws SQLException {
        if (item != null) {
            preparedStatement.setInt(i, RoleEnum.toMark(item));
        }
    }

    @Override
    public List<RoleEnum> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return to(resultSet.getObject(s));
    }

    @Override
    public List<RoleEnum> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return to(resultSet.getObject(i));
    }

    @Override
    public List<RoleEnum> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return to(callableStatement.getObject(i));
    }

    private List<RoleEnum> to(Object value) {
        if (value == null) {
            return null;
        }

        Integer intVal = (Integer) value;
        return RoleEnum.mark(intVal);
    }
}

mybatis的xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xy.tasty.dao.core.ViewWidgetDao">
    <resultMap id="mapper" type="com.xy.tasty.dao.core.entity.ViewWidget">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="code" property="code"/>
        <result column="url" property="url"/>
        <result column="icon" property="icon"/>
        <result column="scene_mask" property="sceneMask" typeHandler="com.xy.tasty.dao.core.handler.WidgetSceneEnumListHandler"/>
        <result column="role_mask" property="roleMask" typeHandler="com.xy.tasty.dao.core.handler.RoleEnumListHandler"/>
        <result column="type" property="type"/>
        <result column="enabled" property="enabled"/>
        <result column="hierarchy" property="hierarchy"/>
        <result column="descr" property="descr"/>
        <result column="rank" property="rank"/>
        <result column="create_time" property="createTime" jdbcType="BIGINT" javaType="date"/>
        <result column="update_time" property="updateTime"/>
        <association property="parent" columnPrefix="parent_" resultMap="mapper"/>
    </resultMap>

    <!--【基础条件】-->
    <sql id="baseWhere">
        <trim prefixOverrides="and">
            <if test="id_eq != null">
                and `id` = #{id_eq}
            </if>
            <if test="id_in != null">
                and id in
                <foreach collection="id_in" open="(" item="id_in_item" separator="," close=")">
                    #{id_in_item}
                </foreach>
            </if>
            <if test="name_lk != null">
                and name LIKE CONCAT(#{name_lk},'%')
            </if>
            <!-- Long时间范围例子
             <if test="createTime_gt != null">
                and create_time &gt; #{createTime_gt}
            </if>
            <if test="createTime_le != null">
                and create_time &lt;= #{createTime_le}
            </if>
            -->
            <if test="parentId_eq != null">
                and `parent_id` = #{parentId_eq}
            </if>
            <if test="parentId_in != null">
                and `parent_id` in
                <foreach collection="parentId_in" open="(" item="parentId_in_item" separator="," close=")">
                    #{parentId_in_item}
                </foreach>
            </if>
            <if test="name_eq != null">
                and `name` = #{name_eq}
            </if>
            <if test="code_eq != null">
                and `code` = #{code_eq}
            </if>
            <if test="url_eq != null">
                and `url` = #{url_eq}
            </if>
            <if test="icon_eq != null">
                and `icon` = #{icon_eq}
            </if>
            <if test="type_eq != null">
                and `type` = #{type_eq}
            </if>
            <if test="enabled_eq != null">
                and `enabled` = #{enabled_eq}
            </if>
            <if test="hierarchy_eq != null">
                and `hierarchy` = #{hierarchy_eq}
            </if>
            <if test="hierarchy_lk != null">
                and `hierarchy` LIKE CONCAT(#{hierarchy_lk},'%')
            </if>
            <if test="descr_eq != null">
                and `descr` = #{descr_eq}
            </if>
            <if test="scenes_in != null">
                and scene_mask in
                <foreach collection="scenes_in" open="(" item="scene_in_item" separator="," close=")">
                    #{scene_in_item}
                </foreach>
            </if>
            <if test="roles_in != null">
                and role_mask in
                <foreach collection="roles_in" open="(" item="roles_in_item" separator="," close=")">
                    #{roles_in_item}
                </foreach>
            </if>
            <if test="rank_eq != null">
                and `rank` = #{rank_eq}
            </if>
            <if test="createTime_eq != null">
                and `create_time` = #{createTime_eq}
            </if>
            <if test="updateTime_eq != null">
                and `update_time` = #{updateTime_eq}
            </if>
        </trim>
    </sql>

    <!--【默认条件】-->
    <sql id="where">
        <if test="default_where != null and default_where">
            <where>
                <include refid="baseWhere"/>
            </where>
        </if>
        <if test="default_where == null or !default_where">
            WHERE
            <include refid="baseWhere"/>
        </if>
    </sql>

    <sql id="columns">
        <!--【动态字段】-->
        <if test="use_dynamic_column != null and use_dynamic_column">
            <trim suffixOverrides=",">
                <if test="field_id != null">
                    id,
                </if>
                <if test="field_parent != null">
                    parent_id,
                </if>
                <if test="field_name != null">
                    name,
                </if>
                <if test="field_code != null">
                    code,
                </if>
                <if test="field_url != null">
                    url,
                </if>
                <if test="field_icon != null">
                    icon,
                </if>
                <if test="field_sceneMask != null">
                    scene_mask,
                </if>
                <if test="field_type != null">
                    type,
                </if>
                <if test="field_enabled != null">
                    enabled,
                </if>
                <if test="field_hierarchy != null">
                    hierarchy,
                </if>
                <if test="field_roleMask != null">
                    role_mask,
                </if>
                <if test="field_descr != null">
                    descr,
                </if>
                <if test="field_rank != null">
                    rank,
                </if>
                <if test="field_createTime != null">
                    create_time,
                </if>
                <if test="field_updateTime != null">
                    update_time,
                </if>
            </trim>
        </if>

        <!--【固定的字段】  id, xxid,
          【可选字段】 descr
        -->
        <!-- 这里要自行修改 -->
        <if test="use_dynamic_column == null or !use_dynamic_column">
            id ,parent_id ,code,name ,url ,icon ,scene_mask ,type ,enabled ,hierarchy ,role_mask ,rank
            <if test="field_descr != null">
                ,descr
            </if>
            <if test="field_createTime != null">
                ,create_time
            </if>
            <if test="field_updateTime != null">
                ,update_time
            </if>
        </if>
    </sql>

    <!--排序-->
    <sql id="orderBy">
        <if test="order_by_map != null and !order_by_map.isEmpty()">
            ORDER BY
            <foreach collection="order_by_map" index="key" item="val" separator=",">
                <if test="key == 'id'">
                    id ${val}
                </if>
            </foreach>
        </if>
    </sql>

    <!--【新增】,必填与选填项必须分开-->
    <insert id="insert" parameterType="com.xy.tasty.dao.core.entity.ViewWidget" useGeneratedKeys="true"
            keyProperty="id">
        INSERT INTO auth_view_widget (
        name,
        code,
        url,
        icon,
        scene_mask,
        type,
        enabled,
        role_mask,
        rank,
        create_time,
        parent_id
        <if test="descr != null">
            ,descr
        </if>
        )
        VALUES (
        #{name},
        #{code},
        #{url},
        #{icon},
        #{sceneMask,typeHandler=com.xy.tasty.dao.core.handler.WidgetSceneEnumListHandler},
        #{type,typeHandler=com.xy.tasty.dao.core.handler.WidgetViewTypeEnumHandler},
        #{enabled},
        #{roleMask,typeHandler=com.xy.tasty.dao.core.handler.RoleEnumListHandler},
        #{rank},
        #{createTime,jdbcType=BIGINT},
        #{parent.id}
        <if test="descr != null">
            ,#{descr}
        </if>
        )
    </insert>
    <sql id="updateSet">
        <trim suffixOverrides=",">
            <if test="name != null">
                name = #{name},
            </if>
            <if test="enabled != null">
                enabled = #{enabled},
            </if>
            <if test="url != null">
                url = #{url},
            </if>
            <if test="sceneMask != null">
                `scene_mask` = #{sceneMask,typeHandler=com.xy.tasty.dao.core.handler.WidgetSceneEnumListHandler},
            </if>
            <if test="roleMask != null">
                role_mask=#{roleMask,typeHandler=com.xy.tasty.dao.core.handler.RoleEnumListHandler},
            </if>
            <if test="descr != null">
                descr=#{descr},
            </if>
            <if test="rank != null">
                rank = #{rank},
            </if>
            <if test="icon != null">
                icon = #{icon},
            </if>
        </trim>
    </sql>

    <update id="update" parameterType="com.xy.tasty.dao.core.entity.ViewWidget">
        UPDATE auth_view_widget SET
        <include refid="updateSet"/>
        WHERE id = #{id}
    </update>

    <!--更新,不能选择【默认条件】-->
    <update id="updateByCriteria" parameterType="map">
        UPDATE auth_view_widget SET
        <include refid="updateSet"/>
        WHERE
        <include refid="baseWhere"/>
        <if test="limit_begin != null">
            LIMIT #{limit_begin}
        </if>

    </update>

    <!--【分页查询】,必须选带【默认条件】-->
    <select id="select" parameterType="map" resultMap="mapper">
        SELECT
        <include refid="columns"/>
        FROM auth_view_widget
        <include refid="where"/>
        <include refid="orderBy"/>
    </select>

    <!--记录个数查询,必须选带【默认条件】-->
    <select id="selectCount" parameterType="map" resultType="long">
        SELECT count(*) from auth_view_widget
        <where>
            <include refid="baseWhere"/>
        </where>
    </select>

    <!--【删除】-->
    <update id="delete" parameterType="map">
        DELETE FROM auth_view_widget
        WHERE
        <include refid="baseWhere"/>
        <if test="limit_begin != null">
            LIMIT #{limit_begin}
        </if>

    </update>

</mapper>
1 使用的时候主要是查询的时候ViewWidgetPagingCriteria 需要用枚举里面的includeSet方法
2 xml里面除查询都需要加上mybatis的TypeHandler转换器
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值