OpenJPA:使用新实体列表保留新实体

时间:2014-07-06 19:05:42

标签: jpa one-to-many openjpa

我有以下型号:A * - > B.(onedirectional onetomany)

当我检索A时,创建一个新的B,将该B添加到A,持久化A并提交事务。 B保存正确。

然而,当我创建一个新的A,创建一个新的B,将该B添加到A,持久化A并提交事务。 B被保存,但是表B中到表A的外键没有填写。(因此A和B之间的关系不会被保留)

任何人都可以解释我的错误吗?

@Entity
@Table(name="`ORDER`")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @JoinColumn(name="FK_ORDER_ID", referencedColumnName = "ID")
    @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    public List<ProductOrder> productOrders = new ArrayList<>();

    public Order(){}
}

public class ProductOrder {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    public ProductOrder(){}
}

//调用代码

@Path("/orders")
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class OrderResource { 

     @PersistenceContext
     private EntityManager entityManager;

     @Path("/make")
     @POST
     @Consumes(MediaType.APPLICATION_JSON)
     public Response makeOrder(){
         Order o = new Order();
         o.productOrders.add(new ProductOrder());
         entityManager.persist(o);
         //result The order and the productOrder are saved in the database, but the             foreign key to order in the productOrder tabel is not filled in
     }

     @Path("/updateForTesting")
     @POST
     @Consumes(MediaType.APPLICATION_JSON)
     public Response updateOrder(String orderId){
         Order o = entityManager.find(Order.class, orderId);
         o.productOrders.add(new ProductOrder());
         entityManager.persist(o);
         //result The productOrder is saved to the database with the foreign key filled in
     }
}

1 个答案:

答案 0 :(得分:-1)

正确的是:创建一个新的A,创建一个新的B,坚持B(并检索它),将该B添加到A,坚持A