infotiger
infotiger

Reputation: 81

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 each of the string that makes the AL.

Is there any other approach that I can take?

Upvotes: 1

Views: 12050

Answers (6)

Shervin Asgari
Shervin Asgari

Reputation: 24517

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

Upvotes: 3

Behrang Saeedzadeh
Behrang Saeedzadeh

Reputation: 47971

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.

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240996

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

Upvotes: 6

SJuan76
SJuan76

Reputation: 24895

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.

Upvotes: 0

TrueDub
TrueDub

Reputation: 5070

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.

Upvotes: 0

fluminis
fluminis

Reputation: 4109

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

Upvotes: 0

Related Questions