Hibernate Single Table Inheritance using Spring Boot

In this post, we will see Hibernate Single Table Inheritance using Spring Boot. We are going to use a maven, embedded tomcat, postman and oracle database. Here we will have rest endpoint which will be used to save data in the database.

Hibernate Single Table Inheritance using Spring Boot

 

Let’s see some point related to Hibernate Single Table Inheritance.

  • In Single Table Inheritance for all classes/entities which are in an inheritance relationship, there will be the only one table. 
  • @Inheritance(strategy=InheritanceType.SINGLE_TABLE) annotation is used with parent class. 
  • Apart from the above annotation @DiscriminatorColumn and @DiscriminatorValue used, for example we are going to use these annotations as (@DiscriminatorColumn(name=”type”,discriminatorType=DiscriminatorType.STRING) and @DiscriminatorValue(value=”INS”)).
  • @DiscriminatorValue needs to use with each entity which used to distinguish one entity from another.

Let’s see the sample table we will have after running this example.

hibernate single table inheritance

The entity with no fields will have null values.

Let’s see complete Hibernate Single Table Inheritance using Spring Boot and Oracle example from scratch.

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 – tableperclasshibernatejpa , ArtifactId – tableperclasshibernatejpa  and name – tableperclasshibernatejpa ) and click on finish. Keep packaging as the jar.

Modify pom.xml

<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>tableperclasshibernatejpa</groupId>
	<artifactId>tableperclasshibernatejpa</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>tableperclasshibernatejpa</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.

hibernate single table inheritance

Define entity class 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;


@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value="INS")
@Entity
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.Table;

@Entity
@DiscriminatorValue("HEL")
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
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;

@Entity
@DiscriminatorValue("VHI")
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
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

Now we will prepare JSON data and will try save in database.

Sample request JSON data-

[{
	"companyName": "LIC"
}]

 

Response – 

[
    {
        "id": 1,
        "companyName": "LIC"
    },
    {
        "id": 2,
        "companyName": "Max Life Insurance",
        "personName": "John",
        "age": 30
    },
    {
        "id": 3,
        "companyName": "Reliance general Insurance",
        "vehicleModel": "FZ-S",
        "numberOfWheels": 2
    }
]

hibernate single table inheritance

 

This is all about Hibernate Single Table Inheritance using Spring Boot.

You may like.

Association Mapping in Hibernate using Spring Boot and Oracle Example.

Spring Data JPA examples.

 

Summary – We have seen Hibernate Single Table Inheritance using Spring Boot and Oracle. A single table created for all concrete subclasses.