Serialize to key/value pairs using BeanUtils

1k views Asked by At

I'd like to write a Java program that takes arbitrary data and stores it in a MySQL database. The data can later be read again and the original object structure is reconstructed.

The background is that I want a generic tool for forms that need email verification in order to complete. So:

  1. User fills in form,
  2. Data is stored as mentioned above,
  3. Email is sent to the user with a link containing a certain UUID identifying the data set,
  4. User clicks the link,
  5. The servlet loads the stored data using the UUID in the link and processes the data.

I'd like this to work for any data, not only String/String or String/int pairs. I was thinking about using a LazyDynaBean from org.apache.common.beanutils as a means to pass data to my tool.

The question is: is there a nice way to serialize that stuff, even when the values are beans (let's restrict on Java Beans), and not only primitives?

I was thinking that my database tables could look like this

emailVerification
| ID | UUID | validUntil |

emailVerificationData
| ID | emailVerification.ID | name | index | key | value | className |

Is that feasable at all? Could anyone point me into the right direction on how to store and load a DynaBean into this structure? Or any alternatives that I've missed?

Thanks a bunch.

1

There are 1 answers

2
Andreas On BEST ANSWER

You could serialize-/deserialize your Beans to and from XML (s.example below) and store the String in the database.

Does this help?

    public static String beanToXMLString(final Object bean) {
    String returnvalue = null;
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    final XMLEncoder xmlEncoder = new XMLEncoder(new BufferedOutputStream(byteArrayOutputStream));
    xmlEncoder.writeObject(bean);
    xmlEncoder.close();
    returnvalue = byteArrayOutputStream.toString();
    return returnvalue;
}

public static Object beanFromXMLString(final String xml) {
    Object returnvalue = null;
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xml.getBytes());
    final XMLDecoder xmlDecoder = new XMLDecoder(new BufferedInputStream(byteArrayInputStream));
    returnvalue = xmlDecoder.readObject();
    xmlDecoder.close();
    return returnvalue;
}