Hibernate的多对多和超映射问题 [英] Hibernate ManyToMany and superclass mapping problem

查看:121
本文介绍了Hibernate的多对多和超映射问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要建立在Hibernate中的关系,连接三个表:调查结果显示,用​​户和组。
调查可以看到一个用户或组,以及集团是几个用户的形式。

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.

我的问题是,集团没有映射到一个表,而是一个视图,所以我不能几个表,如果我创建了一个共同的superclass-会发生哪位之间分裂集团的领域。

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将是集团或用户ID,并且类型......它的类型。
有谁知道如何使用Hibernate注解来实现呢?任何其他的想法?

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?

非常感谢

推荐答案

我贴一个非常<一个href=\"http://stackoverflow.com/questions/2912988/persist-collection-of-interface-using-hibernate/2918468#2918468\">similar回答昨天。总之,因为映射超不是一个实体,你不能使用映射超,不能关联的一部分(这是你想要什么),但你可以使用一个抽象的实体与 TABLE_PER_CLASS 继承策略,以获得类似的结果。

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.

像这样(未测试):

@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>();

    ...
}

参考

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