8

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I recognise the problem now (I couldn't find any related posts before posting the question somehow), and I brought it up with my superior; hopefully I will get the permission to make necessary changes to the schema. Additionally, for those who might come across this - the following link might help with understanding the problem as well: stackoverflow.com/a/7457178/2936471

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.