开发者

How to store an ArrayList from Java code in MySQL?

which is a better approach

a) Store AL as BLOB

b) Create columns to store eac开发者_运维技巧h of the string that makes the AL.

Is there any other approach that I can take?


Ofcourse b

class Person{
  String name;
  int age;
  //getters setters and other stuff
}

List<Person> persons = new ArrayList<Person>();

Table

PERSON_MASTER

id | name | age

Also See

  • ORM
  • Hibernate


Avoid Serializing objects.

There are huge potential traps when it comes to serializing objects. Joshua Bloch has a complete section in Effective Java , dedicated to Serialization where he concludes that you should avoid it if possible.

So go for option B


You should go with the approach b, because:

  • In a future version of Java, the structure of the ArrayList class may change and thus you won't be able to deserialize the BLOBs back to ArrayList instances
  • In the future, you might want to use the same database with a language other than Java (e.g. C# in .NET) you can't simply deserialize the ArrayList BLOBs back to .NET lists.
  • When you store the ArrayList as the BLOB, and go to your DBMS management console, and write queries, you won't be able to see the contents of those BLOBs.

Having said that I recommend you to read an introductory book about SQL and database design as well as a theoretical book about relational algebra. This will make things much clearer to you.


You should create a table to store your list of values.

Table A : idA, col1, col2

Table B : idB, ida, rank, value

With of course a foreignkey on ida in table B


I'd say approach B. Storing the entire list in a single blob removes a lot of advantages of using a database in the first place.

If it's a list of complex objects, look at something like JPA or Hibernate to assist you with the database interactions.


Please take a quick course in DB modelling... you are refering here to a 1:N relationship, this is used storing each String as a row in a different table, with a foreign key (a reference) to the row in the original table where your object is.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