Hibernate Table Per Subclass Inheritance Spring Boot

In this post, we will see Hibernate Table Per Subclass Inheritance Example Using Spring Boot. We are going to use a maven, embedded tomcat, postman and oracle database.

Hibernate Table Per Subclass Inheritance

 

Let’s see some points related to Hibernate Table Per Subclass Inheritance.

  1. In Table Per Subclass Mapping, subclass mapped tables are related to parent class mapped table with the primary and foreign key relationship.
  2. We need to mention @Inheritance(strategy=InheritanceType.JOINED) with parent class(Insurance.java) and @PrimaryKeyJoinColumn(name=”id”) with child classes(VehicleInsurance.java and HealthInsurance.java).
  3. There will be a separate table for all entity(i.e insurance, health_insurance and vehicle_insurance).

Let’s see the sample table we will have after running this example and inserting one record.

 

Hibernate Table Per Subclass Inheritance Spring Boot

Spring Boot Table Per Subclass

 

Rest endpoint which will be used to save data in the database.

Let’s see the complete example of Hibernate Table Per Subclass Inheritance Spring Boot.

Create a maven project using eclipse and modify pom.xml.

Note – We will not create the table, let’s hibernate do this job. In application.properties file we will keep spring.jpa.hibernate.ddl-auto =create


Open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)’ click on next.  Fill all details(GroupId – tablepersubclasshibernatejpa, ArtifactId – tablepersubclasshibernatejpa and name – tablepersubclasshibernatejpa) and click on finish. Keep packaging as the jar.

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>tablepersubclasshibernatejpa</groupId>
	<artifactId>tablepersubclasshibernatejpa</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>tablepersubclasshibernatejpa</name>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.2.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>

		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
		</dependency>

	</dependencies>

	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>

			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<fork>true</fork>
					<executable>C:\Program Files\Java\jdk1.8.0_131\bin\javac.exe</executable>
				</configuration>
			</plugin>


		</plugins>
	</build>
</project>

Note – In pom.xml we have defined javac.exe path in configuration tag. You need to change accordingly i.e where you have installed JDK. If you see any error for oracle dependency then follow these steps.

 

Define entity classes i.e Insurance.java, HealthInsurance.java and VehicleInsurance.java.

Insurance.java

package com.inheritance.entity;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;



@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Insurance {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;


	@Column(name="company_name")
	private String companyName;


	public int getId() {
		return id;
	}


	public void setId(int id) {
		this.id = id;
	}


	public String getCompanyName() {
		return companyName;
	}


	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}
	
	

}

HealthInsurance.java

package com.inheritance.entity;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

@Entity
@PrimaryKeyJoinColumn(name="id")
public class HealthInsurance extends Insurance {

	@Column(name = "person_name")
	private String personName;

	@Column(name = "age")
	private int age;

	public String getPersonName() {
		return personName;
	}

