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:io.opentracing.contrib.jdbc.HibernateTest.java

License:Apache License

@Test
public void hibernate() {
    SessionFactory sessionFactory = createSessionFactory(false);
    Session session = sessionFactory.openSession();

    Employee employee = new Employee();
    session.beginTransaction();/*from   w w w  .ja va2s.c  o m*/
    session.save(employee);
    session.getTransaction().commit();
    session.close();
    sessionFactory.close();

    assertNotNull(employee.id);

    List<MockSpan> finishedSpans = mockTracer.finishedSpans();
    assertEquals(9, finishedSpans.size());

    checkSpans(finishedSpans, "hibernate");
    assertNull(mockTracer.activeSpan());
}

From source file:io.opentracing.contrib.jdbc.HibernateTest.java

License:Apache License

@Test
public void hibernate_with_active_span_only() {
    SessionFactory sessionFactory = createSessionFactory(true);
    Session session = sessionFactory.openSession();

    Employee employee = new Employee();
    session.beginTransaction();/*from   w ww. ja  v a2 s. c  om*/
    session.save(employee);
    session.getTransaction().commit();
    session.close();
    sessionFactory.close();

    assertNotNull(employee.id);

    List<MockSpan> finishedSpans = mockTracer.finishedSpans();
    assertEquals(0, finishedSpans.size());

    assertNull(mockTracer.activeSpan());
}

From source file:io.opentracing.contrib.jdbc.HibernateTest.java

License:Apache License

@Test
public void hibernate_with_parent() {
    try (Scope ignored = mockTracer.buildSpan("parent").startActive(true)) {
        SessionFactory sessionFactory = createSessionFactory(false);
        Session session = sessionFactory.openSession();

        session.beginTransaction();//from www  .j a v a 2s .com
        session.save(new Employee());
        session.save(new Employee());
        session.getTransaction().commit();
        session.close();
        sessionFactory.close();
    }

    List<MockSpan> spans = mockTracer.finishedSpans();
    assertEquals(12, spans.size());
    checkSameTrace(spans);
    assertNull(mockTracer.activeSpan());
}

From source file:io.opentracing.contrib.jdbc.HibernateTest.java

License:Apache License

@Test
public void hibernate_with_parent_and_active_span_only() {
    try (Scope ignored = mockTracer.buildSpan("parent").startActive(true)) {
        SessionFactory sessionFactory = createSessionFactory(true);
        Session session = sessionFactory.openSession();

        session.beginTransaction();/* www .  j  a  v a 2s .  com*/
        session.save(new Employee());
        session.save(new Employee());
        session.getTransaction().commit();
        session.close();
        sessionFactory.close();
    }

    List<MockSpan> spans = mockTracer.finishedSpans();
    assertEquals(12, spans.size());
    checkSameTrace(spans);
    assertNull(mockTracer.activeSpan());
}

From source file:io.opentracing.contrib.jdbc.HibernateTest.java

License:Apache License

@Test
public void hibernate_with_ignored_statement() {
    SessionFactory sessionFactory = createSessionFactory(false,
            Arrays.asList("insert into Employee (id) values (?)"));
    Session session = sessionFactory.openSession();

    Employee employee = new Employee();
    session.beginTransaction();// w  w  w.j  a  v a 2  s  . c  om
    session.save(employee);
    session.getTransaction().commit();
    session.close();
    sessionFactory.close();

    assertNotNull(employee.id);

    List<MockSpan> finishedSpans = mockTracer.finishedSpans();
    assertEquals(8, finishedSpans.size());

    checkSpans(finishedSpans, "hibernate");
    assertNull(mockTracer.activeSpan());
}

From source file:isjexecact.br.com.inso.Funcionalidades.EnviarEmail.EnviarEmail.java

/**
 * Grava o log com o resultado do envio do e-mail.
 *///from   w w  w.  j a  va 2s.c o m
