Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: converting instance of subclass to instance of superclass

Let's say I've got a class called User and a class ExtendedUser, which is a subclass of User. Both classes are mapped using hibernate (JPA) annotations:

User:

@Entity
@Table("user-table")
@Inheritance(strategy = InheritanceType.JOINED)
public class User {

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Integer id;

    @Column(name = "name")
    private String name;

}

ExtendedUser:

@Entity
@Table(name = "extended-user-table")
@PrimaryKeyJoinColumn(name="id")
public class ExtendedUser extends User{

    @Column(name = "username")
    private String username;

    @Column(name = "password")
    private String password;

}

Sometimes a user needs to be promoted to an ExtendedUser; similarly an ExtendedUser sometimes needs to be demoted to a User.

First question: is there any way in hibernate to perform this directly?

Not being able to find such a way I tried to do the following (example for demoting):

  1. Copy the fields over from the ExtendedUser instance to a new instance of User.
  2. Delete the ExtendedUser instance
  3. Save the User instance

However, this seems to automatically increment the id when trying to save the new User. All of this is being done in a transaction - could that be the cause? However, I do not want to take them outside of the transaction, since then automatic rollback will not work if, say, the save fails.

Second question (in case the answer to the first one is no): how do I fix the issue of IDs automatically incrementing.

Thanks in advance.

like image 429
Domas Poliakas Avatar asked Nov 18 '13 09:11

Domas Poliakas


1 Answers

I think the issue should be solved on the OOD and not so much on the DB level. What you did is a nice shortcut that works – as long as you don't try to do what you try to do.

I would remove the Login credentials into their own class "Login" and leave the User as it is. Instead of promoting a User to ExtendedUser, just add a Login and be done with it. Each user with a relation to Login is an "ExtendedUser".

See also: https://stackoverflow.com/a/3246244/2615437.

like image 163
xwoker Avatar answered Nov 14 '22 12:11

xwoker