2015-10-05 64 views
2

我有一個用戶模式,我想包含的「朋友」名單,其中:如何定義同一模型的ManyToMany關係?

@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

那麼,這就是答案。你只需要應用進化。朋友列表是用戶對象「朋友」列表。 – Gus

+0

aahh..there有一些時髦與我的配置。這似乎工作! – Martyn

回答

3

我不推薦在實際項目中使用ManyToMany自我實體。最好創建另一個表格,比如「友誼」。看對這個問題的答案: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; 
相關問題