private void GravaLogEmail() {
    //
    // Glauber 25/07/2014
    // 
    // Caso ocorra um erro de gravao da tabela de log de e-mail, utilizo o campo statusRetorno para informar do ocorrido.
    //
    try {

        // Criar o contexto de sesso do hibernate e abrir a conexo.

        SessionFactory sessionFactory = HibernateUtil.getSessionFactory(null);
        org.hibernate.Session sessao = sessionFactory.openSession();
        Transaction tx = sessao.beginTransaction();

        // Cria o objeto que  a foto do registro na tabela conforme mapeamento do hibernate

        IsjwfmaillogId isjwfmaillogid = new IsjwfmaillogId();
        isjwfmaillogid.setData(getDataAtual());
        isjwfmaillogid.setHora(getHoraAtual());
        isjwfmaillogid.setOrigem(Funcoes.TruncarString(this.de, 250));
        isjwfmaillogid.setDestino(Funcoes.TruncarString(this.para, 250));
        isjwfmaillogid.setAssuntoEmail(Funcoes.TruncarString(this.assunto, 250));
        isjwfmaillogid.setCorpo(Funcoes.TruncarString(this.mensagem, 4000));
        isjwfmaillogid.setStatusEnvio(Funcoes.TruncarString(statusRetorno, 4000));

        // Criar o objeto principal

        Isjwfmaillog isjwfmaillog = new Isjwfmaillog();
        isjwfmaillog.setId(isjwfmaillogid);

        // Criar o objeto responsvel pela persistncia, injeta o contexto de sesso e chama o metodo para persistir o objeto.

        IsjwfmaillogDAOHibernate crudmail = new IsjwfmaillogDAOHibernate();

        crudmail.setSession(sessao);
        crudmail.inserirRegistro(isjwfmaillog);
        tx.commit();
        sessao.close();
        sessionFactory.close();
    } catch (Exception ex) {
        this.statusRetorno = "Erro ao gravar o log de envio de email(isjwfmaillog):" + ex.getMessage();
    }

}

From source file:javaapplicationprimerospasoshibernate.InicioAuto.java

public InicioAuto() {

    SessionFactory sf = NewHibernateUtil.getSessionFactory();
    Session session = sf.openSession();/*from  www. j  a  v a2 s  .  c o m*/
    Transaction transaction = session.beginTransaction();
    Concesionario conse = new Concesionario();

    conse.setNombre("nombreConcesionario");
    conse.setDireccion("asdasd");
    session.save(conse);

    Auto a = new Auto();
    a.setMarca("a");
    a.setModelo("b");
    a.setConcesionario(conse);
    conse.getAutos().add(a);
    session.save(a);

    a = new Auto();
    a.setMarca("a");
    a.setModelo("b");
    a.setConcesionario(conse);
    conse.getAutos().add(a);
    session.save(a);

    transaction.commit();
    session.close();
    sf.close();
}

From source file:javaapplicationprimerospasoshibernate.InicioHql.java

