Re: Auto serialize/unserialize on JPA
On Nov 29, 11:24 am, guigouz <guig...@gmail.com> wrote:
On Nov 27, 3:19 am, Owen Jacobson <angrybald...@gmail.com> wrote:
On Nov 26, 10:23 am, guigouz <guig...@gmail.com> wrote:
Hi, I'm trying to build an entity class that has another class as a
field, but I don't want to generate a relationship between them.
Instead i wanted to serialize the contents of the child class as a
String to store on the database. Is it possible ?
Yes, but it sucks. Serialized objects are all but useless if the
associated class files ever change in certain ways, whereas the
mapping between a table and the supporting entity class is flexible.
Table data can also be queried and examined by tools written in other
languages, or manually.
If you're dead set on doing this, look at the @Lob annotation ("Large
Object"). It should allow the data to be mapped into a binary large
object type for your database (BLOB, BYTEA, whatever).
I was thinking about a custom serialization thing. To XML or something
like that (custom properties file, etc)
You're into vendor-specific extensions, if you want it to happen
"automatically". On the other hand, I've had good luck with a pattern
like this for mapping enums to non-obvious values, which you could
probably bend into something like what you want.
public enum Type {
FOO (33), BAR (23);
public final int value;
private Type (int value) { this.value = value; }
public static Type getByValue (int value) {
for (Type t : getValues ())
if (t.value == value)
return t;
return null;
}
}
@Entity
public class HasAFoo implements Serializable {
@Id private int id;
@Basic private int typeId;
/* Public c'tor, get/set for id, _NO_ get/set for typeId */
@Transient
public Type getType () { return Type.getByValue (typeId); }
public void setType (Type type) { typeId = type.value; }
}
The entity itself is responsible for converting between the external
representation of a property and the internal/column representation.
There's nothing preventing you from mapping a single logical property
to many columns, or to an XML document in a TEXT or VARCHAR(*) column
this way.
HTH,
-O