欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

mybatis中數(shù)據(jù)加密與解密的實(shí)現(xiàn)

 更新時(shí)間:2022年03月16日 11:07:35   作者:我是屬車(chē)的  
數(shù)據(jù)加解密的實(shí)現(xiàn)方式多種多樣,在mybatis環(huán)境中數(shù)據(jù)加解密變得非常簡(jiǎn)單易用,本文主要介紹了mybatis中數(shù)據(jù)加密與解密的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

數(shù)據(jù)加解密的實(shí)現(xiàn)方式多種多樣,在mybatis環(huán)境中數(shù)據(jù)加解密變得非常簡(jiǎn)單易用,本文旨在提供參考,在生產(chǎn)中應(yīng)盡可能完成單元測(cè)試,開(kāi)展足夠的覆蓋測(cè)試,以驗(yàn)證可靠性、可用性、安全性。

1、需求

**原始需求:**數(shù)據(jù)在保存時(shí)進(jìn)行加密,取出時(shí)解密,避免被拖庫(kù)時(shí)泄露敏感信息。

**初始分析:**數(shù)據(jù)從前端過(guò)來(lái),到達(dá)后端,經(jīng)過(guò)業(yè)務(wù)邏輯后存入數(shù)據(jù)庫(kù),其中經(jīng)歷三大環(huán)節(jié):

1、前端與后端之間傳輸,是否加密,如果需要加密則前端傳輸前就需要加密,暫時(shí)可以用HTTPS代替;
2、到達(dá)后端,此時(shí)數(shù)據(jù)通常需要經(jīng)過(guò)一些邏輯判斷,所以加密沒(méi)有意義,反而會(huì)帶來(lái)不必要的麻煩;
3、入庫(kù),這個(gè)是最后環(huán)節(jié),數(shù)據(jù)經(jīng)過(guò)insert的sql或者update語(yǔ)句入庫(kù),在此前需要加密;

**核心需求:**入庫(kù)前最后一步完成數(shù)據(jù)加密,達(dá)成的目的是如果數(shù)據(jù)庫(kù)被暴露,一定程度上保障數(shù)據(jù)的安全,也可以防止有數(shù)據(jù)操作權(quán)限的人將數(shù)據(jù)泄露。

**加密算法:**對(duì)稱和非對(duì)稱算法均可,考慮加密和解密的效率以及場(chǎng)景,考慮選用對(duì)稱算法AES加密。

**ORM環(huán)境:**mybatis

**加密字段:**加密字段不確定,應(yīng)該在數(shù)據(jù)庫(kù)表設(shè)計(jì)的時(shí)候確定敏感字段,即加密字段可定制。

應(yīng)注意的細(xì)節(jié):

1、某個(gè)字段被加密后,其字段的存取性能下降,加密字段越多性能下降就越多,無(wú)具體指標(biāo);
2、字段被加密后,該字段的索引沒(méi)有太大意義,比如對(duì)手機(jī)號(hào)碼字段mobile加密,原先可能設(shè)計(jì)為唯一索引以防止號(hào)碼重復(fù),加密后密文性能下降,比對(duì)結(jié)果不直觀,沒(méi)有大量數(shù)據(jù)驗(yàn)證,理論上密文也不會(huì)相同;
3、一些SQL的比對(duì)也無(wú)法直接實(shí)現(xiàn),比如手機(jī)號(hào)碼匹配查詢,在開(kāi)發(fā)和運(yùn)維中,就需要考慮后續(xù)工作中敏感字段的可操作性;
4、原字段的長(zhǎng)度需要擴(kuò)充,密文肯定比原文長(zhǎng);
5、不要對(duì)主鍵加密(真的,有人會(huì)這么做的);
6、有時(shí),為了減少關(guān)聯(lián)查詢,我們會(huì)對(duì)表做冗余字段,比如將name字段放入業(yè)務(wù)表,如果對(duì)name字段加密,則需同步對(duì)冗余表做加密處理,所以在進(jìn)行數(shù)據(jù)加密需求時(shí),應(yīng)進(jìn)行全局考慮。

最后:數(shù)據(jù)加密用來(lái)提高安全性的同時(shí),必然會(huì)犧牲整個(gè)程序性能和易用性。

2、解決方案

在mybatis的依賴環(huán)境下,至少有兩種自動(dòng)加密的方式:

