我有一个用户模型,我希望包含一个"朋友列表":
@Entity
public class User extends Model {
@Id
public long id;
@ManyToMany
public List<User> friends;
...
}
运行它会给我一个错误(Database 'default' is in an inconsistent state
)和一个包含下表的进化文件:
create table user_user (
user_id bigint not null,
user_id bigint not null,
constraint pk_user_user primary key (user_id, user_id)
)
我该如何解决这个问题?另外,对于奖励积分,我如何获得与我的用户成为朋友的人员列表?
答案 0 :(得分:4)
我不建议将ManyToMany用于实际项目中的self实体。最好创建另一个表,比如“友谊”。看看这个问题的答案:Many-to-many on the same table with additional columns
任何方式,这里都是你问题的答案:
您需要“通过武器”配置连接表
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;