user998970
user998970

Reputation: 1

Java type casting for hibernate

Yes, I know we can upcast or downcast in Java. But the type of the instance doesn't really seems to be change and it's giving me a problem.

E.g.

class Foo{
int a, b; 
.. constructors, getters and setters
}

class FooDTO extends Foo {
...
}

FooDTO dto = FooDTO(1,2);
Foo parent = (Foo) dto;

in hibernate, when saving the "parent", it's still think that it's a DTO object and can't be saved. Can I really turn a child instance into a parent instance?

Upvotes: 0

Views: 2194

Answers (3)

CodeClimber
CodeClimber

Reputation: 4664

An object's type cannot be changed after it has been created. If you create a FooDTO object it will always be a FooDTO object.

When you cast you are telling the JVM that you are going to use a reference of type X to point at an object that you know is of type X.

class Parent {}
class Child extends Parent {}

class Test {
    public void stuff() {
        Parent p = new Parent(); // Parent reference, Parent object
        Parent p2 = new Child(); // Parent reference, Child object
        Child c = new Child();   // Child reference, Child object 


        Parent p2 = c; // no explicit cast required as you are up-casting
        Child c2 = (Child)p; // explicit cast required as you are down-casting. Throws ClassCastException as p does not point at a Child object
        Child c3 = (Child)p2; // explicit cast required as you are down-casting. Runs fine as p2 is pointong at a Child object
        String s1 = (String)p; // Does not compile as the compiler knows there is no way a Parent reference could be pointing at a String object            

    }
}

Upvotes: 0

Salandur
Salandur

Reputation: 6453

you can save the 'parent' by using hibernate's save(entityName, object) method. In this case the entityName is the fully qualified class name of 'parent'.

Upvotes: 1

Jothi
Jothi

Reputation: 15090

No u can't trun child into parent in this way. You have create the object for parent sperately.like, Foo parent new Foo(dto.getA(),dto.getB());

Upvotes: 0

Related Questions