I want to be able to store any Serializable object in a database against a unique ID. So I created a Java object that has a constructor taking those 2 values. The constructor converts the Serializable into bytes and then splits these into chunks of 4096 characters. These bytes are stored in a List in the object. So the object looks like:
public class MyObj {
private String id;
private List<byte[]> serData;
public MyObj(String id, Serializable value) {
this.id = id;
this.serData = convertSerializableToByteArray(value);
}
}
I want to store this into a database table but I want the database table to have 3 columns:
ID
line_no
serialized_data (4096 bytes max)
The primary key of the table should be the ID and line_no combined. As an example, to store an object of ID ‘foo’ to a 10,000 character string, I would expect the database to have the following entries:
I am having a lot of trouble creating either an hbm file for this or using Annotations. Can anyone help me out? Is this approach even possible? This is the hbm file I have so far (I am aware that this doesn’t work):
Let us assume that the Java Object and the database table must remain exactly as they are (they are part of a much bigger project). Can a hibernate mapping be created which would perform the mapping I want ?
I fear that I am not explaining myself properly. As you can see from my example there is no line-number in the Java code. I simply have 2 Java objects and wish to map these to 3 columns, using the index of the List as one of the columns.
The mappings I have tried do not work - the example I provided isn’t accepted and I don’t know how to express what I want in either an hbm form or Annotation form. That is what I am looking for.
I abandoned using an hbm file and added Annotations to the class. I added the annotation @ ElementCollection to the List and got it to refer to the same table as the class (is this recommended???) :
@Table(name="myobj_ser")
public class MyObj {
@Id
@Column(name="id", nullable=false)
private String id;
@ElementCollection
@CollectionTable(name="myobj_ser")
private List<byte[]> serData = new ArrayList<>();
This resulted in a table with 3 columns:
id
MyObj_id
serData
Can you advise as to how I can annotate to get the correct columns?
It sort-of worked. Your example created a table with 4 columns which were:
id
myobj_id
line_no
serialized_data
I tried to work round this and put a joinColumns of "@ JoinColumn(name = “id”)) ". This meant that only 3 columns were created. However when my application started it threw a Foreign Key exception (although it still created the table). I was unable to work around this.
Ultimately I have abandoned my initial approach. The Object “MyObj” has no annotations and simply wrappers the “SerData” object, as you supplied. This is then persisted to the database and I have to ensure that updates, deletions, etc. work on the appropriate object.