2015-02-11 38 views
2

我想添加一個外鍵到模型,這可能與「@」符號....?玩框架:將外鍵添加到模型'@'?

所以,我有這兩種型號:

@Entity 
    public class NewEn extends Model{ 
     @Id 
     @GeneratedValue(strategy = GenerationType.AUTO) 
     public int Id; 

     public String name; 
     public String tags; 

     public String user_id; 
... 
} 

和:

@Entity 
public class NewUser extends Model{ 


    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    public int Id; 

    public String username; 
    public String first_name; 
    public String last_name; 
    public String email; 
    public String password; 

.... 
} 

而且我想:從尼文 'USER_ID' 是從主鍵(id)等於NewUser模型。 我該如何在模型中用@符號做到這一點?或者我怎樣才能將這些表格從我的代碼中取出,而不是從數據庫中取出?

+0

好吧,我想我在這裏找到答案:http://stackoverflow.com/questions/17981766/foreign-key-query但是,我會欣賞任何種類的(其他)解決方案.... – flori 2015-02-11 15:45:48

+0

我做了外鍵,但我的數據庫不會把用戶ID太:((... ...) – flori 2015-02-11 15:54:44

回答

2

那些以@開頭的詞是annotations。在這種情況下,這些是JPA annotations,用於將Java中的對象映射到數據庫中的表/行。

假設你正在試圖創建NEWUSER和尼文之間的1-N關係(即NEWUSER對象可以有許多尼文對象),你需要改變這樣的:

@Entity 
public class NewEn extends Model{ 
    // (...) 
    public String tags; 

    @ManyToOne 
    public NewUser user; 
    // (...) 
} 

,然後訪問來自給定NewEn的NewUser,您使用someNewEn.user。如果你想也能獲得所有與給定NEWUSER你指定在類文件相關聯的尼文對象:

@Entity 
public class NewUser extends Model{ 

    // (...) 
    public String password; 

    // mappedBy is the name of the field in NewEn that contains the foreign key 
    @OneToMany(mappedBy = "user") 
    public List<NewEn> newEns; 
    // (...) 
} 

需要注意的是,現在,如果你想在尼文關聯到NEWUSER你將有使用對象而不是簡單的ID。如果你需要使用ID,你只需要這樣做:

int userId = 345; 
User user = new User(); 
user.id = userId; 

someNewEnObject.user = user; 
someNewEnObject.save();