|
| 1 | +package com.baeldung.hibernate.oneToMany.main; |
| 2 | + |
| 3 | +import java.util.HashSet; |
| 4 | +import java.util.Set; |
| 5 | + |
| 6 | +import org.hibernate.Session; |
| 7 | +import org.hibernate.SessionFactory; |
| 8 | +import org.hibernate.Transaction; |
| 9 | + |
| 10 | +import com.baeldung.hibernate.model.Cart; |
| 11 | +import com.baeldung.hibernate.model.Items; |
| 12 | +import com.baeldung.hibernate.config.HibernateAnnotationUtil; |
| 13 | + |
| 14 | +public class HibernateOneToManyAnnotationMain { |
| 15 | + |
| 16 | + public static void main(String[] args) { |
| 17 | + |
| 18 | + Cart cart = new Cart(); |
| 19 | + cart.setName("MyCart"); |
| 20 | + |
| 21 | + Items item1 = new Items("I10", 10, 1, cart); |
| 22 | + Items item2 = new Items("I20", 20, 2, cart); |
| 23 | + Set<Items> itemsSet = new HashSet<Items>(); |
| 24 | + itemsSet.add(item1); itemsSet.add(item2); |
| 25 | + |
| 26 | + cart.setItems(itemsSet); |
| 27 | + cart.setTotal(10*1 + 20*2); |
| 28 | + |
| 29 | + SessionFactory sessionFactory = null; |
| 30 | + Session session = null; |
| 31 | + Transaction tx = null; |
| 32 | + try{ |
| 33 | + //Get Session |
| 34 | + sessionFactory = HibernateAnnotationUtil.getSessionFactory(); |
| 35 | + session = sessionFactory.getCurrentSession(); |
| 36 | + System.out.println("Session created"); |
| 37 | + //start transaction |
| 38 | + tx = session.beginTransaction(); |
| 39 | + //Save the Model object |
| 40 | + session.save(cart); |
| 41 | + session.save(item1); |
| 42 | + session.save(item2); |
| 43 | + //Commit transaction |
| 44 | + tx.commit(); |
| 45 | + System.out.println("Cart ID="+cart.getId()); |
| 46 | + System.out.println("item1 ID="+item1.getId()+", Foreign Key Cart ID="+item1.getCart().getId()); |
| 47 | + System.out.println("item2 ID="+item2.getId()+", Foreign Key Cart ID="+item1.getCart().getId()); |
| 48 | + |
| 49 | + }catch(Exception e){ |
| 50 | + System.out.println("Exception occured. "+e.getMessage()); |
| 51 | + e.printStackTrace(); |
| 52 | + }finally{ |
| 53 | + if(!sessionFactory.isClosed()){ |
| 54 | + System.out.println("Closing SessionFactory"); |
| 55 | + sessionFactory.close(); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments