Quantcast
Viewing all articles
Browse latest Browse all 133

JPA Pitfalls (1): Serialized Collection

This blog article is part of a “series of blog articles” about common pitfalls using JPA and ways to avoid them. In this article, we describe, how easily a relation mapped as collection ends up as a blob.

Two entity classes have a relationship, but there is no relationship modeling annotation such as @OneToOne, @OneToMany, @ManyToOne or @ManyToMany. From the JPA perspective this is a valid object model as long as the entity classes implement the Serializable interface. In this case the related instances are stored as a serialized object in the database. The Java code can change the collection and its objects. The changes are still there, when reloading the object from the data base. Unfortunately, the related entities are not changed.  Sometimes, it can take a while to locate this bug.

In the following sample code a class Department class has a set of employee instances. Without the @OneToMany annotation any change to one of the related instances stored in the set is not reflected in the employee table in the database.

// Stored as a BLOB
private Set<Employee> employees;
 
// Relationship managed by JPA
@OneToMany(...)
private Set<Employee> employees;

When generating the db schema from the object model, a BLOB column is suspicious unless there are images or the like in the Java class. Therefore: Always check your DB schema for unexpected elements!

You can find an example of this pitfall and its solution in the class SerializedCollectionExperiment in this project: https://github.com/akquinet/jpapitfalls.git.


Viewing all articles
Browse latest Browse all 133

Trending Articles