繁体   English   中英

Hibernate批注映射到使用组合键的联接表

[英]Hibernate annotation mapping to joined table with composite key

我有一个实体,我想将OneToOne与带有复合键的表(省略getter / setter)结合在一起:

@Entity
@Table(name = "parent")
public class Parent {
  @Id
  private String parentId;
  @Column(name = "data")
  private String data;
  @OneToOne
  private Child child;
}

和:

@Entity
@IdClass(ChildKey.class)
@Table(name = "child")
public class Child{
  @Id
  private String parentId;
  @Id
  private String username;
  @Column(name = "data")
  private String childData;
}

public class ChildKey implements Serializable {
  private String parentId;
  private String username;
}

父级在子级实体中没有“用户名”字段的概念。 我需要将此作为标准。 在数据库中,child的主键位于parentId和username上。

如果我未指定JoinColumn,则休眠状态将尝试使用child_username和child_parentId字段进行映射。 如果仅指定一个Joincolumn,则会得到一个损坏的映射。 如果我同时指定了两个JoinColumns,则在父级上没有要指定的列。

如何映射该类并将用户名作为条件传递? (它来自身份验证数据),或者如果我偏离轨道,该如何以其他方式执行此操作。

您也许可以使用派生身份。

Parent类将保持不变; 但您需要指定一个@OneToOne映射回孩子的父对象, ChildChildKey类如下所示:

@Entity
@IdClass(ChildKey.class)
@Table(name = "child")
public class Child{
  @Id
  @OneToOne(mappedBy="child")
  private Parent parent;
  @Id
  private String username;
  @Column(name = "data")
  private String childData;
}

public class ChildKey implements Serializable {
  private String parent; // name matches name of the @Id field and type matches type of Parent @Id field
  private String username; // name and type match those of the @Id field
}

派生身份将在JPA 2.1规范的第2.4.1节中讨论。

我最终要做的是在Child类上定义一个@Filter,如下所示:

@Entity
@IdClass(ChildKey.class)
@Table(name = "child")
@FilterDef(name = "usernameFilter", parameters = {
        @ParamDef( name = "username", type="string")
})
public class Child { ... }

在Parent类上,我通过引用过滤器对集合进行了注释:

@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "parentId")
@Filter(name="usernameFilter", condition = "username = :username")
private List<Child> children;

最后,在我的DAO中,我按名称对过滤器进行了参数设置,如下所示:

Filter filter = currentSession().enableFilter("usernameFilter");
filter.setParameter("username", user.getUsername());

这样做产生了我想到的确切的SQL,这是JOIN标准中的一个带有变量的附加子句:

SELECT 
    ...
FROM
    parent this_
        LEFT OUTER JOIN
    child child_ ON this_.parentId = child_.parentId
        AND child_.username = ?

对于最初的问题,我可能一直不清楚最终的结果。 发布此答案,以防其他人受益。

暂无
暂无

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

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