views:

144

answers:

1

table A and B need to have 1:M relationship

a and b are added during application runtime, so A created, then say 4 B's created. Each B instance has to come in order, so that I could later extract them in the same order as I added them.

The app will be a web-app running on Tomcat, so 10 instances may work simultaneously.

So my question are:

1) How to preserve inserting order, so that I could extract B instances that A references in the same order as I persisted them. That's tricky, because we add to a Collection and then it gets saved (am I right?). So, it depends on how Hibernate saves it, what if it changes the order in what we added instances? I've seen something like LIST instead of SET when describing relationships, is that what I need?

2) How to add a 3-rd column to B so that I could differentiate the instances, something like SEX(M,F,U) in B table. Do I need a special table, or there's and easy way to describe constants in Hibernate. What do you recommend?

3) Talking about concurrency, what methods do you recommend to use? There should be no collisions in the db and as you see, there might easily be some if rows are not inserted (PK added) right where it is invoked without delays ?

+3  A: 

How to preserve inserting order, so that I could extract B instances that A references in the same order as I persisted them. (...)

Use an ordered collection like a List. Note that Lists can be mapped in two different ways:

  • as ordered lists, the order is not materialized in the database
  • as indexed lists, the order is materialized in the database

Refer to the section 2.2.5.3.4. Indexed collections (List, Map) for the details.

How to add a 3-rd column to B so that I could differentiate the instances, something like SEX(M,F,U) in B table. Do I need a special table, or there's and easy way to describe constants in Hibernate. What do you recommend?

Use an enum on B and map with @Enumerated. See this previous answer.

Talking about concurrency, what methods do you recommend to use? There should be no collisions in the db and as you see, there might easily be some if rows are not inserted (PK added) right where it is invoked without delays ?

Hmm... Use transactions and the locking strategy that suits your needs (but to be honest, I'm not sure I understood the question).

Pascal Thivent
@Pascal Thivent Thanks for answering, as always professionally. Third question implied situation when a PK is not returned simultaneously, so object is not saved on method invokation, I thought it may arise problems. But sincerely speaking, first two questions are more important.
EugeneP
@EugeneP You're welcome. Regarding question #3, I'm sorry but I still don't understand your concern. Maybe if you clarify the exact scenario you have in mind, I could elaborate.
Pascal Thivent