How Can I Insert/Retrive A Java Object Into/From Sql Server? THX
-
5Just a suggestion: if you spend more time writing a good question, you'll tend to find people are more willing to spend time answering it.butterchicken– butterchicken2009-07-16 09:11:02 +00:00Commented Jul 16, 2009 at 9:11
-
1Right, especially when typing the same question in Google gives you the answer =)Clement Herreman– Clement Herreman2009-07-16 09:13:33 +00:00Commented Jul 16, 2009 at 9:13
-
This might be a newbie question, but it's programming related. Just because the answer is on Google doesn't mean the answer can't be here, too.Clay– Clay2009-07-16 15:19:54 +00:00Commented Jul 16, 2009 at 15:19
7 Answers
You can't just insert the object "as is" in the DB. You need to serialize it, you can either do it yourself, or implement the Serializable interface (cf here )
Comments
Serialize it to, lets say, ByteArrayOutputStream and those bytes insert into table's column of type BLOB. You will have to use PreparedStatement to be sure bytes went up regularly.
If serialization is not feasible because you have in your object reference to some other object which cannot be serialized, than that is another story, you will have to cope with your own serialization implementation or see if something can be declared transient. Maybe you can google for JSON or something similar to see if that suits your needs.
Comments
There are many ways to store a Java object into a database. If you want literally store the object instance in a database so that you can retrieve it later exactly as it was, you can serialize it and store the serialized bytes to a column in one of your database tables.
More than likely, you will want to be able to query the database for the individual properties of your object. For this, you will need to break the object up into pieces and save it to a table in multiple columns using JDBC. There are many persistence frameworks that do Object-Relational Mapping (ORM) for you such as Hibernate and iBatis.