Reputation: 4351
I have two entities, Author
and Book
, connected with a one-to-many relationship. What's the difference between specifying field type as Collection<Book>
and List<Book>
? Aforementioned scenario is presented below:
@Entity
public class Author {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "author")
private Collection<Book> books = new ArrayList<>(); // List<Book> instead?
}
The only difference I have already noticed is that when I want to use @OrderColumn
annotation I need to use List
, but are there any other differences I don't know about? Should I always use Collection
if I don't need an order?
Upvotes: 1
Views: 694
Reputation: 9492
For Set you need to be carefull about hashcode and equals. And one interesting twist with Bags in relation to SQL generated:
If we are using List as a mapped attribute in hibernate without indexed column, hibernates treats it as a Bag. Since Hibernate handles List as a Bag (Unordered collection with non unique values. The best feature of a bag is that you can get the number of occurrences of an object through the API With a list, there is no way to do the same without iterating through the whole list.) as soon as we delete and add a element in this collection. Hibernate issues a SQL to delete all the elements first from join table which are no supposed to be deleted and then it re-insert all of them back from the Bag.
http://lkumarjain.blogspot.no/2013/07/why-hibernate-does-delete-all-entries.html
Upvotes: 2
Reputation: 44970
java.util.Collection
is the most generic unordered collection of elements while the java.util.List
implies existence of an iteration order.
Using @OrderColumn
will give this iteration order however it might change the generated SQL query. Often it results in ORDER BY
statement added to the SQL query. Without @OrderColumn
the JPA provider has more flexibility but you should always measure the performance in your actual database instead of tuning it blindly.
Upvotes: 0