0

We recently joined up to an existing project and in several entity classes we have seen the following code example:

@OneToMany(mappedBy = "department")
private List<Employee> employee= new LinkedList<>();

I had a discussion with a developer about using ArrayList instead of LinkedList for hibernate. But the arguments from both sides were not clear enough.

Usually, i use for many purposes an ArrayList. Here is a good comparison

  • Does hibernate under the hood work better with that?
  • Is there a reason why linkedList is used?
  • Or has it simply been used unknowingly in the project?
Muhammed Misir
  • 400
  • 9
  • 22
  • which list you should totally depends on the business requirement and you already mentioned the answer in the question you have asked – Rajendra Gupta Jul 30 '19 at 06:59
  • 1
    Actually, for an Entity loaded from the database the type will be https://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/collection/PersistentList.html regardless of the concrete type you may have specified in the code. The concrete type will be a LinkedList only for a newly created entity. See further https://stackoverflow.com/questions/8971010/persisting-linkedlist-in-hibernate – Alan Hay Jul 30 '19 at 07:35
  • Possible duplicate of [Persisting LinkedList in Hibernate](https://stackoverflow.com/questions/8971010/persisting-linkedlist-in-hibernate) – Alan Hay Jul 30 '19 at 07:36
  • There is almost never a good reason to use `LinkedList` unless you have clear evidence that `LinkedList` is a better choice. In almost all situations, array list will perform better and have less memory overhead. – Mark Rotteveel Aug 02 '19 at 20:05

1 Answers1

1

The actual implementation used when an entity is loaded from the database is not the same as the default value in the class definition. This is why entity properties which are collections must be specified as an interface type.

Hibernate uses its own collection implementations which are enriched with lazy-loading, caching or state change detection semantics. For this reason, persistent collections must be declared as an interface type.

From https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#collections

If your entity is not loaded from the database then you should specify a default implementation that make sense for the use case, but being aware it'll not be the same implementation when the entity is loaded. Generally, this means just using ArrayList in most situations.

ptomli
  • 11,730
  • 4
  • 40
  • 68