简体   繁体   English

如何在Hibernate中使用两个表持久化自引用实体?

[英]How to persist self-referencing entity using two tables in Hibernate?

I'm having a small and weird issue using Hibernate. 我在使用Hibernate时遇到了一个小而奇怪的问题。 I have two tables: "SERVICE" & SERVICE_RELATIONSHIP that defines a relationship between two services. 我有两个表:“ SERVICE”和SERVICE_RELATIONSHIP,用于定义两个服务之间的关系。

CREATE TABLE TMS.TB_SERVICE ( 
    ID_SERVICE  INTEGER NOT NULL,
    NAME        VARCHAR(255),
)


CREATE TABLE SERVICE_RELATIONSHIP ( 
    ID_SERVICE      INTEGER NOT NULL,
    ID_SERVICE_REL  INTEGER NOT NULL,
    RELATIONSHIP    VARCHAR(1)  // Could be 'E' (Exclude) or 'I' (Include)
    )

I use different methods (getInclude and getExclude) in order to get services depending on the type of relationship that they have. 我使用不同的方法(getInclude和getExclude)来获取服务,具体取决于它们之间的关系类型。 They work perfect, the only problem is when I want to persist a service , ID_SERVICE & ID_SERVICE_REL columns are inserted correctly but not RELATIONSHIP . 它们工作完美,唯一的问题是当我要保留服务时 ,正确插入了ID_SERVICE和ID_SERVICE_REL列, 但没有插入RELATIONSHIP

@Table(name="SERVICE")
public class Service implements Serializable {
    private String name;
    private Integer id;
    private Collection<Service> exclude;
    private Collection<Service> include;
     [..]
    @JoinTable(name = "SERVICE_RELATIONSHIP", 
      joinColumns = {
        @JoinColumn(name="ID_SERVICE", unique = false, updatable = true)
      },
      inverseJoinColumns = {
        @JoinColumn(name="ID_SERVICE_REL")
      }
    )
    @WhereJoinTable(clause = "RELATIONSHIP='E'")
    public Collection<Service> getExclude() {
        return exclude;
    }

    [..] 
    @OneToMany(fetch=FetchType.EAGER)
    @JoinTable(name = "SERVICE_RELATIONSHIP",
      joinColumns = {
        @JoinColumn(name="ID_SERVICE", unique = false, updatable = true)           
      },
      inverseJoinColumns = {
        @JoinColumn(name="ID_SERVICE_REL")
      }
    )
    @WhereJoinTable(clause = "RELATIONSHIP='I'")
    public Collection<Service> getInclude() {
        return include;
    }
}

Any ideas? 有任何想法吗? Thanks in advance 提前致谢

@WhereJoinTable as the name describes, is only used for Where condition when doing a join on a select clause. @WhereJoinTable仅在对select子句进行@WhereJoinTable时用于Where条件。

You have a couple of options to implement this. 您有两种选择可以实现此目的。

  1. Map the relationship as a class. 将关系映射为一个类。
  2. Create an include and exclude tables. 创建一个包含和排除表。

Personally, I would map the relationship class, but I would keep it hidden from outside Service , so the code that uses service is not aware of the relationship class. 就个人而言,我将映射关系类,但是我将其隐藏在Service外部,因此使用service的代码不知道该关系类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM