Reputation: 26627
I'm working on a J2SE desktop application with some POJO classes which represent data and one-to-many/many-to-many relations between them using ArrayLists. I'm not using an ORM, just managing the data using Collections and using Java's PropertyChangeListener to fire model events to keep models decoupled (coming from a Python background, the amount of repetition and boilerplate required with the DAO pattern seems insane to write and maintain).
So to save files in this application I initially used serialisation. This was of course a terrible decision, because updates to the domain objects of the software broke backwards compatibility with previously saved files.
I then decided to move to JAX-B, but looking at this fictitious output:
<Person>
<Todo>
<title>Task 1</title>
</Todo>
</Person>
<Category>
<title>Category 1</title>
<Todo>
<title>Task 1</title>
</Todo>
</Category>
I now have no means of finding out that the Todo
from the Person is the same as the Todo from the Category. I suppose I could add an id
field and keep track of the maximum id as a static variable on my model, but that seems like a lot of boilerplate and work to populate Collections by searching by ID.
Are there standard approaches to these kinds of problems, and what are the most widely solutions in the Java community.
Upvotes: 1
Views: 106
Reputation: 80603
There's no 'standard' way of doing this. But an option you might want to consider is serializing your objects as JSON. You could then store the JSON into a file, or into a small key-value store like Redis. Some of the advantages of JSON?
And some JSON libraries (like Jackson 2+) can track object identity, making data repetition a non factor.
Upvotes: 1
Reputation: 51515
You could add 3 lines to the XML to define the relationships.
<Person>
<title>Person 1</title>
<Todo>
<title>Task 1
<category>Category 1</category
</title>
</Todo>
</Person>
<Category>
<title>Category 1</title>
<Todo>
<title>Task 1
<person>Person 1</person>
</title>
</Todo>
</Category>
Upvotes: 0