开发者

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 betwe开发者_如何学编程en 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


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

  • Annotations, inheritance and interfaces
  • using MappedSuperclass in relation one to many
  • Polymorphic association to a MappedSuperclass throws exception


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