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

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

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

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

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

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

本案例使用自定義類型轉換器對數據列進行加解密9bC28資訊網——每日最新資訊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來幫助我們生成數據表。9bC28資訊網——每日最新資訊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);  }}

加解密工具類9bC28資訊網——每日最新資訊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",指明該列的類型轉換。9bC28資訊網——每日最新資訊28at.com

在insert中對具體的列進行指明類型轉換。9bC28資訊網——每日最新資訊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()) ;  }}

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

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

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

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

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

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

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

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

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

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

標簽:
  • 熱門焦點
  • JavaScript 混淆及反混淆代碼工具

    介紹在我們開始學習反混淆之前,我們首先要了解一下代碼混淆。如果不了解代碼是如何混淆的,我們可能無法成功對代碼進行反混淆,尤其是使用自定義混淆器對其進行混淆時。什么是混
  • .NET 程序的 GDI 句柄泄露的再反思

    一、背景1. 講故事上個月我寫過一篇 如何洞察 C# 程序的 GDI 句柄泄露 文章,當時用的是 GDIView + WinDbg 把問題搞定,前者用來定位泄露資源,后者用來定位泄露代碼,后面有朋友反
  • 一個注解實現接口冪等,這樣才優雅!

    場景碼猿慢病云管理系統中其實高并發的場景不是很多,沒有必要每個接口都去考慮并發高的場景,比如添加住院患者的這個接口,具體的業務代碼就不貼了,業務偽代碼如下:圖片上述代碼有
  • 使用AIGC工具提升安全工作效率

    在日常工作中,安全人員可能會涉及各種各樣的安全任務,包括但不限于:開發某些安全工具的插件,滿足自己特定的安全需求;自定義github搜索工具,快速查找所需的安全資料、漏洞poc、exp
  • 2天漲粉255萬,又一賽道在抖音爆火

    來源:運營研究社作者 | 張知白編輯 | 楊佩汶設計 | 晏談夢潔這個暑期,旅游賽道徹底火了:有的「地方」火了&mdash;&mdash;貴州村超旅游收入 1 個月超過 12 億;有的「博主」火了&m
  • iQOO 11S屏幕細節公布:首發三星2K E6全感屏 安卓最好的直屏手機

    日前iQOO手機官方宣布,新一代電競旗艦iQOO 11S將會在7月4日19:00正式與大家見面。隨著發布時間的日益臨近,官方關于該機的預熱也更加密集,截至目前已
  • 首發天璣9200+ iQOO Neo8系列發布首銷售價2299元起

    2023年5月23日晚,iQOO Neo8系列正式發布。其中,Neo系列首款Pro之作——iQOO Neo8 Pro強悍登場,限時售價3099元起;價位段最強性能手機iQOO Neo8同期上市
  • iQOO Neo8系列新品發布會

    旗艦雙芯 更強更Pro
  • Windows 11發布,微軟一改往常對老機型開放的態度

    距離 Windows 11 發布已經過去一周,在過去一周里,很多數碼愛好者圍繞其對 Android 應用的支持、對老機型的升級問題展開了激烈討論。與以往不同的是,在這次大
Top