1

I would like to retrieve an object from my data store and upgrade its type. For instance from Employee to ExtendedEmployee defined below. Is it possible? How could I achieve this? Because of some synchronization issues in my project I cannot persist another copy of this object (remove actual and save extended one).

@Entity  
@Table(name = "employee")  
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)  
@DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)  
@DiscriminatorValue(value="employee")  
public class Employee {  
@Id  
@GeneratedValue(strategy=GenerationType.AUTO)  

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

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

//setters and getters  
}

@Entity  
@DiscriminatorValue("extendedemployee")  
public class ExtendedEmployee extends Employee{  

@Column(name="salary")    
private float salary;  

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

//setters and getters  
} 
1

1 Answer 1

1

I think it's possible, but I personally not recommend to use the SINGLE_TABLE. For me, this is very confuse. When you are looking only for the tables in the database this mapping can cause some problems to understand the generated queries and debug some situations. There are some concerns with this solution about performance and evolution of the application too.

In your case, I would use composition instead of inheritance.

So, you could have a Employe and ExtendedEmployee like this:

@Entity  
@Table(name = "employee")  
public class Employee {  

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

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

  //setters and getters  
}

@Entity  
public class ExtendedEmployee { 

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

  @ManyToOne(fetch = FetchType.LAZY)
  private Employe employe;

  @Column(name="salary")    
  private float salary;  

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

  //setters and getters  
} 

You only need create the new table and create a foreign key for the existing table.

For me, this is more simple and correct. Use inheritance with JPA bring a lot of problems.

Sign up to request clarification or add additional context in comments.

1 Comment

ok, but the problem here is that ExtendedEmployee in not an Employee, so I can not take advantage of polymorphism :( I can not store them in one collection, I duplicate the same fields and other things like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.