views:

22

answers:

2

UPDATE: after posting, I discovered this is a duplicate of this older question.


I have an odd business requirement: my application supports users getting started as "Guests", then later registering to become "Registered" users.

Guests are feature-restricted: they are not allowed to access some functionality that is available once they register. However, they do have access to a subset of features, and may begin to accumulate persistent data before registering. Many of these features would be modeled as methods on a User entity class, and the accumulated data would naturally be associated via the GuestUser's @Id.

Hence, I'm contemplating modeling this in JPA/Hibernate as a polymorphic Entity type:

            User
             ^
             |
      +-------------+
      |             |
   GuestUser  RegisteredUser

I've mapped this using a boolean discriminator column; no problem:

@DiscriminatorColumn(name="guest", discriminatorType=DiscriminatorType.INTEGER)

This works fine until a GuestUser decides to "register" ...?!

Now I'd like to transform my GuestUser into a RegisteredUser, by setting

    guestUser.guest = false;

The result this transformation would logically be to purge the GuestUser object from existence, and then fetch an equivalent RegisteredUser with the same ID and shared fields from the inherited User mappings.

Is this possible? Could I perhaps use entityManager.refresh() somehow to achieve the desired result? Could I alternatively create a RegisteredUser instance and manually assign its ID to the value from the existing GuestUser? (This ID-assignment idea seems problematic, as our legacy database requires GenerationType.AUTO.)

A: 

Have you tried changing the guest flag, saving the change, and then loading a fresh object from the database with the same User.ID ?

matt b
A: 

Prefer delegation to inheritance. It's better design anyway and easier to map in a way that deals with this change cleanly.

Rather than distinguishing by subtype, create a role which can be reassigned when you want to change what they can access.

Don Roby