How would I go about persisting an object that has a java.util.Properties
object in it?
Note that a java.util.Properties
object has the ability to lookup properties not only in itself, but also in a default properties list. The default properties list is itself another Properties
object, so it too can have another default properties list. Looking up a single property could traverse multiple Properties
objects before the property is found.
The application I'm building needs override-able properties in a hierarchical manner like Properties
provides, so I was thinking of using Properties
instead of implementing my own data structure. But I'm confused on how I would persist them.
not sure if it's a "piece of pie" thing, but since you can store the XML from a Properties instance and load an instance from an XML therefore you could have a @Lob property on your entity holding the XML that will be persisted. Something like:
class MyEntity implements Serializable {
@Transient
Properties props;
@Lob
byte[] xmlProp; //the xml as a byte[]
//ids, getters & setters ommited
}
And then you can implement a DAO to do the hard work of persisting and retrieving your entity:
class MyEntityDAO {
public void persist(MyEntity entity){
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
entity.getProps().storeToXML(bos, "a simple comment if you like");
byte[] byteStream = bos.toByteArray();
entity.setXmlProp = byteStream;
//save your instance with hibernate...
} catch (IOException e) {
e.printStackTrace();
}
}
public MyEntity retrieveById(Long id){
Properties propFromDB = new Properties();
MyEntity ent = //retrieve the instance with hibernate...
try{
Properties propFromDB = new Properties();
ByteArrayInputStream bais = new ByteArrayInputStream(ent.getXmlProp());
propFromDB.load(bais);
ent.setProp(propFromDB);
return ent;
} catch (IOException ioe){
ioe.printStackTrace();
}
return null;
}
}
Check methods storeToXML and loadFromXML at the java.util.Properties API.
Hope this helps;
The first questions is - do you need to store the hierarchy metadata, or you just want to store all properties. If it's the letter case, then simply add all the properties (using getPropertyNames()
) to a Map
end persist it (persisting maps is nearly trivial)
If you want to retain the hierarchy, then a question to ask is - how should this be represented in the database.
The simplest way I imagine is to have one table with the following columns:
id | key | value | properties_set_id | parent_properties_set_id
But how to do that - I can't think of immediately. Perhaps persist a Set<PropertyEntry>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With