Close

JPA - @MappedSuperclass with @OneToMany Example

This example demonstrates how to use @MappedSuperclass with @OneToMany relationship.

Example

@MappedSuperclass
public class Employee {
    @Id
    @GeneratedValue
    private long id;
    private String name;
    @OneToMany(cascade = CascadeType.ALL)
    private List<Phone> phones;
    .............
}
@Entity
public class Phone {
    @Id
    @GeneratedValue
    private long id;
    private String type;
    private String number;
    .............
}
@Entity
@Table(name = "FULL_TIME_EMP")
@AttributeOverrides({
        @AttributeOverride(name = "name", column = @Column(name = "FULL_TIME_EMP_NAME"))
})
public class FullTimeEmployee extends Employee {
    private int salary;
    .............
}
@Entity
@Table(name = "PART_TIME_EMP")
public class PartTimeEmployee extends Employee {
    private int hourlyRate;
    .............
}
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 FULL_TIME_EMP");
            nativeQuery(em, "SHOW COLUMNS from PART_TIME_EMP");
            nativeQuery(em, "SHOW COLUMNS from PHONE");
        } 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'
[FULL_TIME_EMP, PUBLIC]
[FULL_TIME_EMP_PHONE, PUBLIC]
[PART_TIME_EMP, PUBLIC]
[PART_TIME_EMP_PHONE, PUBLIC]
[PHONE, PUBLIC]
'SHOW COLUMNS from FULL_TIME_EMP'
[ID, BIGINT(19), NO, PRI, NULL]
[FULL_TIME_EMP_NAME, VARCHAR(255), YES, , NULL]
[SALARY, INTEGER(10), NO, , NULL]
'SHOW COLUMNS from PART_TIME_EMP'
[ID, BIGINT(19), NO, PRI, NULL]
[NAME, VARCHAR(255), YES, , NULL]
[HOURLYRATE, INTEGER(10), NO, , NULL]
'SHOW COLUMNS from PHONE'
[ID, BIGINT(19), NO, PRI, NULL]
[NUMBER, VARCHAR(255), YES, , NULL]
[TYPE, VARCHAR(255), YES, , NULL]

Persisting and loading data

public class ExampleMain2 {

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

    private static void persistEntities(EntityManagerFactory emf) throws Exception {
        System.out.println("-- Persisting entities --");
        EntityManager em = emf.createEntityManager();

        FullTimeEmployee e1 = new FullTimeEmployee();
        e1.setName("Sara");
        e1.setSalary(100000);
        Phone p1 = new Phone();
        p1.setType("cell");
        p1.setNumber("111-222-3232");

        Phone p2 = new Phone();
        p2.setType("home");
        p2.setNumber("212-222-3232");
        e1.setPhones(Arrays.asList(p1, p2));
        System.out.println(e1);

        PartTimeEmployee e2 = new PartTimeEmployee();
        e2.setName("Robert");
        e2.setHourlyRate(60);
        Phone p3 = new Phone();
        p3.setType("cell");
        p3.setNumber("123-323-9999");
        e2.setPhones(Arrays.asList(p3));
        System.out.println(e2);

        em.getTransaction().begin();
        em.persist(e1);
        em.persist(e2);
        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 FULL_TIME_EMP");
        ExampleMain.nativeQuery(em, "Select * from PART_TIME_EMP");
        ExampleMain.nativeQuery(em, "Select * from PHONE");
    }

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

        entityAList = em.createQuery("Select t from PartTimeEmployee t")
                        .getResultList();
        entityAList.forEach(System.out::println);
        em.close();
    }
}

Output

-- Persisting entities --
FullTimeEmployee{Employee{id=0, name='Sara', phones=[Phone{id=0, type='cell', number='111-222-3232'}, Phone{id=0, type='home', number='212-222-3232'}]}, salary=100000}
PartTimeEmployee{Employee{id=0, name='Robert', phones=[Phone{id=0, type='cell', number='123-323-9999'}]}, hourlyRate='60'}
-- Native queries --
'Select * from FULL_TIME_EMP'
[1, Sara, 100000]
'Select * from PART_TIME_EMP'
[4, Robert, 60]
'Select * from PHONE'
[2, 111-222-3232, cell]
[3, 212-222-3232, home]
[5, 123-323-9999, cell]
-- Loading entities --
FullTimeEmployee{Employee{id=1, name='Sara', phones=[Phone{id=2, type='cell', number='111-222-3232'}, Phone{id=3, type='home', number='212-222-3232'}]}, salary=100000}
PartTimeEmployee{Employee{id=4, name='Robert', phones=[Phone{id=5, type='cell', number='123-323-9999'}]}, hourlyRate='60'}

Example Project

Dependencies and Technologies Used:

  • h2 1.4.196: H2 Database Engine.
  • hibernate-core 5.2.10.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

mapped-super-class-with-one-to-many-example Select All Download
  • mapped-super-class-with-one-to-many-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Employee.java
          • resources
            • META-INF

    See Also