Hibernate Table Per Concrete Class Spring Boot

In this post, we will see Hibernate Table Per Concrete Class Example Using Spring Boot and Oracle. 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 Table Per Concrete Class Spring Boot

Let’s see some point related to Hibernate Table Per Concrete Class Spring Boot Example.

  • In table per concrete class mapping, it will create a separate table for each entity.
  • @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) is used with parent entity.
  • Table created for parent entity will have only parent attribute/column whereas child entity will have both parents as well as child attribute/column.

 

Tables details after running this example.

Hibernate Table Per Concrete Class Spring Boot

Hibernate Table Per Concrete Class Spring Boot

Hibernate Table Per Concrete Class Spring Boot

 

Let’s see the Hibernate Table Per Concrete Class Spring Boot Example.

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 – tableperconcreteclasshibernatejpa, ArtifactId – tableperconcreteclasshibernatejpa and name – tableperconcreteclasshibernatejpa) 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>tableperconcreteclasshibernatejpa</groupId>
	<artifactId>tableperconcreteclasshibernatejpa</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>tableperconcreteclasshibernatejpa</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.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.TABLE_PER_CLASS)
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.Entity;

@Entity
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.Entity;

@Entity
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

The query generated while one record.

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

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
    }
]

 

Let’s check the database we have after running this example.

Hibernate Table Per Concrete Class Spring Boot

 

That’s all about Hibernate Table Per Concrete Class Spring Boot Example.

You may like.

Association Mapping in Hibernate using Spring Boot and Oracle Example.

 

Spring Data JPA examples.

Inheritance Mapping docs.

Summary – We have seen Hibernate Table Per Concrete Class Spring Boot. A separate table for each entity.

we have seen Table Per Concrete Class Spring Boot And Oracle.