1、使用攔截器,對(duì)insert和update語(yǔ)句攔截,獲取需加密字段,加密后存入數(shù)據(jù)庫(kù)。讀取時(shí)攔截query,解密后存入result對(duì)象;      
2、使用類(lèi)型轉(zhuǎn)換器TypeHandler來(lái)實(shí)現(xiàn)。

3、使用攔截器方式

3.1 定義加密接口

因?yàn)閙ybatis攔截器會(huì)攔截所有符合簽名的請(qǐng)求,為了提高效率定義一個(gè)標(biāo)記接口非常重要,既然有接口不如就在接口里加入需要加密的字段信息,當(dāng)然也可以不加,根據(jù)實(shí)際場(chǎng)景來(lái)設(shè)計(jì)。

/**
 * @author: xu.dm
 * @since: 2022/3/8 16:30
 * 該接口用于標(biāo)記實(shí)體類(lèi)需要加密,具體的加密內(nèi)容字段通過(guò)getEncryptFields返回.
 * 注意:getEncryptFields與@Encrypt注解可配合使用也可以互斥使用,根據(jù)具體的需求實(shí)現(xiàn)。
 **/
public interface Encrypted {
    /**
     * 實(shí)現(xiàn)該接口,返回需要加密的字段名數(shù)組,需與類(lèi)中字段完全一致,區(qū)分大小寫(xiě)
     * @return 返回需要加密的字段
     */
    default String[] getEncryptFields() {
        return new String[0];
    }
}

3.2 定義加密注解

主要為了某些場(chǎng)景,直接在實(shí)體類(lèi)的字段打標(biāo)記,直觀的說(shuō)明該字段是加密字段,某些業(yè)務(wù)邏輯也可以依賴此標(biāo)記做進(jìn)一步操作,一句話,根據(jù)場(chǎng)景來(lái)適配和設(shè)計(jì)。

/**
 * @author : xu.dm
 * @since : 2022/3/8
 * 標(biāo)識(shí)加密的注解,value值暫時(shí)沒(méi)用,根據(jù)需要可以考慮采用的加密方式與算法等
 * 注意:Encrypted接口的getEncryptFields與@Encrypt注解可配合使用也可以互斥使用,根據(jù)具體的需求實(shí)現(xiàn)。
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Encrypt {
    String value() default "";
}

3.3 攔截器加密數(shù)據(jù)

初始攔截器定義是相對(duì)單一的場(chǎng)景,利用反射遍歷需加密的字段,對(duì)字段的字符加密,也就是待加密字段最好是字符串類(lèi)型,并且,沒(méi)有對(duì)父類(lèi)反射遍歷,如果有繼承情況,并且父類(lèi)也有需要加密的字段,需根據(jù)場(chǎng)景調(diào)整代碼,對(duì)父類(lèi)遞歸,直到根父類(lèi)。在當(dāng)前設(shè)計(jì)中Encrypted接口和@Encrypt只會(huì)生效一種,并且以接口優(yōu)先。

/**
 * @author: xu.dm
 * @since: 2022/3/8
 * 攔截所有實(shí)現(xiàn)Encrypted接口的實(shí)體類(lèi)insert和update操作
 * 如果接口的getEncryptFields返回?cái)?shù)組長(zhǎng)度大于0,則使用該參數(shù)進(jìn)行加密,
 * 否則檢查實(shí)體類(lèi)中帶@Encrypt注解,對(duì)該標(biāo)識(shí)字段加密,
 * 注意:待加密的字段最好是字符串,加密調(diào)用的是標(biāo)識(shí)對(duì)象的ToString()結(jié)果進(jìn)行加密,
 *
 **/
@Component
@Slf4j
@Intercepts({
        @Signature(method = "update", type = Executor.class, args = {MappedStatement.class, Object.class})
})
public class EncryptionInterceptor implements Interceptor {

    public EncryptionInterceptor() {

    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        Object[] args = invocation.getArgs();
        SqlCommandType sqlCommandType = null;

        for (Object object : args) {
            // 從MappedStatement參數(shù)中獲取到操作類(lèi)型
            if (object instanceof MappedStatement) {
                MappedStatement ms = (MappedStatement) object;
                sqlCommandType = ms.getSqlCommandType();
                log.debug("Encryption interceptor 操作類(lèi)型: {}", sqlCommandType);
                continue;
            }
            log.debug("Encryption interceptor 操作參數(shù):{}",object);

            // 判斷參數(shù)
            if (object instanceof Encrypted) {
                if (SqlCommandType.INSERT == sqlCommandType) {
                    encryptField((Encrypted)object);
                    continue;
                }
                if (SqlCommandType.UPDATE == sqlCommandType) {
                    encryptField((Encrypted)object);
                    log.debug("Encryption interceptor update operation,encrypt field: {}",object.toString());
                }
            }
        }
        return invocation.proceed();
    }


