JPA - Embeddable class with entity relationships

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

An embeddable class may contain a relationship with an entity. Let's see that with an example

Example

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

  @Embedded
  private ClassA classARef;
    .............
}

The @Embeddable ClassA has ManyToOne relationship with entityB:

@Embeddable
public class ClassA {
  private String myStr;

  @ManyToOne
  private EntityB entityBRef;
    .............
}
@Entity
public class EntityB {
  @Id
  @GeneratedValue
  private int myIdB;
  private String myStr2;
    .............
}
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 EntityA");
          nativeQuery(em, "SHOW COLUMNS from EntityB");
          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'
[ENTITYA, PUBLIC]
[ENTITYB, PUBLIC]
'SHOW COLUMNS from EntityA'
[ID, INTEGER(10), NO, PRI, NULL]
[MYSTR, VARCHAR(255), YES, , NULL]
[ENTITYBREF_MYIDB, INTEGER(10), YES, , NULL]
'SHOW COLUMNS from EntityB'
[MYIDB, INTEGER(10), NO, PRI, NULL]
[MYSTR2, VARCHAR(255), YES, , NULL]

The foreign key column ENTITYBREF_MYIDB is in EntityA table, that's because EntityA having the embedded class in it is just like: EntityA has direct ManyToOne relationship to EntityB

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();

      EntityB entityB = new EntityB();
      entityB.setMyStr2("a test string in EntityB");

      ClassA a = new ClassA();
      a.setMyStr("a test string in ClassA");
      a.setEntityBRef(entityB);

      EntityA entityA = new EntityA();
      entityA.setClassARef(a);

      System.out.println(entityA);

      em.getTransaction().begin();
      em.persist(entityA);
      em.persist(entityB);
      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 EntityA");
      ExampleMain.nativeQuery(em, "Select * from EntityB");
  }

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

      System.out.println("-- Loading EntityB --");
      List<EntityB> entityBList = em.createQuery("Select t from EntityB t")
                                    .getResultList();
      entityBList.forEach(System.out::println);
      em.close();
  }
}

Output

-- Persisting entities --
EntityA{id=0, classARef=ClassA{myStr='a test string in ClassA', entityBRef=EntityB{myIdB=0, myStr2='a test string in EntityB'}}}
-- native queries --
'Select * from EntityA'
[1, a test string in ClassA, 2]
'Select * from EntityB'
[2, a test string in EntityB]
-- Loading EntityA --
EntityA{id=1, classARef=ClassA{myStr='a test string in ClassA', entityBRef=EntityB{myIdB=2, myStr2='a test string in EntityB'}}}
-- Loading EntityB --
EntityB{myIdB=2, myStr2='a test string in EntityB'}

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.
  • JDK 1.8
  • Maven 3.3.9

Embeddable With Entity Relationship Select All Download
  • embeddable-with-many-to-one-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
          • META-INF

See Also