Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the easiest way to persist java objects?

Right now I have java program whose classes are currently POJOs and stored in volatile memory. These need to be persisted. As I understand it two popular choices are JDO and the Java Persistence API. For someone who know little about SQL, Torque, etc, which is the easiest way to add persistence to my program's data?

like image 204
James Avatar asked Dec 23 '09 21:12

James


People also ask

How do you persist data in Java?

There are many ways to make data persist in Java, including (to name a few): JDBC, serialization, file IO, JCA, object databases, and XML databases. However, the majority of data is persisted in databases, specifically relational databases.

How do you persist an object?

You can use serialization to persist an object's data between instances, which enables you to store values and retrieve them the next time that the object is instantiated. In this walkthrough, you will create a basic Loan object and persist its data to a file.

How do you store Java objects?

In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In JAVA , when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static.


2 Answers

The traditional way to serialise to the filesystem is to use Java Serialisation. However you need to implement Serializable everywhere.

A simpler solution is to serialise to XML (and then dump to the filesystem) using XStream. You don't need to implement any interfaces, and most everything serialises and deserialises without further intervention. You can further customise the serialisation if required. The only problem I've ever had is serialising an inner class without intentionally serialising the containing outer class (this is due to the implicit this reference)

like image 149
Brian Agnew Avatar answered Sep 18 '22 13:09

Brian Agnew


Serialize the objects to the file system if you don't know SQL or relational databases.

You'll have to learn JDBC to use JDO, JPA, Hibernate, or anything else. Unless your POJOs are terribly complex I'd recommend starting there and working your way up.

Make sure you learn about normalization and proper design of indexes.

like image 27
duffymo Avatar answered Sep 21 '22 13:09

duffymo