AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

Mybatis自定義類型轉換,數據加密解密全攻略【實戰】

來源: 責編: 時間:2023-10-06 19:17:54 318觀看
導讀環境:springboot2.6.12 + MyBatis3.5.6 + MySQLMyBatis是一種優秀的持久層框架,它支持自定義類型轉換和數據加密解密。通過自定義類型轉換,你可以輕松地將數據庫中的數據類型轉換為Java對象中的數據類型,以及將Java對象中

環境:springboot2.6.12 + MyBatis3.5.6 + MySQLFyT28資訊網——每日最新資訊28at.com

MyBatis是一種優秀的持久層框架,它支持自定義類型轉換和數據加密解密。通過自定義類型轉換,你可以輕松地將數據庫中的數據類型轉換為Java對象中的數據類型,以及將Java對象中的數據類型轉換為數據庫中的數據類型。而數據加密解密則可以提高數據的安全性,保護敏感信息不被泄露。在MyBatis中,你可以使用類型處理器(TypeHandler)來實現自定義類型轉換,使用加密和解密算法來實現數據加密解密。FyT28資訊網——每日最新資訊28at.com

本案例使用自定義類型轉換器對數據列進行加解密FyT28資訊網——每日最新資訊28at.com

1. 依賴及相關配置

<dependencies>  <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId>  </dependency>  <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-jpa</artifactId>  </dependency>  <dependency>    <groupId>mysql</groupId>    <artifactId>mysql-connector-java</artifactId>    <scope>runtime</scope>  </dependency>  <dependency>    <groupId>org.mybatis.spring.boot</groupId>    <artifactId>mybatis-spring-boot-starter</artifactId>    <version>2.1.4</version>  </dependency>  <dependency>    <groupId>com.github.pagehelper</groupId>    <artifactId>pagehelper-spring-boot-starter</artifactId>    <version>1.3.0</version>  </dependency></dependencies>
spring:  datasource:    driverClassName: com.mysql.cj.jdbc.Driver    url: jdbc:mysql://localhost:3306/testjpa?serverTimezone=GMT%2B8    username: root    password: xxxxx    type: com.zaxxer.hikari.HikariDataSource    hikari:      minimumIdle: 10      maximumPoolSize: 200      autoCommit: true      idleTimeout: 30000      poolName: MasterDatabookHikariCP      maxLifetime: 1800000      connectionTimeout: 30000      connectionTestQuery: SELECT 1---spring:  jpa:    generateDdl: false    hibernate:      ddlAuto: update    openInView: true    show-sql: true---pagehelper:  helperDialect: mysql  reasonable: true  pageSizeZero: true  offsetAsPageNum: true  rowBoundsWithCount: true---mybatis:  type-aliases-package: com.pack.domain  mapper-locations:  - classpath:/mappers/*.xml  configuration:    lazy-loading-enabled: true    aggressive-lazy-loading: false---logging:  level:    com.pack.mapper: debug

實體對象

@Entity@Table(name = "BC_PERSON")public class Person extends BaseEntity {  private String name ;  private String idNo ;}

這里是用JPA來幫助我們生成數據表。FyT28資訊網——每日最新資訊28at.com

2. 自定義類型轉換器及數據加解密工具

public class EncryptTypeHandler implements TypeHandler<String> {  @Override  public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {    ps.setString(i, EncryptUtils.encrypt(parameter)) ;  }  @Override  public String getResult(ResultSet rs, String columnName) throws SQLException {    String value = rs.getString(columnName) ;    if (value == null || value.length() == 0) {      return null ;    }    return EncryptUtils.decrypt(value);  }  @Override  public String getResult(ResultSet rs, int columnIndex) throws SQLException {    String value = rs.getString(columnIndex) ;    if (value == null || value.length() == 0) {      return null ;    }    return EncryptUtils.decrypt(value);  }  @Override  public String getResult(CallableStatement cs, int columnIndex) throws SQLException {    String value = cs.getString(columnIndex) ;    if (value == null || value.length() == 0) {      return null ;    }    return EncryptUtils.decrypt(value);  }}

加解密工具類FyT28資訊網——每日最新資訊28at.com

public class EncryptUtils {  private static final String secretKey = "1111222244445555" ;  private static final String ALGORITHM  = "AES" ;  public static String encrypt(String data) {    try {      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding") ;      cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secretKey.getBytes(), ALGORITHM)) ;      return Hex.encode(cipher.doFinal(data.getBytes())) ;    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {      e.printStackTrace();      return null ;    }  }  public static String decrypt(String secretText) {    try {      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding") ;      cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secretKey.getBytes(), ALGORITHM)) ;      return new String(cipher.doFinal(Hex.decode(secretText))) ;    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {      e.printStackTrace();      return null ;    }  }  private static class Hex {    private static final char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };    public static byte[] decode(CharSequence s) {      int nChars = s.length();      if (nChars % 2 != 0) {        throw new IllegalArgumentException("16進制數據錯誤");      }      byte[] result = new byte[nChars / 2];      for (int i = 0; i < nChars; i += 2) {        int msb = Character.digit(s.charAt(i), 16);        int lsb = Character.digit(s.charAt(i + 1), 16);        if (msb < 0 || lsb < 0) {          throw new IllegalArgumentException("Detected a Non-hex character at " + (i + 1) + " or " + (i + 2) + " position");        }        result[i / 2] = (byte) ((msb << 4) | lsb);      }      return result;    }    public static String encode(byte[] buf) {      StringBuilder sb = new StringBuilder() ;      for (int i = 0, leng = buf.length; i < leng; i++) {        sb.append(HEX[(buf[i] & 0xF0) >>> 4]).append(HEX[buf[i] & 0x0F]) ;      }      return sb.toString() ;    }  }}

