1 Reply Latest reply on Aug 3, 2005 6:21 PM by epbernard

    relations and composite keys

      I'm trying to write an EJB3 application that has a one to many relationship. Unfortunately, there is no surrogate id on the many side. The schema looks like this:

      Table ORDERS has PK ORDERID

      Table ORDERLINES as FK ORDERID and local id ORDERLINEID. However, ORDERLINEID is not a key for the table. It's just the line number in the order. (line 1, line 2, etc..)

      This is easy enough to map. The OrderLine object has an @EmbeddedId representing the composite ORDERID/ORDERLINEID. This maps fine.

      The OrderLine object also can map the Order relation, but I have to mark it as not updatable:

       @ManyToOne
       @JoinColumn(name="ORDERID",updatable=false,insertable=false)
       public Order getOrder() {
       return order;
       }
       public void setOrder(Order order) {
       this.order = order;
       }
      


      This also works, but it leaves me in the position of having to set both the order and the orderid fields. This becomes problematic when creating a new order object since the new order object has no id. I'm forced to manage all of this at a low level with the entity manager:
       Order order = new Order();
       // fill in some field
       em.persist(order); // make sure we get the id
      
       // ...
       for (OrderLine line: lines) {
       // fill in line details
       line.getPk().setOrderId(order.getOrderId());
       line.setOrder(order);
       }
      


      Ideally I'd like not to have to manage the persistence so tightly. If this were a normal relationship, I could simply add the orderlines to the order and let the entity manager manage everything.

      Is there a better way to manage this type of relation? Am I stuck until I can get the schema updated to use a surrogate key?