Hi guys I would like some advice regarding data persistence, specifically storing a serialised object in a db vs storing an object's attributes in a record.
I am planning on creating a university-centric user feedback system. The program will contain user, module, lecture, lecturer and feedback objects
These map up with the fact that a user takes a module, which it leaves feedback for, a module has an owner (a lecturer) who can control an individual lecture.
I was wondering if anyone could suggest what is better periodically serialising the objects in memory to a db, or storing the main attributes of an object in db and creating a new object on each load?
Storing serialized objects is definitely not a good way to do this.
Assuming you are going to use a normal, relational database to do this, then the most common approach in Java is to use the Java Persistence API (JPA), which is the standard API for mapping objects to / from a relational database. There are different implementations of JPA available, of which Hibernate is probably the most used and well-known one.
Storing serialized objects has a number of big drawbacks. For example, you cannot use regular database tools to look at the content of the database. You'd have a column with binary data, and database tools don't show you what data the serialized objects contain. Also, you cannot take advantage of the features of the database, such as primary key and foreign key relationships on one or more of the fields of the objects, because all the fields are hidden in binary blobs of data.
Also, Java's serialization mechanism is not suitable for long-term storage of data, because it's tied too closely to the code of your classes. If you decide to change something, for example add or rename a field in a class, then you will not be able to read the previously serialized objects anymore, they will have become incompatible with the new version of your class.
1. Serializing and later deserialising objects can be troublesome if the class implementation changes between the serializing and deserialising. It's not impossible to achieve but care needs to be taken.
2. If you store individual fields to the DB then it can be used/searched by other means/programs.
3. If you want to store objects in a DB then rather than serializing them you may want to consider an object database such as http://www.java-objects-database.com (Note: I'm not recommending this DB as I've never used it, it's just an example of what is available).
posted 3 years ago
Thanks very much guys, one question: what's the benefit of using something like hibernate vs simply storing variables in a table and creating a new object on boot?
You could use the JDBC API instead of Hibernate and map rows and columns in a table to Java objects yourself, but that's a lot more cumbersome.
Hibernate does the conversion from database rows to objects and vice versa (and much more) automatically for you.