休眠:两个OneToMany属性,由同一实体使用不同的列映射 [英] Hibernate: Two OneToMany properties, mapped by the same entity with different columns

查看:60
本文介绍了休眠:两个OneToMany属性,由同一实体使用不同的列映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这可以通过HQL查询轻松解决,但是我更喜欢让Hibernate为我处理一些OneToMany属性.

让我演示我希望我的域模型在伪代码中是什么样子:

Game
  Long GameID
  Team HomeTeam
  Team AwayTeam
  @OneToMany(mappedBy="team")
  Set<TeamPlay> HomeTeamPlays
  @OneToMany(mappedBy="team")
  Set<TeamPlay> AwayTeamPlays

表的结构类似,有两个外键都指向Game表上的Team表.显然,如果只有一个外键,那么它将表示真正的一对多关系,但实际上,我想要的是针对同一实体子类型的两个双向一对多属性.

我不相信使用@Where注释会有效,因为它需要一个常量,并且这里不允许使用@JoinColumn.如果不可能,那没关系,我只是想从其他人这里得到.

解决方案

我敢打赌,您真的不了解对appedBy的使用.

您可以在 https://stackoverflow.com/a/13812047/395202 中参考我的其他答案

简而言之,mappedBy是双向关系相对侧"中的属性名称.

对于您来说,它可能看起来像:

class TeamPlay {
    @ManyToOne
    Team homeTeam;

    @ManyToOne
    Team awayTeam;
}

class Team {
    @OneToMany(mappedBy="homeTeam")
    Set<TeamPlay> homeTeamPlays;

    @OneToMany(mappedBy="awayTeam")
    Set<TeamPlay> awayTeamPlays;
}

I know that this can be easily solved with an HQL query, however I prefered to simply have Hibernate handle this with a few OneToMany properties for me.

Let me demonstrate what I want my domain model to look like in pseudo-code:

Game
  Long GameID
  Team HomeTeam
  Team AwayTeam
  @OneToMany(mappedBy="team")
  Set<TeamPlay> HomeTeamPlays
  @OneToMany(mappedBy="team")
  Set<TeamPlay> AwayTeamPlays

The table structure is similar, there are two foreign keys that both point to the Team table on the Game table. Clearly if there were only one foreign key then it would represent a true One-To-Many relationship but in reality what I want is two bi-directional One-To-Many properies for the same entity child type.

I don't believe using the @Where annotation will work as it requires a constant, and @JoinColumn is not allowed here. If it is not possible then that is okay, I just wanted to here it from somebody else.

解决方案

I bet you don't really understand the use of mappedBy.

You may refer to my other answer in https://stackoverflow.com/a/13812047/395202

In short, mappedBy is the property name in the "opposite side" of a bi-directional relationships.

For you case, it probably look something like:

class TeamPlay {
    @ManyToOne
    Team homeTeam;

    @ManyToOne
    Team awayTeam;
}

class Team {
    @OneToMany(mappedBy="homeTeam")
    Set<TeamPlay> homeTeamPlays;

    @OneToMany(mappedBy="awayTeam")
    Set<TeamPlay> awayTeamPlays;
}

这篇关于休眠:两个OneToMany属性,由同一实体使用不同的列映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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