views:

49

answers:

1

Hi, I have mapped class in JPA. :

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class User {
    private Long id;
    private Long name;
    //getters and setters go here
    ....
}

I also have a subclass of this class, called Admin:

@Entity
public class Admin extends User {
    private String cridentials;
    //getters and setters go here
    ....
}

Now in my code I have managed instance of User attached to the session

...
User user = entityManager.find(User.class, userId)

I need to transform this user to its subclass, Admin. This means I need 'User' table data remain untouched and new row to be inserted into 'Admin' table:

javax.persistence.EntityManager entityManager = ...;
...
User user = entityManager.find(User.class, userId)
Admin admin = new Admin();
admin.setName(user.getName());

entityManager.persist(admin);

But after I execute the last line, another row is inserted in both User and Admin tables. How would I solve this?

The only way I found so far is to save the fields of a User somewhere, then delete this instance from DB, and then create new Admin with all the data from User class. But I bet there is much better way of doing this.

Thanks

+1  A: 

(...) But after I execute the last line, another row is inserted in both User and Admin tables. How would I solve this?

Well, you created a new instance of Admin and called persist on it so this is exactly what you told Hibernate to do. Try to downcast the fetched User instance as Admin instead (not tested).

But there is IMO something broken with your design, you should assign some kind of role instead of using inheritance here.

Pascal Thivent
Actually, Admin has many properties that User shouldn't have - that's why I use inheritance. User can't be downcasted to Admin, so 'Admin a = (Admin) user;'doesn't work here... The problem that User is not abstract, it is used by the system as well as Admin. However, I can't 'tell' hibernate to create new Admin from current User - even when I set Admin's ID to User's one and try to merge, it say that Admin is not managed.
denis_k