views:

261

answers:

3

I have a Java class with a property like this

private Object myObj;

When I try to save the class using Hibernate annotations, I get the rather confusing error message "property mapping has wrong number of columns".

What is the correct approach to persisting a class containing a generic property such as this?

A: 

Don't use a generic Object attribute if you can help it. My first brush with Hibernate meant inheriting a project with oodles of things like this, and it was a world of pain. As Zoidberg says, using Object means that your model isn't easily serialised / versioned (an understatement if I'm honest).

Ben Poole
+1  A: 

As you said, the object can be image, video, and more.

If it is supposed to have only binary data, you can create another class, and transfer the data from this one. In the process of transferring you can convert the Object to byte[] (depending on the concrete type), and use a Lob data type (@Lob) for mapping it.

To extend this, if not only binary data is to be supported, your new object can have 2 fields - one in case of binary, and one (or more) in case of other types.

Anyway, the object as it is now, represents a quite unintelligent design, and it cannot be persisted properly without hassle.

Bozho
A: 

Change the type of your property:

private byte[] myObj;

This worked for me with Fluent NHibernate (albeit in C#) and an SQL field type of varbinary(max).

You can then expose this as an image, video, or whatever. An example of converting to an image in Java:

ImageIO.read(new ByteArrayInputStream(myObj));
RaceFace