Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JPA return "null" or empty collection for a collection property that is empty in the DB?

If I have a JPA entity containing a collection field, such as

public class Post {    
  // [...]
  @OneToMany
  private List<String> tags;

the corresponding database schema will typically contain a separate table for storing the tags, where each record contains one tag and a foreign key reference to the "Post" table.

Now when I load a "Post" entity from the database which has no tags (i.e. no corresponding "tag" records exist), what will the value of Post.tags be? Will it be set to null, or to an empty List? Or is this undefined?

I could not find this in the JPA specification.


Note: This is the same question like Does Hibernate return null or empty collection if table in relation is empty?, only for the JPA spec instead of for Hibernate specifically.

I know that most JPA implementations (at least Hibernate and EclipseLink) will return an empty collection - I'm interested in whether this is specified anywhere.

like image 503
sleske Avatar asked Jun 14 '18 14:06

sleske


People also ask

Does JPA return null or empty list?

The normal behavior is indeed returning an empty list if no results are found. If a List<Object> is the return value of the method in the defined interface, the method should never return Null . The problem is that a parameter is given to the method and is not used anywhere in the Query.

What does JPA repository return when not found?

From my little and personal experience, if you search for an object on your repo, for example by Id or Name the named query method returns an object of type T , but if no results are found from your repo, it will return null.

How does JPA handle null values?

The JPA specification defines that during ordering, NULL values shall be handled in the same way as determined by the SQL standard. The standard specifies that all null values shall be returned before or after all non-null values. It's up to the database to pick one of the two options.

How do I ignore null values in JPA?

You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.


1 Answers

According to the JPA 2.1 spec:

2.9 Entity Relationships

If there are no associated entities for a multi-valued relationship of an entity fetched from the database, the persistence provider is responsible for returning an empty collection as the value of the relationship.

like image 75
crizzis Avatar answered Sep 20 '22 10:09

crizzis