convert String to Clob and vice versa in Hibernate

后端 未结 3 1891
北海茫月
北海茫月 2021-01-05 04:30

Suppose that I have a Class:

class EventTransaction {
    .....
    private Clob dataXML;

    public Clob getDataXML() {
       return dataXML;
    }

    p         


        
相关标签:
3条回答
  • 2021-01-05 04:35

    Do this

    @Column(name='xml')
    @Lob
    private String dataXML;
    
    public String getDataXML() {
       return dataXML;
    }
    
    public void setDataXML(String dataXML) {
       this.dataXML = dataXML;
    }
    

    So there is no need to convert, and everything is done by Hibernate.

    I showed it using annotations, the same thing can be done using .hbm.xml files.

    0 讨论(0)
  • 2021-01-05 04:47

    Here is code I made a long time ago to convert a Clob to a String. It's meant to be used in a utility class.

        public static String convertClobToString(Clob clob) throws IOException, SQLException {
                Reader reader = clob.getCharacterStream();
                int c = -1;
                StringBuilder sb = new StringBuilder();
                while((c = reader.read()) != -1) {
                     sb.append(((char)c));
                }
    
                return sb.toString();
         }
    

    And if I am not mistaken, to create a Clob you would do something like this

         Clob myClobFile = new SerialClob("my string".toCharArray());
    
    0 讨论(0)
  • 2021-01-05 04:51

    The limitation of 64000 characters is on the database side when you declare the XML column as VARCHAR (and not on Java String), so as long as your column XML is a CLOB, it should work.

    Excerpt from working code:

    Entity:

    private String xml;
    

    SQL (ORACLE):

    XML       CLOB,
    

    Hibernate mapping:

    <property name="xml" type="java.lang.String">
        <column name="XML" length="999999" />
    </property>
    

    If you want to store the XML as a file, then you should rather use BLOBs as shown below :

    Entity:

    private byte[] xmlFile;
    

    SQL (ORACLE):

    XML       BLOB,
    

    Hibernate mapping:

    <property name="xmlFile" type="java.io.File">
        <column name="XML" />
    </property>
    
    0 讨论(0)
提交回复
热议问题