1 26 27 29 package de.nava.informa.impl.hibernate; 30 31 import java.util.Iterator ; 32 import java.util.List ; 33 34 import de.nava.informa.core.CategoryIF; 35 36 import net.sf.hibernate.Hibernate; 37 import net.sf.hibernate.HibernateException; 38 import net.sf.hibernate.Session; 39 import net.sf.hibernate.Transaction; 40 41 47 public class DemoCategoryHibernate { 48 49 public static void main(String [] args) throws Exception { 50 SessionHandler handler = SessionHandler.getInstance(); 51 Session session = handler.getSession(); 52 ChannelBuilder builder = new ChannelBuilder(session); 53 54 CategoryIF catA = builder.createCategory(null, "News Category"); 56 Long catId = null; 57 58 Transaction tx = null; 59 try { 60 tx = session.beginTransaction(); 61 session.save(catA); 62 tx.commit(); 63 catId = new Long (catA.getId()); 64 System.out.println("Saved category with id " + catId + " persistently"); 65 } 66 catch (HibernateException he) { 67 if (tx != null) tx.rollback(); 68 throw he; 69 } 70 finally { 71 session.close(); 72 } 73 74 session = handler.getSession(); 76 try { 77 tx = session.beginTransaction(); 78 Category theCat = (Category) session.load(Category.class, catId); 79 theCat.setTitle("Another category title"); 80 tx.commit(); 81 System.out.println("Updated category title for id: " + catId); 82 } catch (HibernateException he) { 83 if (tx != null) tx.rollback(); 84 throw he; 85 } 86 finally { 87 session.close(); 88 } 89 90 session = handler.getSession(); 92 try { 93 tx = session.beginTransaction(); 94 List cats = session.find("from Category as cat where cat.title = ?", 97 "Another category title", Hibernate.STRING); 98 tx.commit(); 99 Iterator it = cats.iterator(); 100 while (it.hasNext()) { 101 Category c = (Category) it.next(); 102 System.out.println("--> " + c.getId()); 103 } 104 } catch (HibernateException he2) { 105 if (tx != null) tx.rollback(); 106 throw he2; 107 } 108 finally { 109 session.close(); 110 } 111 } 112 113 } 114 | Popular Tags |