Jesus Benito
Jesus Benito

Reputation: 386

Hibernate ManyToMany and superclass mapping problem

I need to create a relation in Hibernate, linking three tables: Survey, User and Group. The Survey can be visible to a User or to a Group, and a Group is form of several Users.

My idea was to create a superclass for User and Group, and create a ManyToMany relationship between that superclass and Survey.

My problem is that Group, is not map to a table, but to a view, so I can't split the fields of Group among several tables -which would happen if I created a common superclass-.

I thought about creating a common interface, but mapping to them is not allowed. I will probably end up going for a two relations solution (Survey-User and Survey-Group), but I don't like too much that approach.

I thought as well about creating a table that would look like:

  Survey Id  |  ElementId  | Type

ElementId would be the Group or UserId, and the type... the type of it. Does anyone know how to achieve it using hibernate annotations? Any other ideas?

Thanks a lot

Upvotes: 1

Views: 2529

Answers (3)

Pascal Thivent
Pascal Thivent

Reputation: 570585

I posted a very similar answer yesterday. To summarize, you can't use a mapped superclass because a mapped superclass is not an entity and can't be part of an association (which is what you want) but you can use an abstract Entity with a TABLE_PER_CLASS inheritance strategy to obtain a similar result.

Something like this (not tested):

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractEntity {
    @Id @GeneratedValue(strategy = GenerationType.TABLE)
    private Long id;

    @ManyToMany(mappedBy="entities")
    private Set<Survey> surveys = new HashSet<Survey>();
    ...

}

@Entity
public class User extends AbstractEntity {
    ...
}

@Entity
public class Group extends AbstractEntity {
    ...
}

@Entity
public class Survey {
    @Id @GeneratedValue
    private Long id;

    @ManyToMany
    private Set<AbstractEntity> entities = new HashSet<AbstractEntity>();

    ...
}

References

Upvotes: 1

Alexander Torstling
Alexander Torstling

Reputation: 18908

This is possible. Such an 'inherited properties' approach can be achieved by defining the superclass as a MappedSuperclass.

EDIT:

There is also some alternatives listed in section 2.2.4 in the hibernate annotations reference doc, section 2.2.4.4 covers MappedSuperclass.

Upvotes: 0

shipmaster
shipmaster

Reputation: 3974

You can use the table per concrete class inheritance strategy, hibernate will replicate all properties for each subclass, this will work with a view.

I would also suggest the composite pattern for users/groups (which is close to your first option).

http://en.wikipedia.org/wiki/Composite_pattern

Upvotes: 0

Related Questions