If you asked yourself how to persist list of String elements in Hibernate, there are few ways to do so, but the most common and easiest one is by using @ElementCollection annotation.

What you need to do is to annotate the list element with @ElementCollection and you'll notice that persistence provider will create a new table in a database where it will store your list. In this tutorial, we'll show how Hibernate behaves and what is created in the database when using @ElementCollection annotation.

Implementation

import java.util.ArrayList;
import java.util.List;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Shirt {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	Long id;

	@ElementCollection
	List<String> availableColors = new ArrayList<String>();

	public Long getId() {
		return id;
	}

	public List<String> getAvailableColors() {
		return availableColors;
	}

	public void setAvailableColors(List<String> availableColors) {
		this.availableColors = availableColors;
	}

}

Result in database

I'll create one object of Shirt type with available colors {Red, Blue} and persist it. The situation in the database would be as follows:

How to persist list of String elements in Hibernate

You'll notice that there's the separate table for field availableColors, and that Hibernate added shirt_ prefix to availableColors table. If you do select on table Shirt, you'll notice that there's nothing related to availableColors table there, just the Id field. 

How to persist list of String elements in Hibernate

But if you select from shirt_availablecolors, you'll notice that every String object in List is now separate row with reference to parent Shirt object by shirt_id. The bad side of this approach is that availableColors element has no id so it couldn't be addressed separately from other elements.

How to persist list of String elements in Hibernate

Pin It