Mapper及XML文件

@Mapperpublic interface PersonMapper {  List<Person> queryPersons() ;  int insertPerson(Person person) ;}
<mapper namespace="com.pack.mapper.PersonMapper">  <resultMap type="com.pack.domain.Person" id="PersonMap">    <id column="id" property="id"/>    <result column="name" property="name"/>    <result column="id_no" property="idNo" typeHandler="com.pack.mybatis.EncryptTypeHandler"/>    <result column="create_time" property="createTime"/>  </resultMap>  <select id="queryPersons" resultMap="PersonMap">    SELECT * FROM bc_person  </select>  <insert id="insertPerson" parameterType="com.pack.domain.Person">    insert into bc_person (id, name, id_no, create_time) values (#{id}, #{name}, #{idNo, typeHandler=com.pack.mybatis.EncryptTypeHandler}, #{createTime})  </insert></mapper>

查詢數據時在resultMap中的result中配置typeHandler="com.pack.mybatis.EncryptTypeHandler",指明該列的類型轉換。FyT28資訊網——每日最新資訊28at.com

在insert中對具體的列進行指明類型轉換。FyT28資訊網——每日最新資訊28at.com

3. 測試

@RunWith(SpringRunner.class)@SpringBootTestpublic class SpringBootComprehensiveApplicationTests {  @Resource  private PersonMapper personMapper ;  @Test  public void testInsertMapper() {    com.pack.domain.Person person = new com.pack.domain.Person() ;    person.setId("0001") ;    person.setCreateTime(new Date()) ;    person.setIdNo("111111") ;    person.setName("中國") ;    personMapper.insertPerson(person) ;  }  @Test  public void testQueryUers() {    System.out.println(personMapper.queryPersons()) ;  }}

圖片圖片FyT28資訊網——每日最新資訊28at.com

FyT28資訊網——每日最新資訊28at.com

插入數據時數據已經被我們自定義的類型轉換器進行了加密處理。FyT28資訊網——每日最新資訊28at.com

圖片圖片FyT28資訊網——每日最新資訊28at.com

查詢數據進行了解密處理。FyT28資訊網——每日最新資訊28at.com

完畢!!!FyT28資訊網——每日最新資訊28at.com

本文鏈接:http://www.tebozhan.com/showinfo-26-12115-0.htmlMybatis自定義類型轉換,數據加密解密全攻略【實戰】

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 微軟為 VS Code 正式推出 C# 開發套件

下一篇: 尤雨溪:Vite 的現狀與未來展望

標簽:
  • 熱門焦點
  • 線程通訊的三種方法!通俗易懂

    線程通信是指多個線程之間通過某種機制進行協調和交互,例如,線程等待和通知機制就是線程通訊的主要手段之一。 在 Java 中,線程等待和通知的實現手段有以下幾種方式:Object 類下
  • 一文掌握 Golang 模糊測試(Fuzz Testing)

    模糊測試(Fuzz Testing)模糊測試(Fuzz Testing)是通過向目標系統提供非預期的輸入并監視異常結果來發現軟件漏洞的方法。可以用來發現應用程序、操作系統和網絡協議等中的漏洞或
  • 三分鐘白話RocketMQ系列—— 如何發送消息

    我們知道RocketMQ主要分為消息 生產、存儲(消息堆積)、消費 三大塊領域。那接下來,我們白話一下,RocketMQ是如何發送消息的,揭秘消息生產全過程。注意,如果白話中不小心提到相關代
  • JVM優化:實戰OutOfMemoryError異常

    一、Java堆溢出堆內存中主要存放對象、數組等,只要不斷地創建這些對象,并且保證 GC Roots 到對象之間有可達路徑來避免垃 圾收集回收機制清除這些對象,當這些對象所占空間超過
  • 東方甄選單飛:有些鳥注定是關不住的

    文/彭寬鴻編輯/羅卿東方甄選創始人俞敏洪帶隊的&ldquo;7天甘肅行&rdquo;直播活動已在近日順利收官。成立后一年多時間里,東方甄選要脫離抖音自立門戶的傳聞不絕于耳,&ldquo;7
  • 國行版三星Galaxy Z Fold5/Z Flip5發布 售價7499元起

    2023年8月3日,三星電子舉行Galaxy新品中國發布會,正式在國內推出了新一代折疊屏智能手機三星Galaxy Z Fold5與Galaxy Z Flip5,以及三星Galaxy Tab S9
  • 三星Galaxy Z Fold5官方渲染圖曝光:13.4mm折疊厚度依舊感人

    據官方此前宣布,三星將于7月26日在韓國首爾舉辦Unpacked活動,屆時將帶來帶來包括Galaxy Buds 3、Galaxy Watch 6、Galaxy Tab S9、Galaxy Z Flip 5、
  • 聯想YOGA 16s 2022筆記本將要推出,屏幕支持觸控功能

    聯想此前宣布,將于11月2日19:30召開聯想秋季輕薄新品發布會,推出聯想 YOGA 16s 2022 筆記本等新品。官方稱,YOGA 16s 2022 筆記本將搭載 16 英寸屏幕,并且是一
  • 電博會與軟博會實現"線下+云端"的雙線融合

    在本次“電博會”與“軟博會”雙展會利好條件的加持下,既可以發揮展會拉動人流、信息流、資金流實現快速交互流動的作用,繼而推動區域經濟良性發展;又可以聚
Top