Insert one-to-many relation using hibernate [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
开发者_Go百科 Improve this questionWhat is the best way to insert data using Hibernate? As a example when I wont to insert new Order into order table. It has one-to-many relationship with Item. when we consider it on Object manner Order object has Item collection. Should I need to populate all variables(itemName,ItemId,ItemSize,, ) in Item object collection ? If you can please give me the code sample on insert Order using hibernate session..
@Entity
@Table(name="orders")
class Order {
@Id @GeneratedId private Long id;
@OneToMany(mappedBy="order")
private List<Item> items;
public Order() {
items = new ArrayList<Item>();
}
public void addItem(Item item) {
if (item != null)
items.add(item);
}
/* getters setters */
}
and item:
@Entity
@Table(name="items")
class Item {
@Id @GeneratedId private Long id;
@ManyToOne
private Order order;
/* getters setters */
}
to query:
Query query = query.createQuery("from Order o where o.id=:id");
query.setLong("id", 1234L);
List<Order> orders = query.list();
to insert could like this:
Session session = null;
try {
session = HibernateUtils.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
Order order = new Order();
Item item = new Item();
item.setQuantity(1);
/* etc.. */
order.addItem(item);
item.setOrder(order);
session.save(item);
session.save(order);
tx.commit();
} finally {
if (session.isOpen())
session.close();
}
Normally you should create your Item object and set the reference to the Order, since in the general case the Item is the owning side of the relation (assuming a birectional association and that you don't want to use a mapping table).
Besides that, can you give more information on what you have already (especially your Order and Item entities) or where exactly your problem is?
精彩评论