0

I want to use inheritance or some clean JPA logic so that i dont have to replicate my code to perform POST, GET and PUT operations on 2 identical table objects using spring data jpa

I have 2 identical tables as 1) contractemployees 2)permanentemployees

Both have the same structure

CREATE TABLE permanentemployee (
  empid int(11) NOT NULL,
  age int(11) NOT NULL,
  departmentname varchar(255) NOT NULL,
  empname varchar(255) DEFAULT NULL,
  salary int(11) NOT NULL,
  PRIMARY KEY (empid));

CREATE TABLE contractemployees(
  empid int(11) NOT NULL,
  age int(11) NOT NULL,
  departmentname varchar(255) NOT NULL,
  empname varchar(255) DEFAULT NULL,
  salary int(11) NOT NULL,
  PRIMARY KEY (empid));

PROBLEM I want to use a single spring data JPA Repo which can create, get, update the records.

Adding all the table properties to a abstract class entity

@Entity
@MappedSuperclass
@Data
public abstract class Employee{
private String empname;
private String departmentid;
private int age;
private int salary;
}

First entity for contract employees

@Entity
@Table(name="contractemployee")
public class Contractemployees extends Employee {
@Id
private int empid;

}

Second entity for permananent employees

@Entity
@Table(name="permanentemployee")
public class PermanentEmployee extends Employee {
@Id
private int empid;

}

Repo

@NoRepositoryBean
public interface EmployeeRepo<T extends Employee> extends CrudRepository<T, Integer> {

    }

How should i pass these object from controller that JPA knows which table to fetch/update from.

JavaDeveloper
  • 92
  • 1
  • 1
  • 11
  • I would rather say why 2 tables? why not add an extra column 'type' (Permanent, Contract) That would make you model/code less complex. – Dirk Deyne May 24 '19 at 18:23
  • This is just an example actually problem is similar but i cannot alter the tables :( as db is not owned by us. – JavaDeveloper May 26 '19 at 10:08
  • Possible duplicate of [Spring Data JPA inheritance in repositories](https://stackoverflow.com/questions/43350397/spring-data-jpa-inheritance-in-repositories) – watchme May 26 '19 at 10:29
  • We have this exact issue. To answer @DirkDeyne's question, we need to split a large table into two tables for performance reasons, the table is getting huge and most of the additions will come from data with certain values so we are splitting it into two tables as a short term performance benefit. – Uncle Long Hair Aug 21 '20 at 13:55
  • @UncleLongHair Ok, but there is no issue if you create two concrete repositories... – Dirk Deyne Aug 21 '20 at 15:05
  • @DirkDeyne well we have repositories, and entities with relationships, and some JPQL, and are trying to figure a way to do it without just duplicating everything, and also ensuring that we get db traffic on only one table or the other and not both. Seeing some solutions that use the MappedSuperclass annotation, looking to see if that will work. – Uncle Long Hair Aug 21 '20 at 15:39

0 Answers0