Homemade vs. Java Serialization

前端 未结 14 746
离开以前
离开以前 2021-02-04 06:16

I have a certain POJO which needs to be persisted on a database, current design specifies its field as a single string column, and adding additional fields to the table is not a

14条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-04 06:49

    Consider putting the data in a Properties object and use its load()/store() serialization. That's a text-based technique so it's still readable in the database:

    public String getFieldsAsString() {
      Properties data = new Properties();
      data.setProperty( "foo", this.getFoo() );
      data.setProperty( "bar", this.getBar() );
      ...
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      data.store( out, "" );
      return new String( out.toByteArray(), "8859-1" );   //store() always uses this encoding
    }
    

    To load from string, do similar using a new Properties object and load() the data.

    This is better than Java serialization because it's very readable and compact.

    If you need support for different data types (i.e. not just String), use BeanUtils to convert each field to and from a string representation.

提交回复
热议问题