Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.model.manegers; import com.util.HibernateUtil; import static com.util.HibernateUtil.getSessionFactory; import com.util.Products; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; /** * * @author Khalil Sharkawi */ public class Product_maneger { public static List<Products> getProducts() { Session session = getSessionFactory().openSession(); List<Products> l = session.createQuery("FROM Products").list(); // session.close(); return l; } public static void AddProduct(Products p) { Transaction trs = null; Session session = getSessionFactory().openSession(); try { trs = session.beginTransaction(); session.save(p); session.getTransaction().commit(); } catch (RuntimeException e) { if (trs != null) { trs.rollback(); } } finally { session.flush(); session.close(); } } public static void DeleteProduct(int id) { Products myObject; Transaction trs = null; Session session = getSessionFactory().openSession(); try { trs = session.beginTransaction(); myObject = (Products) session.load(Products.class, new Integer((int) id)); session.delete(myObject); session.getTransaction().commit(); } catch (RuntimeException e) { if (trs != null) { trs.rollback(); } } finally { session.flush(); session.close(); } } public static void updateProduct(Products pro) { Transaction trns = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { trns = session.beginTransaction(); // Products lolo = new Products(); lolo.setId(pro.getId()); lolo.setName(pro.getName()); lolo.setAvailableAmount(pro.getAvailableAmount()); lolo.setUnit(pro.getUnit()); lolo.setDiscription(pro.getDiscription()); // session.saveOrUpdate(lolo); session.getTransaction().commit(); } catch (RuntimeException e) { if (trns != null) { trns.rollback(); } e.printStackTrace(); } finally { session.flush(); session.close(); } } public static Products getByid(int id) { Products myObject = null; Transaction trs = null; Session session = getSessionFactory().openSession(); try { // trs = session.beginTransaction(); myObject = (Products) session.load(Products.class, new Integer((int) id)); // session.delete(myObject); // session.getTransaction().commit(); } catch (RuntimeException e) { if (trs != null) { // trs.rollback(); } } finally { session.flush(); session.close(); return myObject; } } }