Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORMLite custom data persister with multiple columns

Say I have a class called Person which is normally persisted into a db table using ORMLite.

Now, I have a member inside that Person class called House. The House class contains 3 properties and is NEVER stored into the database.

What I want is whenever Person is persisted I want to store the 3 fields of House into the Person table into 3 different columns.

So the Person table will have : { person_name, person_contact, house_address, house_type, house_date }.

The last 3 fields will come in from House object.

I think I should be using a DataPersister on the House member variable but does this mean it will write the entire House object into ONE column? I want to split it into 3 columns inside the Person table. Can someone help?

Thanks!

like image 460
dnkoutso Avatar asked Oct 21 '11 17:10

dnkoutso


3 Answers

Actually a perfect workaround for Serializable objects this could be:

@DatabaseField (dataType = DataType.SERIALIZABLE) 
public Person person;

As a result Person stored in a single column as usual primitive variable.

like image 155
Roman Minenok Avatar answered Nov 15 '22 11:11

Roman Minenok


What you are asking for is called embedded objects. All of the fields in the sub-object are stored in the parent object.

Sorry, but right now (12/2012) ORMLite does not support embedded objects. It is on the TODO list but no plans are in the way for it. As @user999717 mentioned, we do support foreign objects that can be automatically refreshed. This allows you to store the House object in another table and ORMLite will query for it when you pull out a Person. Here are the docs for it:

http://ormlite.com/docs/foreign

like image 34
Gray Avatar answered Nov 15 '22 12:11

Gray


You could use this:

@DatabaseField (useGetSet = true)
private String personStr; // Dummy

public Person person;
public String getPersonStr(){ person.toString(); }
public void setPersonStr(String personstr){ person = Person(personstr); }

Too bad the following doesn't work and you need the extra dummy field:

@DatabaseField (dataType = DataType.String, useGetSet = true) 
public Person person;
public String getPerson(){ person.toString(); }
public void setPerson(String personstr){ person = Person(personstr); }

You could also use dataType = DataType.SERIALIZABLE as stated in other answers BUT using custom serialization, which means actually implementing Serializable and handle all possible serialization versions when reading. Default serialization should NOT be used as u'll end up with messed up DB.

like image 21
Markos Evlogimenos Avatar answered Nov 15 '22 12:11

Markos Evlogimenos