Suppose there are three classes:
One is:
@Entity
@Indexed
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
@Table(name = "tbl_a")
public class A {
@Id
@DocumentId
@GeneratedValue(generator="rwSpecSeq")
@SequenceGenerator(name="rwSpecSeq", sequenceName="RW_SPEC_SEQ")
private int id;
private String sampleAttribute;
//Getters and Setters
}
@Entity
@DiscriminatorValue("b")
public class B extends A {
}
@Entity
@DiscriminatorValue("c")
public class C extends A {
}
If one object is saved as B’s object then if again I want to cast or change the object to C then it is giving class cast exception. Please tell me how to cast class in hibernate when merging.
My approach was something like this:
//Assuming that the object is C class' object.
A a = adminService.getA(request.getParameter("id"));
//before merging I did this
B b = (B)a;
adminService.save(b);
You just can’t. Hibernate keeps the objects type when they are persisted to the database. And Java prevents casting objects from one type to another when they are incompatible.
In your case, you can’t cast an instance of
CinB. It would be like casting aStringinto anInteger.Your best shot is to write a method that takes an instance of
Cand copies all the attributes ofCinto a new object of typeB.