	public void setPersonName(String personName) {
		this.personName = personName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

 

VehicleInsurance.java.

package com.inheritance.entity;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;

import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;

@Entity
@PrimaryKeyJoinColumn(name="id")
public class VehicleInsurance extends Insurance {

	@Column(name = "vehicle_model")
	String vehicleModel;

	@Column(name = "number_of_wheels")
	int numberOfWheels;

	public String getVehicleModel() {
		return vehicleModel;
	}

	public void setVehicleModel(String vehicleModel) {
		this.vehicleModel = vehicleModel;
	}

	public int getNumberOfWheels() {
		return numberOfWheels;
	}

	public void setNumberOfWheels(int numberOfWheels) {
		this.numberOfWheels = numberOfWheels;
	}

}

Define the repository interface extending CrudRepository.

package com.inheritance.repository;

import java.io.Serializable;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.inheritance.entity.Insurance;
@Repository
public interface InsuranceRepository extends CrudRepository<Insurance,Serializable> {
	
}

 

Define service interface i.e InsuranceService.java

package com.inheritance.service;

import java.util.List;

import org.springframework.stereotype.Component;

import com.inheritance.entity.Insurance;

@Component
public interface InsuranceService {
	public List<Insurance> saveInsurance(List<Insurance> insuranceList);
}

 

Define service implementation class.


package com.inheritance.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.inheritance.entity.HealthInsurance;
import com.inheritance.entity.Insurance;
import com.inheritance.entity.VehicleInsurance;
import com.inheritance.repository.InsuranceRepository;
import com.inheritance.service.InsuranceService;

@Service("insuranceServiceImpl")
public class InsuranceServiceImpl implements InsuranceService {

	@Autowired
	private InsuranceRepository insuranceRepository;

	@Override
	public List<Insurance> saveInsurance(List<Insurance> insuranceList) {

		List<Insurance> insuranceListNew = new ArrayList<>(insuranceList.size());

		Insurance insurance = new Insurance();
		insurance.setCompanyName(insuranceList.get(0).getCompanyName());

		HealthInsurance healthInsurance = new HealthInsurance();
		healthInsurance.setAge(30);
		healthInsurance.setCompanyName("Max Life Insurance");
		healthInsurance.setPersonName("John");

		VehicleInsurance vehicleInsurance = new VehicleInsurance();
		vehicleInsurance.setCompanyName("Reliance general Insurance");
		vehicleInsurance.setNumberOfWheels(2);
		vehicleInsurance.setVehicleModel("FZ-S");

		insuranceListNew.add(insurance);
		insuranceListNew.add(healthInsurance);
		insuranceListNew.add(vehicleInsurance);

		List<Insurance> insuranceResponse = (List<Insurance>) insuranceRepository.saveAll(insuranceListNew);
		return insuranceResponse;
	}

}

Note – See here more about @Component, @Controller, @Service and @Repository annotations here.

Define the controller class or endpoint.


package com.inheritance.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.inheritance.entity.Insurance;
import com.inheritance.service.InsuranceService;
 
@RestController
@RequestMapping(value = "/insurance")
public class InsuranceController {
	
	@Autowired
	private InsuranceService insuranceService;
	
	
	@RequestMapping(value = "/save",method = RequestMethod.POST)
	@ResponseBody
    public List<Insurance> saveBook(@RequestBody List<Insurance> insuranceList) {
		List<Insurance> insuranceResponse = (List<Insurance>) insuranceService.saveInsurance(insuranceList);
		return insuranceResponse;
	}
	
	
	
}

Note – See more details about @Controller and RestController here.

Define the JpaConfig.java

package com.inheritance.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@Configuration
@EnableJpaRepositories(basePackages = "com.inheritance.repository")
public class JpaConfig {

}

Note – See more details about @Configuration annotations here.

Define the SpringMain.java.

package com.inheritance.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages="com.inheritance.*")
@EntityScan("com.inheritance.*")
public class SpringMain {
	public static void main(String[] args) {

        SpringApplication.run(SpringMain.class, args);
    }

}

Note – See more details about @ComponentScan here.

application.properties

# Connection url for the database
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=SYSTEM
spring.datasource.password=oracle2
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
# Show or not log for each sql query
spring.jpa.show-sql = true
 
 
spring.jpa.hibernate.ddl-auto =create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.Oracle10gDialect
 
server.port = 9091

 

 

Generated query.

Hibernate: insert into insurance (company_name, id) values (?, ?)
Hibernate: insert into insurance (company_name, id) values (?, ?)
Hibernate: insert into health_insurance (age, person_name, id) values (?, ?, ?)
Hibernate: insert into insurance (company_name, id) values (?, ?)
Hibernate: insert into vehicle_insurance (number_of_wheels, vehicle_model, id) values (?, ?, ?)

 

That’s all about Hibernate Table Per Subclass Inheritance Example Using Spring Boot.

You may like.

Association Mapping Examples Using Spring Boot and Oracle.

Spring Data JPA examples.

 

Summary – We have seen Hibernate Table Per Subclass Inheritance Example Using Spring Boot. A separate table created for all concrete subclasses.