How can I cast from one class to another class in hibernate

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);

Answers


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 C in B. It would be like casting a String into an Integer.

Your best shot is to write a method that takes an instance of C and copies all the attributes of C into a new object of type B.


Need Your Help

Django django-smart-select: get TemplateSyntaxError during adding of data in admin site

django django-models django-admin django-templates render

I'm a Django newbie. I want to try this app django-smart-selects. I would like the "Customer" adress being auto-populated by choosing the appropiate "Customer" in the "Order" form of the admin site...

Should i use nginx for my image hosting site with high traffic?

apache optimization nginx

I am suggested by a friend to use nginx for my site http://www.imgzzz.com . its an image hosting site with loads of traffic.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.