JPA多對一單向關聯
阿新 • • 發佈:2018-03-05
單向關聯 com 使用 gpo false jpa log post 關聯
在實際開發過程中,JPA多對一單向關聯是使用最多的關聯方式。
下面是訂單與訂單項的配置關系。
訂單(Order):一的一方,不進行任何配置
- @Entity
- @Table(name="orders")
- public class Order {
- @Id
- @Column(length=40)
- private String orderId; //訂單ID
- @Column(nullable=false)
- private Float amount = 0f; //總價
- private Set<OrderItem> items;//訂單項(可有可無,查詢訂單時,無法查出此項)
- public String getOrderId() {
- return orderId;
- }
- public void setOrderId(String orderId) {
- this.orderId = orderId;
- }
- public Float getAmount() {
- return amount;
- }
- public void setAmount(Float amount) {
- this.amount = amount;
- }
- public Set<OrderItem> getItems() {
- return items;
- }
- public void setItems(Set<OrderItem> items) {
- this.items = items;
- }
訂單項(OrderItem):多的一方,進行ManyToOne關聯配置。
- @Entity
- public class OrderItem {
- @Id
- @GeneratedValue //ID自增長
- private Integer id;
- @Column(length=40,nullable=false)
- private String productName;
- @Column(nullable=false)
- private Float sellPrice;
- /*
- * @JoinColumn(name="order_id") 數據庫中外鍵的名字為order_id
- */
- @ManyToOne(cascade={CascadeType.MERGE,CascadeType.REFRESH},
- fetch=FetchType.EAGER,optional=false)
- @JoinColumn(name="order_id")
- private Order order;
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getProductName() {
- return productName;
- }
- public void setProductName(String productName) {
- this.productName = productName;
- }
- public Float getSellPrice() {
- return sellPrice;
- }
- public void setSellPrice(Float sellPrice) {
- this.sellPrice = sellPrice;
- }
- public Order getOrder() {
- return order;
- }
- public void setOrder(Order order) {
- this.order = order;
- }
JPA多對一單向關聯