JPA
Java
Persistence
List<String>
ORM

How to persist a property of type ListString in JPA?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Understanding JPA and Persisting a List of Strings

Java Persistence API (JPA) is an essential tool in the arsenal of a modern Java developer for managing and persisting data. In complex applications, you often need to store collections of data directly associated with an entity. A common requirement is to persist a property of type List<String>. Let's explore how you can achieve this in JPA.

Basics of JPA and Entity Relationships

JPA provides a way to manage relational data in Java applications. Suppose you have a Person entity and want to store a list of hobbies. Each hobby is a simple String. Here's a typical scenario using basic JPA annotations:

java
1@Entity
2public class Person {
3    
4    @Id
5    @GeneratedValue(strategy = GenerationType.IDENTITY)
6    private Long id;
7
8    private String name;
9
10    @ElementCollection
11    @CollectionTable(name = "person_hobbies", joinColumns = @JoinColumn(name = "person_id"))
12    @Column(name = "hobby")
13    private List<String> hobbies = new ArrayList<>();
14
15    // getters and setters
16}

Exploring the Annotations

  1. @ElementCollection: This annotation is used to specify a collection of basic or embeddable types. Since List<String> is a collection of basic types, we can use @ElementCollection here.
  2. @CollectionTable: This annotation defines the table that holds the collection. joinColumns attribute shows how this table links back to the Person entity through a foreign key person_id.
  3. @Column: Used to define the mapping for the elements of the list. In this case, it's the column name for the String elements in the collection.

Database Table Mapping

When using the above configuration, JPA generates two tables. Consider you have a Person table:

person
id
name

And a generated person_hobbies table that looks somewhat like this:

person_hobbies
person_idhobby

Here, person_id is a foreign key referencing the primary key of the Person entity.

Key Considerations

  • Uniqueness: Data in an ElementCollection is not unique by default. Duplicate entries in the list will be stored as-is.
  • Ordering: By default, there is no order preserved in the collection. If you want to maintain order, consider implementing a sorted collection or adding an @OrderBy annotation.

Handling Lists with JPA

Customizing EntityMapping with @AttributeOverrides

If your application requires more customization in terms of column naming without creating separate tables:

java
1@ElementCollection
2@CollectionTable(name = "person_hobbies")
3@AttributeOverrides({
4    @AttributeOverride(name = "hobby", column = @Column(name = "hobby_name"))
5})
6private List<String> hobbies;

Full Example and Considerations

java
1@Entity
2public class Lecturer {
3
4    @Id
5    @GeneratedValue(strategy = GenerationType.IDENTITY)
6    private Long id;
7
8    private String name;
9
10    @ElementCollection
11    @CollectionTable(name = "lecturer_subjects", joinColumns = @JoinColumn(name = "lecturer_id"))
12    @Column(name = "subject")
13    private List<String> subjects = new ArrayList<>();
14
15    // Add more logic here if necessary
16
17    // Getters, Setters, toString, hashCode, and equals
18}

Advantages and Caveats

Advantages:

  • Simplicity in mapping basic collections directly.
  • Automatic table creation and management by the JPA provider.

Caveats:

  • If relationships become complex, a @OneToMany relationship might be more appropriate using a dedicated Subject entity.
  • Handling cascade operations and fetch types can become tricky with large datasets.

Summary Table of Key Points

FeatureDescription
@ElementCollectionMaps a collection of basic types.
@CollectionTableDefines the intermediary table for collections.
@ColumnDefines the column for each list item.
Data OrderingUse @OrderBy if the order matters.
Handling DuplicatesNo inherent mechanism for uniqueness. Use lists!

This guide outlines the straightforward approach JPA offers for handling lists of basic types. As your application evolves, regularly review these configurations to ensure they still meet your performance and complexity requirements.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design