    /**
     * @param object 待檢查的對(duì)象
     * @throws IllegalAccessException
     * 通過(guò)查詢注解@Encrypt或者Encrypted返回的字段,進(jìn)行動(dòng)態(tài)加密
     * 兩種方式互斥
     */
    private void encryptField(Encrypted object) throws IllegalAccessException, NoSuchFieldException {
        String[] encryptFields = object.getEncryptFields();
        String factor = "xu.dm118dAADF!@$";
        Class<?> clazz = object.getClass();

        if(encryptFields.length==0){
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Encrypt encrypt = field.getAnnotation(Encrypt.class);
                if(encrypt!=null) {
                    String encryptString = AesUtils.encrypt(field.get(object).toString(), factor);
                    field.set(object,encryptString);
                    log.debug("Encryption interceptor,encrypt field: {}",field.getName());
                }
            }
        }else {
            for (String fieldName : encryptFields) {
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                String encryptString = AesUtils.encrypt(field.get(object).toString(), factor);
                field.set(object,encryptString);
                log.debug("Encryption interceptor,encrypt field: {}",field.getName());
            }
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

}

3.4 攔截器解密數(shù)據(jù)

解密時(shí)攔截query方法,只對(duì)結(jié)果集判斷,結(jié)果屬于Encrypted接口或者結(jié)果結(jié)果集第一條數(shù)據(jù)屬于Encrypted接口則進(jìn)入解密流程。

解密失敗或者解密方法返回空串后,不會(huì)修改原本字段數(shù)據(jù)。

/**
 * @author: xu.dm
 * @since: 2022/3/9 11:39
 * 解密數(shù)據(jù),返回結(jié)果為list集合時(shí),應(yīng)保證集合里都是同一類(lèi)型的元素。
 * 解密失敗時(shí)返回為null,或者返回為空串時(shí),不對(duì)原數(shù)據(jù)操作。
 **/
@Component
@Slf4j
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
})
public class DecryptionInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();
        if(result instanceof ArrayList) {
            @SuppressWarnings("rawtypes")
            ArrayList list = (ArrayList) result;
            if(list.size() == 0) {
                return result;
            }
            if(list.get(0) instanceof Encrypted) {
                for (Object item : list) {
                    decryptField((Encrypted) item);
                }
            }
            return result;
        }
        if(result instanceof Encrypted) {
            decryptField((Encrypted) result);
        }
        return result;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    /**
     * @param object 待檢查的對(duì)象
     * @throws IllegalAccessException
     * 通過(guò)查詢注解@Encrypt或者Encrypted返回的字段,進(jìn)行解密
     * 兩種方式互斥
     */
    private void decryptField(Encrypted object) throws IllegalAccessException, NoSuchFieldException {
        String[] encryptFields = object.getEncryptFields();
        String factor = "xu.dm118dAADF!@$";
        Class<?> clazz = object.getClass();

        if(encryptFields.length==0){
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Encrypt encrypt = field.getAnnotation(Encrypt.class);
                if(encrypt!=null) {
                    String encryptString = AesUtils.decrypt(field.get(object).toString(), factor);
                    if(encryptString!=null){
                        field.set(object,encryptString);
                        log.debug("Encryption interceptor,encrypt field: {}",field.getName());
                    }
                }
            }
        }else {
            for (String fieldName : encryptFields) {
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                String encryptString = AesUtils.decrypt(field.get(object).toString(), factor);
                if(encryptString!=null && encryptString.length() > 0){
                    field.set(object,encryptString);
                    log.debug("Encryption interceptor,encrypt field: {}",field.getName());
                }
            }
        }
    }
}

3.5 解密工具類(lèi)

解密工具類(lèi)可根據(jù)場(chǎng)景進(jìn)一步優(yōu)化,例如:可考慮解密類(lèi)實(shí)例化后常駐內(nèi)存,以減少CPU負(fù)載。

/**
 * @author: xu.dm
 * @since: 2018/11/24 22:26
 *
 */
