Example usage for org.hibernate SessionFactory close

List of usage examples for org.hibernate SessionFactory close

Introduction

In this page you can find the example usage for org.hibernate SessionFactory close.

Prototype

void close() throws HibernateException;

Source Link

Document

Destroy this SessionFactory and release all resources (caches, connection pools, etc).

Usage

From source file:org.xchain.framework.hibernate.HibernateLifecycle.java

License:Apache License

private static void close(SessionFactory sessionFactory) {
    if (sessionFactory != null) {
        try {//from  ww  w .j  av  a  2s  .c om
            sessionFactory.close();
        } catch (Throwable e) {
            if (log.isWarnEnabled()) {
                log.warn("A hibernate session factory could not be closed.", e);
            }
        }
    }
}

From source file:OTS.Servlets.ApplicationListener.java

private void closeSessionFactory(SessionFactory factory) {
    if (factory instanceof SessionFactoryImpl) {
        SessionFactoryImpl sf = (SessionFactoryImpl) factory;
        ConnectionProvider conn = sf.getConnectionProvider();
        if (conn instanceof C3P0ConnectionProvider) {
            ((C3P0ConnectionProvider) conn).close();
        }//from   w w  w.  j  av  a  2  s  . c  om
    }
    factory.close();
}

From source file:persistence.DBUtility.java

public static void initializeUsers() {
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();

    Transaction tx = null;/*from  w w  w.j a va 2s . c  om*/

    try {
        tx = session.beginTransaction();
        //
        //            PMUser demoUser = new PMUser("song", "song");
        //            PMGroup defaultGroup = new PMGroup("default");
        //
        //            demoUser.getGroups().add(defaultGroup);
        //
        //            session.save(demoUser);
        //            
        Verantwortlicher v1 = new Verantwortlicher();
        v1.setName("Keiner");
        v1.setFarbcode(Utility.convertColorToColorString(Color.RED));

        LegacySystem s1 = new LegacySystem();
        s1.setName("SAP");

        Prozessschritt p1 = new Prozessschritt("P1", v1);
        p1.getSysteme().add(s1);

        session.save(p1);

        session.flush();
        tx.commit();

    } catch (HibernateException he) {
        if (tx != null) {
            tx.rollback();
            he.printStackTrace();
        } else {
            he.printStackTrace();
            throw he;
        }
    } finally {
        try {
            session.close();
        } catch (HibernateException he) {
            he.printStackTrace();
        }
    }

    sessionFactory.close();
}

From source file:proy.gui.Main.java

License:Mozilla Public License

@Override
public void start(Stage primaryStage) {
    //Analizar parmetros de entrada
    verParametros(getParameters().getRaw());

    //Inicializar parametros
    this.primaryStage = primaryStage;
    presentador = new PresentadorVentanas();

    //Iniciar el stage en el centro de la pantalla
    primaryStage.centerOnScreen();//ww  w .j  a  va 2 s .  co  m

    //Setear icono y titulo de aplicacion
    primaryStage.getIcons().add(new IconoAplicacion());
    primaryStage.setTitle("Aplicacion Romano");

    //Setear accin de cierre
    primaryStage.setOnCloseRequest((e) -> {
        if (!apilador.sePuedeSalir()) {
            e.consume();
        } else {
            SessionFactory sessionFact = (SessionFactory) appContext.getBean("sessionFactory");
            sessionFact.close();
        }
    });

    iniciarHibernate();
}

From source file:proy.gui.Main.java

License:Mozilla Public License

private void iniciarHibernate() {
    //Crear ventana de espera
    VentanaEsperaBaseDeDatos ventanaEspera = presentador.presentarEsperaBaseDeDatos(primaryStage);

    //Crear tarea para iniciar hibernate y el coordinador de la aplicacion
    Task<Boolean> task = new Task<Boolean>() {
        @Override/*from   www. ja  va  2  s . c  om*/
        public Boolean call() throws Exception {
            appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
            coordinador = appContext.getBean(CoordinadorJavaFX.class);
            return true;
        }
    };

    //mientras se muestra una ventana de espera
    task.setOnRunning((event) -> {
        ventanaEspera.showAndWait();
    });

    //que se cierra al terminar.
    task.setOnSucceeded((event) -> {
        ventanaEspera.close();
        apilador = ControladorRomano.crearYMostrarPrimeraVentana(coordinador, primaryStage,
                VTareasController.URL_VISTA);
    });

    //Si falla, informa al usuario del error y cierra la aplicacion
    task.setOnFailed((event) -> {
        try {
            throw task.getException();
        } catch (Throwable e) {
            System.out.println(e.getClass());
            if (appContext != null) {
                SessionFactory sessionFact = (SessionFactory) appContext.getBean("sessionFactory");
                sessionFact.close();
            }
            presentador.presentarExcepcion(new ErrorInicioException(e), ventanaEspera);
            System.exit(1);
        }
    });

    //Iniciar tarea
    Thread hiloHibernate = new Thread(task);
    hiloHibernate.setDaemon(false);
    hiloHibernate.start();
}

From source file:ru.roseurobank.collections.AppOTO.java

