`
xzcgeorge
  • 浏览: 31451 次
  • 性别: Icon_minigender_1
  • 来自: 珠海
社区版块
存档分类
最新评论

JPA one to many

 
阅读更多

1. one to many:

1.1 db tables:
CREATE TABLE customer
(
   customer_id   bigint NOT NULL,
   adresse       VARCHAR (255) NOT NULL,
   city          VARCHAR (255) NOT NULL,
   name          VARCHAR (255) NOT NULL,
   phone         VARCHAR (255) NOT NULL,
   state         VARCHAR (255) NOT NULL,
   tax_id        INTEGER NOT NULL,
   zip           VARCHAR (255) NOT NULL,
   PRIMARY KEY (customer_id)
);


CREATE TABLE customer_order
(
   order_id        bigint NOT NULL,
   date_placed     DATE NOT NULL,
   date_promised   DATE,
   status          VARCHAR (255) NOT NULL,
   terms           VARCHAR (255) NOT NULL,
   customer_id     bigint,
   PRIMARY KEY (order_id)
);

ALTER TABLE customer_order ADD CONSTRAINT FK86DB8BAD595591FB FOREIGN KEY (customer_id) REFERENCES customer


1.2  Customer class ( one side)
   @OneToMany(mappedBy = "customer",cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<CustomerOrder> CustomerOrders;


1.3  CustomerOrder ( many side )

    @ManyToOne(fetch=FetchType.EAGER)  //fetch=FetchType.LAZY or EAGER
    @JoinColumn(name="customer_id")
    //@Fetch(FetchMode.JOIN)
    private Customer customer;

Keys:  a.   cascade -> ALL:   save customer will also save orders of it.
       b.   fetch = FetchType.LAZY: lazy loading, if you want the order loaded with customer, you have
           to access it like this:

               public Customer getCustomerAndOrdersById(Long id) {

                   Customer customer = customerDao.getById(id);
                   for (CustomerOrder c : customer.getCustomerOrders())
                       ;    // no n+1 issue.
               }

       c. If fetch = FetchType.EAGER: no problem. It is alway loaded with customer loading.

1.4  If you remove the  ,cascade = CascadeType.ALL, you have to save both customer and his orders
     manually, and load them separately.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics