【问题标题】:Wrong encoding when read blob to string using Hibernate 4 and MySQL使用 Hibernate 4 和 MySQL 将 blob 读取为字符串时编码错误
【发布时间】:2017-12-17 04:38:03
【问题描述】:

我有一个带有字段的实体:

@Column
String shortVarcharField;

@Column(columnDefinition = "BLOB", length = 65534)
private String veryLongStringInBlob;

当我将此实体存储到数据库并使用 MySQL-CLI 观看时,我在那里看到正常的 UTF。但是当我用 Hibrnate 读取它时,它读取的是 �� 而不是普通的 unicode。

那么,我应该如何更改我的实体以正常地将长字符串映射到 blob?

【问题讨论】:

    标签: java mysql hibernate blob


    【解决方案1】:

    在可验证之前在实体中使用@Lob 注释。 @Lob 用于 blob 和 clob 的技巧(使用 String 作为类型)。您可以参考下面的参考代码。

    @Column( name = "FILEIMAGE" )
    @Lob(type = LobType.BLOB)
    private byte[] fileimage;
    

    你也可以使用下面的代码:

    @Column(name="content")
    @Lob
    private Blob content;
    

    【讨论】:

    • 不幸的是,它没有帮助
    【解决方案2】:

    解决方法很简单:

    @Column
    String shortVarcharField;
    
    @Column(columnDefinition = "BLOB", length = 65534)
    private byte[] veryLongStringInBlob;
    
    public String getVeryLongStringInBlob(){
      return new String(veryLongStringInBlob);
    }
    
    public void setVeryLongStringInBlob(String value){
      this.setVeryLongStringInBlob = value.getBytes();
    }
    

    【讨论】:

      【解决方案3】:

      您需要将该 BLOB 列读取为 byte[] 并使用 UTF-8 字符集从该 byte[] 构造一个字符串,类似于您的模型中的以下内容

      @Lob 
      @Basic(fetch = FetchType.EAGER) 
      @Column(name="YOURCOLUMN", columnDefinition="BLOB", nullable = true)
      private byte[] info;
      
      
      public String getInfo() {
          try {
              return (new String(info,"UTF-8"));
          } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
              return "";
          }
      }
      
      public void setInfo(byte[] info) {
          this.info = info;
      }
      

      【讨论】:

        猜你喜欢
        • 2013-12-06
        • 1970-01-01
        • 1970-01-01
        • 2020-04-19
        • 2018-01-03
        • 2018-04-19
        • 2015-02-22
        • 2020-08-16
        • 2015-03-01
        相关资源
        最近更新 更多