public InicioHql() {

    SessionFactory sf = NewHibernateUtil.getSessionFactory();
    Session session = sf.openSession();/*from w  w w.j  ava  2 s.  c om*/
    Transaction transaction = session.beginTransaction();

    Query query = session.createQuery("from Persona as p order by p.nombre");
    List<Persona> personas = query.list();

    System.out.println("javaapplicationprimerospasoshibernate.InicioHql.<init>()");
    recorrer(personas);

    Query query2 = session.createQuery("from Personas as p where p.id = :idBuscar");
    query2.setLong("idBuscar", 1l);
    Persona persona2 = (Persona) query2.uniqueResult();
    System.out.println("persona nombre:" + persona2.getId());

    Query query3 = session.createQuery("from Auto as a where a.concesionario.id =:idConcesionario");
    query3.setParameter("idConcesionario", 1l);
    List<Auto> auto = query3.list();

    //        levanto la marca del auto sin levantar la concecionaria
    Query query4 = session.createQuery("select a.marca from Auto as a where a.id =:idBuscar");
    query4.setLong("idBuscar", 1);
    Auto auto1 = (Auto) query4.uniqueResult();

    //        busca una coleccion de autos en cocesionaria
    Query query5 = session.createQuery("select c.autos from Concesionarios as c where c.id = :idbuscar");
    query5.setLong("idbuscar", 1l);
    List<Auto> auto2 = query5.list();

    //esta no va a andar porque la entidad persona se refiere a la vieja
    Query query6 = session
            .createQuery("from Persona as p join p.telefonos as t where t.numero like :numeroBuscar");
    query6.setString("numeroBuscar", "455%");
    List<Persona> personas2 = query6.list();

    //        quiero el nombre de una persona espesifica
    Query query7 = session.createQuery("select p.nombre from Persona as p where .id = :idbuscar");
    query7.setLong("numeroBuscar", 1);
    String personas23 = (String) query6.uniqueResult();

    //me traigo dos cmapos y me devuelve un array de una persona
    Query query8 = session.createQuery("select p.nombre, p.apellido from Persona as p where .id = :idbuscar");
    query8.setLong("numeroBuscar", 1);
    String personas24 = (String) query8.uniqueResult();

    //me traigo dos cmapos de todas las personas, devuelve un list y dentro del list un campo con vectores
    Query query9 = session.createQuery("select p.nombre, p.apellido from Persona ");
    query8.setLong("numeroBuscar", 1);
    List<Object[]> rows = (List<Object[]>) query8.list();

    transaction.commit();
    session.close();
    sf.close();

}

From source file:javaapplicationprimerospasoshibernate.InicioVendedor.java

public InicioVendedor() {

    SessionFactory sf = NewHibernateUtil.getSessionFactory();
    Session session = sf.openSession();//  www . ja  va2  s .c o  m
    Transaction transaction = session.beginTransaction();

    Vendedor vendedor = new Vendedor("123564", new Date());
    vendedor.setNombre("jose");
    vendedor.setApellido("ivatis");
    vendedor.setDireccion("una calle");
    session.save(vendedor);
    transaction.commit();
    session.close();
    sf.close();

}

From source file:javahibernateparametros.JavaHibernateParametros.java

/**
 * @param args the command line arguments
 *///w w  w.  jav  a2  s.c o  m
public static void main(String[] args) {

    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();

    {
        System.out.println("Parametro posicionar");
        System.out.println("=====================");

        Query query = session.createQuery("SELECT p FROM Participante p WHERE p.club=? AND p.poblacion=?");

        query.setString(0, "ATLETAS NUCLEO DURO DENIA");
        query.setString(1, "DENIA");

        List<Participante> participantes = query.list();

        for (Object participante : participantes) {
            System.out.println(participante.toString());
        }

    }

    {
        System.out.println("\nParametro con nombre");
        System.out.println("=====================");

        String club = "ATLETAS NUCLEO DURO DENIA";
        String poblacion = "DENIA";

        Query query = session.createQuery(
                "SELECT p FROM Participante p WHERE p.club=:clubhql AND p.poblacion=:poblacionhql");

        //Depende del tipo de dato se deberia de usar setInteger
        query.setString("clubhql", club);

        //siempre se puede usar setParameter.
        query.setParameter("poblacionhql", poblacion);

        List<Participante> participantes = query.list();

        for (Object participante : participantes) {
            System.out.println(participante.toString());
        }

    }

    {
        System.out.println("\nParametros por metodos encadenados");
        System.out.println("=====================");

        String club = "ATLETAS NUCLEO DURO DENIA";
        String poblacion = "DENIA";

        Query query = session
                .createQuery("SELECT p FROM Participante p WHERE p.club=:clubhql AND p.poblacion=:poblacionhql")
                .setParameter("clubhql", club).setParameter("poblacionhql", poblacion);

        List<Participante> participantes = query.list();

        for (Object participante : participantes) {
            System.out.println(participante.toString());
        }

    }

    session.close();
    sessionFactory.close();

}