public class AesUtils {
    private static final String ALGORITHM = "AES/ECB/PKCS5Padding";

    public static String encrypt(String content, String key) {
        try {
            //獲得密碼的字節(jié)數(shù)組
            byte[] raw = key.getBytes();
            //根據(jù)密碼生成AES密鑰
            SecretKeySpec keySpec = new SecretKeySpec(raw, "AES");
            //根據(jù)指定算法ALGORITHM自成密碼器
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            //初始化密碼器,第一個(gè)參數(shù)為加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作,第二個(gè)參數(shù)為生成的AES密鑰
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            //獲取加密內(nèi)容的字節(jié)數(shù)組(設(shè)置為utf-8)不然內(nèi)容中如果有中文和英文混合中文就會(huì)解密為亂碼
            byte [] contentBytes = content.getBytes(StandardCharsets.UTF_8);
            //密碼器加密數(shù)據(jù)
            byte [] encodeContent = cipher.doFinal(contentBytes);
            //將加密后的數(shù)據(jù)轉(zhuǎn)換為字符串返回
            return Base64.encodeBase64String(encodeContent);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("AesUtils加密失敗");
        }
    }

    public static String decrypt(String encryptStr, String decryptKey) {
        try {
            //獲得密碼的字節(jié)數(shù)組
            byte[] raw = decryptKey.getBytes();
            //根據(jù)密碼生成AES密鑰
            SecretKeySpec keySpec = new SecretKeySpec(raw, "AES");
            //根據(jù)指定算法ALGORITHM自成密碼器
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            //初始化密碼器,第一個(gè)參數(shù)為加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作,第二個(gè)參數(shù)為生成的AES密鑰
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            //把密文字符串轉(zhuǎn)回密文字節(jié)數(shù)組
            byte [] encodeContent = Base64.decodeBase64(encryptStr);
            //密碼器解密數(shù)據(jù)
            byte [] byteContent = cipher.doFinal(encodeContent);
            //將解密后的數(shù)據(jù)轉(zhuǎn)換為字符串返回
            return new String(byteContent, StandardCharsets.UTF_8);
        } catch (Exception e) {
            // e.printStackTrace();
            // 解密失敗暫時(shí)返回null,可以拋出runtime異常
            return null;
        }
    }
}

3.6 實(shí)體類(lèi)樣例

/**
 * (SysUser)實(shí)體類(lèi)
 *
 * @author xu.dm
 * @since 2020-05-02 09:34:53
 */
