Close

JPA - Customizing the mapping of java.util.Map

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

The mapping of java.util.Map can be customized by using one or more of the followings annotations on the map field/property:

  • @CollectionTable:

    To customize the map table (the the foreign key table containing map's key/value columns).

  • @MapKeyColumn:

    To customize the 'key' column in the map table.

  • @Column:

    To customize the 'value' column in the map table.

Example

@Entity
public class Customer {
  @Id
  @GeneratedValue
  private int id;

  private String name;
  @ElementCollection
  @MapKeyColumn(name = "item")
  @Column(name = "qty")
  @CollectionTable(name = "ITEM_QTY")
  private Map<String, Integer> itemQtyMap;
    .............
}
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 ITEM_QTY");

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

Output

'SHOW TABLES'
[CUSTOMER, PUBLIC]
[ITEM_QTY, PUBLIC]
'SHOW COLUMNS from Customer'
[ID, INTEGER(10), NO, PRI, NULL]
[NAME, VARCHAR(255), YES, , NULL]
'SHOW COLUMNS from ITEM_QTY'
[CUSTOMER_ID, INTEGER(10), NO, PRI, NULL]
[QTY, INTEGER(10), YES, , NULL]
[ITEM, VARCHAR(255), NO, PRI, 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");
      Map<String, Integer> itemPurchased = new HashMap<>();
      itemPurchased.put("XYZ Blender", 1);
      itemPurchased.put("ZZZ Beer Glass", 4);
      c1.setItemQtyMap(itemPurchased);
      System.out.println(c1);

      Customer c2 = new Customer();
      c2.setName("Morgan Philips");
      Map<String, Integer> orderMap2 = new HashMap<>();
      orderMap2.put("AA Glass Cleaner",3);
      c2.setItemQtyMap(orderMap2);
      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 ITEM_QTY");
  }

  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', itemQtyMap={XYZ Blender=1, ZZZ Beer Glass=4}}
Customer{id=0, name='Morgan Philips', itemQtyMap={AA Glass Cleaner=3}}
-- Native queries --
'Select * from Customer'
[1, Lindsey Craft]
[2, Morgan Philips]
'Select * from ITEM_QTY'
[1, 1, XYZ Blender]
[1, 4, ZZZ Beer Glass]
[2, 3, AA Glass Cleaner]
-- Loading Customer --
Customer{id=1, name='Lindsey Craft', itemQtyMap={XYZ Blender=1, ZZZ Beer Glass=4}}
Customer{id=2, name='Morgan Philips', itemQtyMap={AA Glass Cleaner=3}}

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

Customizing Map Mapping Select All Download
  • customizing-map-mapping
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Customer.java
          • resources
            • META-INF

    See Also