Reputation: 3166
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
}
Upvotes: 1
Views: 463
Reputation: 19130
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.
Upvotes: 1