Question

silly qeustion: I wonder if it is possible to persist POJOs with JDBC like it is possible with JPA?

Lets say I have the class "A" that contains one field

public class A implements Serializable{

    public String someString = "asd";
}

Now let's say I have an Instance of A (A myA = new A(); ).

My question is: Is it possible to persist "myA" with JDBC or do I have to persist the String. Or when I want to load "myA" can I load the instance "myA" or do I have to build up "myA" by loading the String and create a new instance form A with that loaded String.

Was it helpful?

Solution

You can store serialized Java objects to a database; e.g. by using a Blob type.

But it is not generally a good idea:

  • It is is impractical to perform an SQL query that tests the state of a serialized object in any non-trivial way.

  • Serialized objects tend to be sensitive to changes in the object's code. Dealing with this can be awkward, and not dealing with it can leave you with serialized objects in your database that you can't deserialize any more.

If you want to persist POJOs to relational database, you would be better off using an object-relational mapping, such as JPA or Hibernate.

OTHER TIPS

You gonna have to do the maping in some way (before persist and on retrieve ).

One way is to create method that I like to call the fillX where you could do the mapping manually(java code) or create some kind of convention like name in class with column in DB.

This is well done in Spring JDBC for example. In the docs you can see who does what.

In most cases using Object Relational Mapping like JPA would be the way to go but that is not always an option.

In general you can persist a byte Stream with JDBC. In this case you should work with BLOB (if its a textual stream, then work with CLOB).

So if your class A really implements Serializable interface you may serialize it into bytestream and store.

However, I would still suggest you to store strings instead. This is due to the fact that the work with BLOB/CLOB is considerably slower than with Strings.

Hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top