@EqualsAndHashCode(callSuper = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString(exclude = {"password","username"},callSuper = true)
public class SysUser extends BaseDO implements Serializable, Encrypted {
    private static final long serialVersionUID = 100317866935565576L;
    /**
    * ID 轉(zhuǎn)換成字符串給前端,否則js會(huì)出現(xiàn)精度問(wèn)題
    * 對(duì)于前后臺(tái)傳參Long類(lèi)型64位而言,當(dāng)前端超過(guò)53位后會(huì)丟失精度,超過(guò)的部分會(huì)以00的形式展示.
     * 可以使用   @JsonSerialize(using = ToStringSerializer.class)
    */
    @JsonSerialize(using = ToStringSerializer.class)
    private Long id;
    /**
    * 手機(jī)號(hào)碼
    */
    @Encrypt
    private String mobile;
    /**
    * 用戶登錄名稱
    */
    private String username;

    private String name;
    /**
    * 密碼
    */
    @JsonIgnore
    private String password;
    /**
    * email
    */
    private String email;

    @Override
    public String[] getEncryptFields() {
        return new String[]{"mobile","name"};
    }
}

4、使用類(lèi)型轉(zhuǎn)換器

在mybatis中使用類(lèi)型轉(zhuǎn)換器,本質(zhì)上就是就自定義一個(gè)類(lèi)型(本質(zhì)就是一個(gè)類(lèi)),通過(guò)mybatis提供的TypeHandler接口擴(kuò)展,對(duì)數(shù)據(jù)類(lèi)型轉(zhuǎn)換,在這個(gè)過(guò)程中加入加密和解密業(yè)務(wù)邏輯實(shí)現(xiàn)數(shù)據(jù)存儲(chǔ)和查詢的加解密功能。

4.1 定義加密類(lèi)型

這個(gè)類(lèi)型就直接理解成類(lèi)似java.lang.String。如果對(duì)加密的方式有多種需求,可擴(kuò)N種EncryptType類(lèi)型。

/**
 * @author: xu.dm
 * @since: 2022/3/9 16:54
 * 自定義類(lèi)型,用于在mybatis中表示加密類(lèi)型
 * 需要加密的字段使用EncryptType聲明
 **/
public class EncryptType {
    private String value;

    public EncryptType() {
    }

    public EncryptType(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value;
    }
}

4.2 定義類(lèi)型轉(zhuǎn)換處理器

AesUtils工具類(lèi)見(jiàn)上文描述。

轉(zhuǎn)換器繼承自mybatisBaseTypeHandler,重寫(xiě)值設(shè)置和值獲取的方法,在其過(guò)程中加入加密和解密邏輯。

/**
 * @author: xu.dm
 * @since: 2022/3/9 16:21
 * 類(lèi)型轉(zhuǎn)換器,處理EncryptType類(lèi)型,用于數(shù)據(jù)加解密
 **/
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(EncryptType.class)
public class EncryptTypeHandler extends BaseTypeHandler<EncryptType> {
    private String factor = "xu.dm118dAADF!@$";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, EncryptType parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null || parameter.getValue() == null) {
            ps.setString(i, null);
            return;
        }
        String encrypt = AesUtils.encrypt(parameter.getValue(),factor);
        ps.setString(i, encrypt);
    }

    @Override
    public EncryptType getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String decrypt = AesUtils.decrypt(rs.getString(columnName), factor);
        if(decrypt==null || decrypt.length()==0){
            decrypt = rs.getString(columnName);
        }
        return new EncryptType(decrypt);
    }

    @Override
    public EncryptType getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String decrypt = AesUtils.decrypt(rs.getString(columnIndex), factor);
        if(decrypt==null || decrypt.length()==0){
            decrypt = rs.getString(columnIndex);
        }
        return new EncryptType(decrypt);
    }

    @Override
    public EncryptType getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String decrypt = AesUtils.decrypt(cs.getString(columnIndex), factor);
        if(decrypt==null || decrypt.length()==0){
            decrypt = cs.getString(columnIndex);
        }
        return new EncryptType(decrypt);
    }
}

4.3 配置類(lèi)型轉(zhuǎn)換器的包路徑

這個(gè)配置是可選的,因?yàn)榭梢栽趍apper的映射xml文件中指定。

mybatis:
  #xml映射版才需要配置,純注解版本不需要
  mapper-locations: classpath*:mapper/*.xml #多模塊指定sql映射文件的位置,需要在classpath后面多加一個(gè)星號(hào)
  type-handlers-package: com.wood.encryption.handler

4.4 測(cè)試用的實(shí)體類(lèi)

截取了部分代碼,關(guān)注代碼中使用EncryptType類(lèi)型的字段name和mobile。

/**
 * (TestUser)實(shí)體類(lèi)
 *
 * @author xu.dm
 * @since 2022-03-10 11:31:54
 */
@Data
public class TestUser extends BaseDO implements Serializable {
    private static final long serialVersionUID = -53491943096074862L;
    /**
     * ID
     */
    private Long id;
    /**
     * 手機(jī)號(hào)碼
     */
    private EncryptType mobile;
    /**
     * 用戶登錄名稱
     */
    private String username;
    /**
     * 用戶名或昵稱
     */
    private EncryptType name;
    /**
     * 密碼
     */
    private String password;
    /**
     * email
     */
    private String email;
	
    ... ...

}

4.5 mapper接口文件

這個(gè)類(lèi)沒(méi)有本質(zhì)的變化,截取了部分代碼,注意EncryptType類(lèi)型的使用。

/**
 * (TestUser)表數(shù)據(jù)庫(kù)訪問(wèn)層
 *
 * @author xu.dm
 * @since 2022-03-10 11:31:54
 */
public interface TestUserDao {

    /**
     * 查詢手機(jī)號(hào)碼,通過(guò)主鍵
     *
     * @param id 主鍵
     * @return 手機(jī)號(hào)碼
     */
    EncryptType queryMobileById(Long id);

    /**
     * 通過(guò)手機(jī)號(hào)碼查詢單條數(shù)據(jù)
     *
     * @param mobile 手機(jī)號(hào)碼
     * @return 實(shí)例對(duì)象
     */
    List<TestUser> queryByMobile(EncryptType mobile);

    /**
     * 通過(guò)ID查詢單條數(shù)據(jù)
     *
     * @param id 主鍵
     * @return 實(shí)例對(duì)象
     */
    TestUser queryById(Long id);

