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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

標簽:
  • 熱門焦點
  • Redmi Pad評測:紅米充滿野心的一次嘗試

    從Note系列到K系列,從藍牙耳機到筆記本電腦,紅米不知不覺之間也已經形成了自己頗有競爭力的產品體系,在中端和次旗艦市場上甚至要比小米新機的表現來得更好,正所謂“大丈夫生居
  • 0糖0卡0脂 旭日森林仙草烏龍茶優惠:15瓶到手29元

    旭日森林無糖仙草烏龍茶510ml*15瓶平時要賣為79.9元,今日下單領取50元優惠券,到手價為29.9元。產品規格:0糖0卡0脂,添加草本仙草汁,清涼爽口,富含茶多酚,保留
  • 線程通訊的三種方法!通俗易懂

    線程通信是指多個線程之間通過某種機制進行協調和交互,例如,線程等待和通知機制就是線程通訊的主要手段之一。 在 Java 中,線程等待和通知的實現手段有以下幾種方式:Object 類下
  • 把LangChain跑起來的三個方法

    使用LangChain開發LLM應用時,需要機器進行GLM部署,好多同學第一步就被勸退了,那么如何繞過這個步驟先學習LLM模型的應用,對Langchain進行快速上手?本片講解3個把LangChain跑起來
  • K8S | Service服務發現

    一、背景在微服務架構中,這里以開發環境「Dev」為基礎來描述,在K8S集群中通常會開放:路由網關、注冊中心、配置中心等相關服務,可以被集群外部訪問;圖片對于測試「Tes」環境或者
  • 得物效率前端微應用推進過程與思考

    一、背景效率工程隨著業務的發展,組織規模的擴大,越來越多的企業開始意識到協作效率對于企業團隊的重要性,甚至是決定其在某個行業競爭中突圍的關鍵,是企業長久生存的根本。得物
  • 破圈是B站頭上的緊箍咒

    來源 | 光子星球撰文 | 吳坤諺編輯 | 吳先之每年的暑期檔都少不了瞄準追劇女孩們的古偶劇集,2021年有優酷的《山河令》,2022年有愛奇藝的《蒼蘭訣》,今年卻輪到小破站抓住了追
  • 小米汽車電池信息疑似曝光:容量101kWh,支持800V高壓快充

    7月14日消息,今日一名博主在社交媒體發布了一張疑似小米汽車電池信息的照片,顯示該電池包正是寧德時代麒麟電池,容量為101kWh,電壓為726.7V,可以預測小
  • 2納米決戰2025

    集微網報道 從三強爭霸到四雄逐鹿,2nm的廝殺聲已然隱約傳來。無論是老牌勁旅臺積電、三星,還是誓言重回先進制程領先地位的英特爾,甚至初成立不久的新
Top