Author | Message |
---|---|
dguhath
Posts: 61
|
Posted 00:19 Feb 13, 2015 |
Hello Dr. Sun, Could you please help me understand how hibernate works in the case of @CollectionTable types? I am not clear on how hibernate identifies the column types of the collection table specially when the collection type doesn't have any entity associated with it. I was referring to the "question_choices" table and it is only mentioned in the following code in csns also it didn't map to any entity. @ElementCollection(fetch = FetchType.EAGER) So how does hibernate identify question_id & choice_index as a primary key & how does it understand about the data types of choice_index & choice columns? Am I missing something here? Could we have created a QuestionChoice entity in this case? Thannks. |
cysun
Posts: 2935
|
Posted 10:58 Feb 13, 2015 |
The type of the choice column is the type of the elements in the collection, i.e. List<String>, and the default SQL type for String is varchar(255). The default type for choice_index is integer as it is an @OrderColumn - as the name says, it's a column used to keep track of the order of the elements in the collection, so of course it's an integer. Given a question and the index of a choice in the question, we can uniquely identify a choice. This is why the combination of (question_id, choice_index) is the primary key of the collection table. |
dguhath
Posts: 61
|
Posted 12:20 Feb 13, 2015 |
Thanks Dr. Sun, I do understand the fact why (question_id, choice_index) is the primary key. What i am not able to understand is that how hibernate understands that it should be the primary key and generates the create statements. Why does it not think (question_id, choice) is the primary key. Is it because we declare a @OrderColumn and as a rule it will always be a part of the primary key along with the foreign key? Also i noted for another such scenario for the "answer_selections" table where we don't have any primary key mentioned. Is it because in case of @ElementCollection the primary key is only formed if there is a @OrderColumn?
|
cysun
Posts: 2935
|
Posted 13:00 Feb 13, 2015 |
Two choices may have the same value. For example, I could create a question that says "what are the 3 most important things in real estate", and the choices would be:
This is why (question_id, choice_index) is the primary key but (question_id, choice) is not. Hibernate will generate a primary key when you have an @OrderColumn. Strictly speaking it should generate one for Set as well (like ChoiceAnswer.selections), but I guess in JPA a List with @OrderBy and a Set are pretty much the same, so Hibernate doesn't generate primary key constraint for answer_selections, but you can add one if you want. |
dguhath
Posts: 61
|
Posted 13:53 Feb 13, 2015 |
Thanks Dr. Sun. That helps. I might bother you with further questions if and when i have them. |