    /**
     * 查詢所有數(shù)據(jù),根據(jù)入?yún)?,決定是否模糊查詢
     *
     * @param testUser 查詢條件
     * 
     * @return 對(duì)象列表
     */
    List<TestUser> queryByBlurry(TestUser testUser);

    /**
     * 統(tǒng)計(jì)總行數(shù)
     *
     * @param testUser 查詢條件
     * @return 總行數(shù)
     */
    long count(TestUser testUser);

    /**
     * 新增數(shù)據(jù)
     *
     * @param testUser 實(shí)例對(duì)象
     * @return 影響行數(shù)
     */
    int insert(TestUser testUser);

   
    /**
     * 修改數(shù)據(jù)
     *
     * @param testUser 實(shí)例對(duì)象
     * @return 影響行數(shù)
     */
    int update(TestUser testUser);


}

4.6 mapper映射文件

沒(méi)有本質(zhì)變化,截取了部分代碼,注意EncryptType類(lèi)型的使用。

<?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.wood.system.dao.TestUserDao">

    <resultMap type="com.wood.system.entity.TestUser" id="TestUserMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="mobile" column="mobile" jdbcType="VARCHAR"/>
        <result property="username" column="username" jdbcType="VARCHAR"/>
        <result property="name" column="name" jdbcType="VARCHAR"/>
        <result property="password" column="password" jdbcType="VARCHAR"/>
        <result property="email" column="email" jdbcType="VARCHAR"/>
        <result property="state" column="state" jdbcType="VARCHAR"/>
        <result property="level" column="level" jdbcType="VARCHAR"/>
        <result property="companyId" column="company_id" jdbcType="INTEGER"/>
        <result property="deptId" column="dept_id" jdbcType="INTEGER"/>
        <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
        <result property="updateTime" column="update_time" jdbcType="TIMESTAMP"/>
    </resultMap>

    <!--查詢單個(gè)-->
    <select id="queryById" resultMap="TestUserMap">
        select
          id, mobile, username, name, password, email, state, level, company_id, dept_id, create_time, update_time
        from test_user
        where id = #{id}
    </select>

    <!--查詢指定行數(shù)據(jù)-->
    <select id="queryByBlurry" resultMap="TestUserMap">
        select
          id, mobile, username, name, password, email, state, level, company_id, dept_id, create_time, update_time
        from test_user
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="mobile != null and mobile != ''">
                and mobile = #{mobile}
            </if>
            <if test="username != null and username != ''">
                and username = #{username}
            </if>
            <if test="name != null and name != ''">
                and name = #{name}
            </if>
			... ...

        </where>        
    </select>
  
    <select id="queryMobileById" resultType="com.wood.encryption.type.EncryptType">
        select mobile from test_user where id = #{id}
    </select>

    <select id="queryByMobile" resultType="com.wood.system.entity.TestUser">
        select * from test_user where mobile = #{mobile}
    </select>

    <!--新增所有列-->
    <insert id="insert" keyProperty="id" useGeneratedKeys="false">
        insert into test_user(id, mobile, username, name, password, email, state, level, company_id, dept_id, create_time, update_time)
        values (#{id}, #{mobile}, #{username}, #{name}, #{password}, #{email}, #{state}, #{level}, #{companyId}, #{deptId}, #{createTime}, #{updateTime})
    </insert>

  
    <!--通過(guò)主鍵修改數(shù)據(jù)-->
    <update id="update">
        update test_user
        <set>
            <if test="mobile != null and mobile != ''">
                mobile = #{mobile},
            </if>
            <if test="username != null and username != ''">
                username = #{username},
            </if>
            <if test="name != null and name != ''">
                name = #{name},
            </if>
         
            <if test="email != null and email != ''">
                email = #{email},
            </if>
            <if test="state != null and state != ''">
                state = #{state},
            </if>
            <if test="level != null and level != ''">
                level = #{level},
            </if>
            <if test="companyId != null">
                company_id = #{companyId},
            </if>
            <if test="deptId != null">
                dept_id = #{deptId},
            </if>
          
            <if test="updateTime != null">
                update_time = #{updateTime},
            </if>
        </set>
        where id = #{id}
    </update>

</mapper>

到此這篇關(guān)于mybatis中數(shù)據(jù)加密與解密的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)mybatis數(shù)據(jù)加密與解密內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論