2013-11-27 60 views
1

我只是想知道,實現了一個一對多的關係,如果你們能闡明什麼一些光,困惑我如何使用JPA

我有兩個表一個userdetails

create table usertable (
     username varchar(128) NOT NULL, 
     password varchar(128) NOT NULL 
); 

和一個addresses,我如何將它映射到JPA中,我可以讓一個用戶訪問多個地址,如何實現這一點,它是在創建表還是在類中完成?

感謝

EDITTTT

create table usertable (
     username varchar(128) NOT NULL CONSTRAINT USER_PK PRIMARY KEY , 
     password varchar(128) NOT NULL, 
firstaname varchar(30) NOT NULL, 
surname varchar(30) NOT NULL, 
gender varchar(6) NOT NULL, 
homenumber varchar(128) NOT NULL, 
mobilenumber varchar(128) NOT NULL, 
dob date NOT NULL, 
id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) 
); 


create table grouptable(
     username varchar(128) NOT NULL, 
     groupid varchar(128) NOT NULL, 
     CONSTRAINT GROUP_PK PRIMARY KEY(username, groupid), 
     CONSTRAINT USER_FK FOREIGN KEY(username) REFERENCES usertable(username) 
      ON DELETE CASCADE ON UPDATE RESTRICT 
    ); 

create table address(
username varchar(128) NOT NULL, 
       addressline1 varchar(128) NOT NULL, 
       addressline2 varchar(128) NOT NULL, 
       addressline3 varchar(128) NOT NULL, 
       country varchar(128) NOT NULL, 
       postcode varchar(9) NOT NULL, 
CONSTRAINT USER2_FK FOREIGN KEY(username) REFERENCES usertable(username) 
        ); 

回答

2

這可以在你的實體類指定。這是一個使用註釋的簡單例子。

@Entity 
public class UserDetail { 
    @Id 
    @Column(name="ID") 
    private long id; 
    ... 
    @OneToMany(mappedBy="userdetail") 
    private List<Address> addresses; 
    ... 
} 

@Entity 
public class Address { 
    @Id 
    private long id; 
    ... 
    @ManyToOne(fetch=FetchType.LAZY) 
    @JoinColumn(name="userdetail") 
    private UserDetail userdetail; 
    ... 
} 
+0

好的謝謝,有道理,在實際的數據庫設置是否需要設置外鍵等?或者只是兩張桌子,這是他們如何鏈接? – user2061913

+0

使用外鍵設置它是有意義的,地址將有一個名爲userdetail的列,它是userdetail表的id列的外鍵。 –

+0

我已經添加了當前用於上述數據表生成的代碼,如何在此處添加外鍵? – user2061913