如何定义同一模型的多对多关系?

How to define a ManyToMany relationship of the same model?

我有一个用户模型,我想包含 "friends":

的列表
@Entity 
public class User extends Model {

  @Id
  public long id; 

  @ManyToMany
  public List<User> friends;

  ...
}

运行 这给了我一个错误 (Database 'default' is in an inconsistent state) 和一个包含以下 table:

的进化文件
create table user_user (
    user_id                        bigint not null,
    user_id                        bigint not null,
    constraint pk_user_user primary key (user_id, user_id)
)

我该如何解决这个问题?另外对于奖励积分,我怎样才能得到我用户的好友列表?

我不建议在实际项目中对自身实体使用ManyToMany。最好创建另一个 table,例如 "Friendship"。查看此问题的答案:Many-to-many on the same table with additional columns

无论如何,这里是您问题的确切答案:

您需要配置加入table"by arms"

package models;

import java.util.*;
import javax.persistence.*;

import com.avaje.ebean.Model;

@Entity
public class User extends Model {

  @Id
  public long id;

  @ManyToMany(targetEntity=User.class)
  @JoinTable(name="friends",
      joinColumns={@JoinColumn(name="user_a_id", referencedColumnName="id")},
      inverseJoinColumns={@JoinColumn(name="user_b_id", referencedColumnName="id")}
  )
  public List<User> friends;
}

自动生成的进化脚本:

create table user (
  id                        bigint not null,
  constraint pk_user primary key (id))
;


create table friends (
  user_a_id                      bigint not null,
  user_b_id                      bigint not null,
  constraint pk_friends primary key (user_a_id, user_b_id))
;
create sequence user_seq;




alter table friends add constraint fk_friends_user_01 foreign key (user_a_id) references user (id) on delete restrict on update restrict;

alter table friends add constraint fk_friends_user_02 foreign key (user_b_id) references user (id) on delete restrict on update restrict;

# --- !Downs

SET REFERENTIAL_INTEGRITY FALSE;

drop table if exists user;

drop table if exists friends;

SET REFERENTIAL_INTEGRITY TRUE;

drop sequence if exists user_seq;