public static void main(String[] args) throws NotSupportedException, SystemException, RollbackException,
        HeuristicMixedException, HeuristicRollbackException, NamingException {
    SessionFactory sf = HibernateUtil.getSessionFactory();

    Session s = sf.openSession();/*from  w  ww.  ja v a 2  s. c o  m*/
    Transaction tx = s.beginTransaction();

    AddressOTO a = new AddressOTO();
    a.setCity("Moscow");
    a.setState("Center");
    a.setStreet("Leninskiy");
    a.setZipcode("100200");

    CustomerOTO c = new CustomerOTO();
    c.setName("Customer 1");
    c.setAddress(a);
    a.setCustomer(c);

    s.save(c);

    List<CustomerOTO> custList = s.createQuery("from CustomerOTO as c fetch left join c.orders").list();
    for (CustomerOTO cust : custList) {
        System.out.printf(
                "Id => %d%n? => %s%n => %s%n => %s%n => %s%n? => %s%n",
                cust.getId(), cust.getName(), cust.getAddress().getCity(), cust.getAddress().getState(),
                cust.getAddress().getStreet(), cust.getAddress().getZipcode());
    }

    List<AddressOTO> addressList = s.createQuery("from AddressOTO").list();
    for (AddressOTO address : addressList) {
        System.out.printf(
                "%nId => %d%n => %s%n => %s%n => %s%n? => %s%n",
                //            System.out.printf("%nId => %d%n? => %s%nId => %d%n => %s%n => %s%n => %s%n? => %s%n",
                //                    address.getCustomer().getId(), address.getCustomer().getName(),
                address.getId(), address.getCity(), address.getState(), address.getStreet(),
                address.getZipcode());
    }

    tx.commit();
    s.close();

    sf.close();
}

From source file:ru.roseurobank.hibernateinheritance.Application.java

public static void main(String[] args) {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session s = sf.openSession();/*w ww. j  a  va2s  .  c  om*/
    Transaction tx = s.beginTransaction();

    Users u = new Users();
    u.setName("Hank");

    Role r = new Role();
    r.setName("Administrator");

    //        u.setRols(new HashSet<>(Arrays.asList(r)));
    u.getRols().add(r);

    s.save(r);
    s.save(u);

    tx.commit();
    s.close();
    sf.close();

    SessionFactory sf1 = HibernateUtil.getSessionFactory();
    Session s1 = sf1.openSession();
    Transaction tx1 = s1.beginTransaction();

    Users u1 = (Users) s1.get(Users.class, new Long(1));
    //        System.out.println(u1.getClass());
    System.out.println(u1.getName());

    //        List<BillingDetailsTPS> list = s.createQuery("from BillingDetailsTPS").list();
    //        for (BillingDetailsTPS bd : list) {
    //            System.out.println("Id: " + bd.getId());
    //            System.out.println("Owner: " + bd.getOwner());
    //            if (bd instanceof BankAccountTPS) {
    //                System.out.println("Account: " + ((BankAccountTPS) bd).getAccount());
    //            } else {
    //                if (bd instanceof CreditCardTPS) {
    //                    System.out.println("Number: " + ((CreditCardTPS) bd).getNumber());
    //                }
    //            }
    //        }

    tx1.commit();
    s1.close();
    sf1.close();
}

From source file:rvg.sots.CoursesEntity.java

public static CoursesEntity getById(Long id) {

    Configuration c = new Configuration();
    c.configure("hibernate.config.xml");

    // creating seession factory object
    SessionFactory factory = c.buildSessionFactory();

    // creating session object
    Session session = factory.openSession();

    CoursesEntity result = null;//from   www .j  a v  a 2 s.c  om
    result = session.get(CoursesEntity.class, id);
    session.close();
    factory.close();
    return result;
}

From source file:rvg.sots.CoursesEntity.java

public static List<CoursesEntity> getAll() {

    Configuration c = new Configuration();
    c.configure("hibernate.config.xml");

    // creating seession factory object
    SessionFactory factory = c.buildSessionFactory();

    // creating session object
    Session session = factory.openSession();

    org.hibernate.query.Query query = session.createQuery("from CoursesEntity");
    java.util.List<CoursesEntity> result = query.list();
    session.close();/*from  w  w w .  j  a v  a  2  s .co m*/
    factory.close();
    return result;
}

From source file:servs.AddCategory.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from www . j  a va 2s .  c om*/

        String catname = request.getParameter("categoryname");
        String desc = request.getParameter("desc");

        bean.Category c = new Category();
        c.setCatname(catname);
        c.setDesc(desc);

        Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
        SessionFactory factory = cfg.buildSessionFactory();
        Session s = factory.openSession();
        Transaction tx = s.beginTransaction();
        s.save(c);
        tx.commit();
        request.getSession(true).setAttribute("msg", "msg");
        s.close();
        factory.close();
        //==== if success then redirect to success page
        request.getSession(false).setAttribute("info", "Your Record is Added Successfully");
        response.sendRedirect("AdminPanel/AdminPanelSuccess.jsp");

    } catch (Exception ex) {
        System.out.println("ERROR STARTS FROM HERE:" + ex);
    }

}