0

我面临一个类似于 Tinder 匹配逻辑的问题,所以我以它为例。

在此处输入图像描述

我的用户可以通过具有两个用户引用的公共匹配实体在彼此之间进行“匹配”。

@Data
@Entity
@Table(name = "match")
@EqualsAndHashCode(callSuper = true)
public class Match extends PanacheEntity {

    @Column(name = "matchDate")
    Calendar matchDate;

    @ManyToOne
    @JsonIgnore
    User userA;

    @ManyToOne
    @JsonIgnore
    User userB;

  }
}

我喜欢对用户属于两个用户实体对象的所有匹配项进行单一引用,但是我需要选择(假设使用“mappedBy”)关系的另一端,即第一个或第二个用户。

@Data
@Entity
@Table(name = "user_")
@EqualsAndHashCode(callSuper = true)
public class User extends PanacheEntity {

    @Column(name = "email")
    String email;

    @Column(name = "name")
    String name;

    // Needs to contain all "Matches", no matter if the user is referenced as "A" or "B"
    @OneToMany
    List<Match> matches;
}

我希望列表匹配项填充以下查询表示的对象,即与用户相关的所有匹配项,与列无关。

select distinct match.id, user_a_id, user_b_id
from match,
     user_
where user_.id = match.user_a_id
   or user_.id = match.user_b_id

无论我是被邀请还是被邀请的人,都可以为我作为用户提供与我相关联的任何连接对象。

有没有办法使用 Hibernate 注释来实现它?

4

1 回答 1

1

可以@JoinColumn用来指定列名

联系

@Data
@Entity
@Table(name = "connection")
@EqualsAndHashCode(callSuper = true)
public class Connection extends PanacheEntity {

    @ManyToOne
    @JsonIgnore
    @JoinColumn(name = "inviter_id")
    User inviter;

    @ManyToOne
    @JsonIgnore
    @JoinColumn(name = "invited_id")
    User invited;
}

用户

@Data
@Entity
@Table(name = "user_")
@EqualsAndHashCode(callSuper = true)
public class User extends PanacheEntity {

    @Column(name = "email")
    String email;

    @Column(name = "name")
    String name;

    @OneToMany(mappedBy = "inviter")
    List<Connection> inviterConnections;
 
    @OneToMany(mappedBy = "invited")
    List<Connection> invitedConnections;
}

根据评论更新

您可以尝试如下所示@JoinColumnsConnection但它会给您和子句。

@JoinColumns(value = {
            @JoinColumn(name = "id", referencedColumnName = "inviter_id"),
            @JoinColumn(name = "id", referencedColumnName = "invited_id") })
User user;
于 2020-08-13T03:58:17.563 回答