4

I have a User class, which extends Model, and two classes that I want to extend the User class.

User.java:

@Entity
@Table(name = "users")
public class User extends Model implements RoleHolder {

    private static final long serialVersionUID = 1L;

    @Id
    public Long id;

...

Driver.java:

public class Driver extends User {
...

Customer.java:

public class Customer extends User {
...

Edit All three entities need to be directly accessed. To say it another way, I have Users, Customers, and Drivers; Customers and Drivers just happen to share all of the properties of a User. Therefore, I need to have a valid User entity as well as Customer and Driver.

I need to be able to get a list of all Users (including Customers and Drivers).

I haven't been able to figure out how to make this work using ebean in Play. How can I do this?

Matt
  • 14,906
  • 27
  • 99
  • 149
Ben Carlson
  • 762
  • 8
  • 18
  • Sorry but what's the problem exactly? what do you mean by you can't use the User directly? – emt14 Nov 19 '12 at 06:46

2 Answers2

3

This might be an use case for the MappedSuperClass annotation. See http://docs.oracle.com/javaee/5/api/javax/persistence/MappedSuperclass.html for documentation. Presumably, this is suppoerted by Ebean, although there's a lack of documentation about it.

Samuel
  • 1,667
  • 12
  • 18
  • 1
    Thanks Samuel, unfortunately, MappedSuperClass doesn't allow the User entity to exist. It's the perfect solution if I only needed to access the subclasses though! – Ben Carlson Nov 19 '12 at 15:24
  • Then have a `AbstractUser` superclass (MappedSuperClass) and `User` as well as the others inherit from it -- It's not clear to me why you would absolutely need to have `User` as such also. – Samuel Nov 19 '12 at 15:30
  • The problem with the AbstractUser class as you suggest is that if I want a complete list of Users, I have to do three queries, one for Users, one for Customers and one for Drivers. In my model, a Customer IS a User, and a Driver IS a User. – Ben Carlson Nov 19 '12 at 15:41
  • I've added a new answer for that case :-) – Samuel Nov 19 '12 at 15:54
3

To keep the User table concrete, you can use the @Inheritance annotation. See Play Framework 2 Ebean and InheritanceType as JOINED for a discussion about that.

Also possible is to manually join auxiliar tables for Drivers and Customers using @OneToOne.

Using @OneToOne would also be favor composition over inheritance, which is considered a good practice.

Community
  • 1
  • 1
Samuel
  • 1,667
  • 12
  • 18
  • 1
    Thanks Samuel, I tried the `@Inheritance` track before finding the `@OneToOne`. I went that route, and my problems are solved. Thanks! – Ben Carlson Nov 20 '12 at 02:42