Close

JPA - Customizing @ElementCollection table attributes by using @CollectionTable

[Updated: May 31, 2017, Created: May 26, 2017]

To customize foreign-key table mapped by @ElementCollection (both for basic types or embedded types), @CollectionTable can be used. This is specially useful when we already have a collection table to be mapped.

Example

@Entity
public class Customer {
  @Id
  @GeneratedValue
  private int id;
  private String name;
  @ElementCollection
  @CollectionTable(name = "PHONES", joinColumns = @JoinColumn(name = "CUST_ID"))
  @Column(name = "PH_NO")
  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 Phones");
          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]
[PHONES, PUBLIC]
'SHOW COLUMNS from Customer'
[ID, INTEGER(10), NO, PRI, NULL]
[NAME, VARCHAR(255), YES, , NULL]
'SHOW COLUMNS from Phones'
[CUST_ID, INTEGER(10), NO, , NULL]
[PH_NO, VARCHAR(255), YES, , NULL]

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 Phones");
  }

  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 Phones'
[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

Collection Table Example Select All Download
  • collection-table-annotation
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Customer.java
          • resources
            • META-INF

    See Also