Close

JPA - Persisting Collections of basic Java types by using @ElementCollection

[Last Updated: May 31, 2017]
A quick overview of collection of basic types mapping in JPA
  • To persist a collection of basic Java type, the annotation @ElementCollection is used. This annotation is placed on the collection reference in the entity class.
  • The Entity and the basic type collection are mapped to two separate foreign/primary-key tables. One for the entity and other for basic collection values. The collection table has the foreign key pointing to the primary key of the entity.
  • This is similar to OneToMany relation, except the target is a basic value instead of another entity.
  • By default, JPA specific naming conventions are used for the mapping. To customize that, we can use @CollectionTable annotation along with @ElementCollection.

Example

@Entity
public class Customer {
  @Id
  @GeneratedValue
  private int id;
  private String name;
  @ElementCollection
  private List<String> phoneNumbers;
    .............
}
public class ExampleMain {

  public static void main(String[] args) {
      EntityManagerFactory emf = Persistence.createEntityManagerFactory("example-unit");
      try {
          EntityManager em = emf.createEntityManager();
          nativeQuery(em, "SHOW TABLES");
          nativeQuery(em, "SHOW COLUMNS from Customer");
          nativeQuery(em, "SHOW COLUMNS from Customer_PhoneNumbers");

          emf.close();
      } finally {
          emf.close();
      }
  }

  public static void nativeQuery(EntityManager em, String s) {
      System.out.printf("'%s'%n", s);
      Query query = em.createNativeQuery(s);
      List list = query.getResultList();
      for (Object o : list) {
          if (o instanceof Object[]) {
              System.out.println(Arrays.toString((Object[]) o));
          } else {
              System.out.println(o);
          }
      }
  }
}

Output

'SHOW TABLES'
[CUSTOMER, PUBLIC]
[CUSTOMER_PHONENUMBERS, PUBLIC]
'SHOW COLUMNS from Customer'
[ID, INTEGER(10), NO, PRI, NULL]
[NAME, VARCHAR(255), YES, , NULL]
'SHOW COLUMNS from Customer_PhoneNumbers'
[CUSTOMER_ID, INTEGER(10), NO, , NULL]
[PHONENUMBERS, VARCHAR(255), YES, , NULL]

An overview of the mapping:

Persisting and loading Data

public class ExampleMain2 {

  public static void main(String[] args) {
      EntityManagerFactory emf = Persistence.createEntityManagerFactory("example-unit");
      try {
          persistEntity(emf);
          runNativeQueries(emf);
          loadEntity(emf);
      } finally {
          emf.close();
      }
  }

  private static void persistEntity(EntityManagerFactory emf) {

      System.out.println("-- Persisting entities --");
      EntityManager em = emf.createEntityManager();

      Customer c1 = new Customer();
      c1.setName("Lindsey Craft");
      c1.setPhoneNumbers(Arrays.asList("111-111-1111", "222-222-222"));
      System.out.println(c1);

      Customer c2 = new Customer();
      c2.setName("Morgan Philips");
      c2.setPhoneNumbers(Arrays.asList("333-333-3333"));
      System.out.println(c2);

      em.getTransaction().begin();
      em.persist(c1);
      em.persist(c2);
      em.getTransaction().commit();
      em.close();
  }

  private static void runNativeQueries(EntityManagerFactory emf) {
      System.out.println("-- Native queries --");
      EntityManager em = emf.createEntityManager();
      ExampleMain.nativeQuery(em, "Select * from Customer");
      ExampleMain.nativeQuery(em, "Select * from Customer_PhoneNumbers");
  }

  private static void loadEntity(EntityManagerFactory emf) {
      System.out.println("-- Loading Customer --");
      EntityManager em = emf.createEntityManager();
      List<Customer> entityAList = em.createQuery("Select t from Customer t")
                                     .getResultList();
      entityAList.forEach(System.out::println);
      em.close();
  }
}

Output

-- Persisting entities --
Customer{id=0, name='Lindsey Craft', phoneNumbers=[111-111-1111, 222-222-222]}
Customer{id=0, name='Morgan Philips', phoneNumbers=[333-333-3333]}
-- Native queries --
'Select * from Customer'
[1, Lindsey Craft]
[2, Morgan Philips]
'Select * from Customer_PhoneNumbers'
[1, 111-111-1111]
[1, 222-222-222]
[2, 333-333-3333]
-- Loading Customer --
Customer{id=1, name='Lindsey Craft', phoneNumbers=[111-111-1111, 222-222-222]}
Customer{id=2, name='Morgan Philips', phoneNumbers=[333-333-3333]}

Example Project

Dependencies and Technologies Used:

  • h2 1.4.193: H2 Database Engine.
  • hibernate-core 5.2.8.Final: The core O/RM functionality as provided by Hibernate.
    Implements javax.persistence:javax.persistence-api version 2.1
  • JDK 1.8
  • Maven 3.3.9

Element Collection Example Select All Download
  • element-collection-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Customer.java
          • resources
            • META-INF

    See Also