1. 程式人生 > >JPA單項一對多外來鍵關聯

JPA單項一對多外來鍵關聯

一對多即一個物件中包含又另外一個物件的集合。
User主表程式碼

@Table(name="USER")
@Entity
public class User {
    private Integer id;
    private String username;
    private String userpassword;
    private String useraddress;

    private List<Order> listOrder;

    @JoinColumn(name="LIST_ORDER")
    @OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.REMOVE)
    public
List<Order> getListOrder() { return listOrder; } public void setListOrder(List<Order> listOrder) { this.listOrder = listOrder; } @Id @TableGenerator(name="PK_PRIMARY", table="order_user_sque", pkColumnName="pk_column_name", pkColumnValue="pk_column"
, valueColumnName="pk_column_value", allocationSize=1) @GeneratedValue(strategy=GenerationType.TABLE,generator="PK_PRIMARY") public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name="USERNAME") public String getUsername
() { return username; } public void setUsername(String username) { this.username = username; } @Column(name="USERPASSWORD") public String getUserpassword() { return userpassword; } public void setUserpassword(String userpassword) { this.userpassword = userpassword; } @Column(name="USERADDRESS") public String getUseraddress() { return useraddress; } public void setUseraddress(String useraddress) { this.useraddress = useraddress; } }

程式碼中:@JoinColumn(name="LIST_ORDER") -> 表示將外來鍵名設定為LIST_ORDER
@OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.REMOVE) -> OneToMany中fetch表示查詢時的載入模式[懶載入還是積極載入],cascade屬性表示要級聯操作的模式,此處為刪除主表後從表一併刪除。

Order從表程式碼

@Entity
@Table(name="ORDER_USER")
public class Order {
    private Integer id;
    private String orderName;
    //private User user;

    @Id
    @GeneratedValue
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getOrderName() {
        return orderName;
    }
    public void setOrderName(String orderName) {
        this.orderName = orderName;
    }
}