开发者

Java, what is a straightforward, simple method for persisting an object? Do all methods require serialization?

I am new to doing this so开发者_如何学运维rt of thing but I would like to figure a simple method for persisting a Java object that will contains a sashMap and also lists. I have been researching this and believe I can serialize this and save to a regular DB, such as through hibernate, but am not quite clear on this, even after reading numerous tutorials as I am not sure if a regular list is serializable. I don't expect a full answer on how to do this but rather I am wondering what is generally considered the best way to do this with the least unnecessary complexity as I am open to using a different database setup than I am currently using (hibernate with MySQL)

I have looked at an option like Mongo DB but am also a bit confused as far as whether I would need to serialize the object before saving to Mongo db. I have been reading a lot of documentation but want to make sure I choose the simplest way to do this that is still reliable and am open to suggestions any advice would be appreciated. The object that I would be persisting would be something like below (although more complex / nested)

public class TestClass {

    public Map <Integer, Map> primaryHolder = new HashMap <Integer, Map>;

    public addRecord (Integer key, Map inputMap<Integer, List>) {
        primaryHolder.add(key, inputMap);
    }

}

Thanks for any advice


Unfortunately, "simple" and "straightforward" doesn't mix well with "SQL" or "database" in general. Java collection types just don't map easily to sets or documents.

The "correct" solution (as far as SQL is concerned) is to create a table for the list elements, then a table for the inner map (Integer -> List) and one for the outer map.

If your structure contains more than a couple of elements, you're not going to like the performance of this.

So the other solution is a BLOB column and the Serializable interface. This has other issues like:

  • You always have to load the whole structure
  • all elements in the structure must be serializable
  • if you can't load one piece, you can't load anything, etc).
  • If you want to add objects to the structure which are mapped to tables via Hibernate, you need some hacks to convert the instance to its primary key and back during save and load.

You should consider an OO database like db4o which can save any Java object but you will need a different mindset when you write your code: Suddenly, you will need to think about things like running db4o queries on Java collections.


Whenever your persisting a object into DB, you need to Serialize that object.


Look at object databases like NeoDatis or db4o. They offer pretty straightforward way to persist objects.

Personally I have used NeoDatis and I didnt need to implement Serializable interface or anything similar.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