Example usage for org.hibernate SessionFactory getCurrentSession

List of usage examples for org.hibernate SessionFactory getCurrentSession

Introduction

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

Prototype

Session getCurrentSession() throws HibernateException;

Source Link

Document

Obtains the current session.

Usage

From source file:fr.alpha.actions.VendeurAction.java

public String addUser() {
    if (user != null && !user.getNom().equals("") && !user.getMail().equals("") && !user.getPrenom().equals("")
            && !user.getMdp().equals("")) {

        SessionFactory factory = HibernateUtil.createSessionFactory();
        utilDAO.setSessionFactory(factory);
        Transaction tx = factory.getCurrentSession().beginTransaction();

        session.put("USER", user);
        utilDAO.save(user);//from   w ww.  j av  a  2  s .c o m

        tx.commit();

        return SUCCESS;
    }
    return INPUT;
}

From source file:fr.gael.dhus.database.dao.interfaces.HibernateDao.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<T> listCriteria(DetachedCriteria detached, int skip, int top) {
    SessionFactory factory = getSessionFactory();
    org.hibernate.classic.Session session = factory.getCurrentSession();

    Criteria criteria = detached.getExecutableCriteria(session);

    if (skip > 0)
        criteria.setFirstResult(skip);/*from  www  . java  2  s .c o m*/
    if (top > 0)
        criteria.setMaxResults(top);
    return criteria.list();
}

From source file:fr.keyconsulting.oliphant.test.Benchmark.java

License:Open Source License

public void update(long id, boolean magic, boolean stale) throws SQLException {
    SessionFactory factory = magic ? magicSessionFactory : sessionFactory;

    Session session = factory.getCurrentSession();

    System.out.println("Hibernate: starting transaction");
    Transaction tx = session.beginTransaction();
    PersistentVersionedObject o1 = (PersistentVersionedObject) session.load(PersistentVersionedObject.class,
            id + 1);//  w w  w. ja  va 2s  .  co m
    System.out.println("Hibernate: loading object " + id);
    PersistentVersionedObject o = (PersistentVersionedObject) session.load(PersistentVersionedObject.class, id);
    o.setChampString("valeur 2");

    if (stale) {
        Statement st = conn.createStatement();
        System.out.println("Updating object " + id + " outside Hibernate");
        st.executeUpdate("UPDATE persistentversionedobject SET version=version+1 WHERE id=" + id);
        st.close();
    }

    try {
        session.persist(o);
        tx.commit();
    } catch (Exception e) {
        System.out.println(e);
        System.out.println("  in " + e.getStackTrace()[0]);
    }
}

From source file:fr.keyconsulting.oliphant.test.unitTests.java

License:Open Source License

public void update(Class theClass, boolean magic, boolean stale, boolean cached) {
    long id = 0;/* ww w.  j a  v  a2  s  .c  o  m*/
    SessionFactory factory = magic ? magicSessionFactory : sessionFactory;

    Session session = factory.getCurrentSession();

    System.out.println("Hibernate: starting transaction");
    Transaction tx = session.beginTransaction();

    if (cached) {
        System.out.println("Hibernate: pre-loading object " + id);
        Object o = theClass.cast(session.load(theClass, id));
    } else {
        factory.evict(theClass);
    }
    System.out.println("Hibernate: loading " + theClass + " " + id);
    PersistentVersionedObject o = (PersistentVersionedObject) session.load(theClass, id);
    o.setChampString("" + System.currentTimeMillis());

    if (stale) {
        try {
            System.out.println("Updating " + theClass + " " + id + " outside Hibernate");
            Statement st = conn.createStatement();
            String entityName = session.getEntityName(o);
            PersistentClass c = config.getClassMapping(entityName);
            st.executeUpdate("UPDATE " + c.getTable().getName() + " SET version=version+1 WHERE id=" + id);
            st.close();
        } catch (SQLException e) {
            fail();
            System.out.println(e);
            System.out.println("  in " + e.getStackTrace()[0]);
        }
    }
    try {
        session.persist(o);
    } catch (StaleObjectStateException e) {
        assertTrue(magic && stale);
        return;
    }
    assertFalse(stale && magic); // We should have had an exception
    try {
        tx.commit();
    } catch (StaleObjectStateException e) {
        assertTrue(stale);
        return;
    }
    assertFalse(stale); // We should have had an exception
}

From source file:fr.mcc.ginco.audit.tracking.GincoRevListener.java

License:CeCILL license

@Override
public void entityChanged(Class entityClass, String entityName, Serializable entityId,
        RevisionType revisionType, Object revisionEntity) {
    GincoRevModifiedEntityType revEntity = new GincoRevModifiedEntityType();
    revEntity.setEntityClassName(entityClass.getName());
    revEntity.setRevision(((GincoRevEntity) revisionEntity).getId());
    ((GincoRevEntity) revisionEntity).addModifiedEntityType(revEntity);
    if (ArrayUtils.contains(entityClass.getGenericInterfaces(), IAuditableBean.class)) {
        if (!revisionType.equals(RevisionType.DEL)) {
            GenericHibernateDAO objectDAO = new GenericHibernateDAO(entityClass);
            objectDAO.setSessionFactory((SessionFactory) applicationContext.getBean("gincoSessionFactory"));
            String thesaurusId = ((IAuditableBean) objectDAO.getById(entityId)).getThesaurusId();
            ((GincoRevEntity) revisionEntity).setThesaurusId(thesaurusId);
        } else {//from   www  .j  av  a  2  s. co m
            SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("gincoSessionFactory");
            AuditReader reader = AuditReaderFactory.get(sessionFactory.getCurrentSession());

            AuditQueryBuilder queryBuilder = new AuditQueryBuilder();
            AuditQuery query;
            try {
                query = queryBuilder.getEntityAddedQuery(reader, Class.forName(entityName), entityId);
                try {
                    List<Object[]> createdEvent = (List<Object[]>) query.getResultList();
                    if (createdEvent != null && createdEvent.size() > 0) {
                        ((GincoRevEntity) revisionEntity)
                                .setThesaurusId(((GincoRevEntity) createdEvent.get(0)[1]).getThesaurusId());
                    }
                } catch (AuditException ae) {
                    logger.warn("Unable to get the creation revision of the destroyed object", ae);
                }
            } catch (ClassNotFoundException e) {
                logger.error("Error storing audit data", e);
            }
        }
    } else {
        logger.warn("Trying to audit a bean not implementing IAuditableBean interface");
    }

}

From source file:InterfacesImplementation.BookDaoImpl.java

@Override
public List getBookList() {

    SessionFactory sessionFactory = HibernateSessionManagment.getSessionFactory();
    session = sessionFactory.getCurrentSession();
    Transaction transaction;// w w  w . jav  a  2  s.  c o  m
    if (session.isOpen()) {
        transaction = session.beginTransaction();
    } else {
        session = sessionFactory.openSession();
    }
    try {
        List booksList = session.createQuery("from Books").list();
        return booksList;
    } finally {
        session.close();
    }
}

From source file:io.datalayer.hibernate.HibernateT4fMain.java

License:Apache License

/**
 * @param args//from www  .  ja v  a 2 s .  c  o  m
 */
public static void main(String... args) throws Exception {

    Thread databaseThread = new Thread(new DatabaseServerControlRunnable());
    databaseThread.start();

    /** Getting the Session Factory and session */
    SessionFactory session = HibernateUtil.getSessionFactory();
    Session sess = session.getCurrentSession();
    /** Starting the Transaction */
    Transaction tx = sess.beginTransaction();
    /** Creating Pojo */
    Employee pojo = new Employee();
    pojo.setId(new Integer(5));
    pojo.setName("XYZ");
    /** Saving POJO */
    sess.save(pojo);
    /** Commiting the changes */
    tx.commit();
    System.out.println("Record Inserted");
    /** Closing Session */
    session.close();

}

From source file:jp.go.nict.langrid.wrapper.edr.importer.Import.java

License:Open Source License

private static <T> void importRecords(SessionFactory factory, RecordReader<T> reader) throws Exception {
    Session s = factory.getCurrentSession();
    s.beginTransaction();/*  ww  w  .ja v  a 2s .com*/

    int i = 0;
    T record = null;
    while ((record = reader.readRecord()) != null) {
        i++;
        if (i % 100 == 0) {
            System.out.println(String.format("%06d result: %s", i, record));
            s.getTransaction().commit();
            s = factory.getCurrentSession();
            s.beginTransaction();
        }
        s.save(record);
        //         if(i == 1000) break;
    }
    reader.close();
    s.getTransaction().commit();
}

From source file:jshm.hibernate.HibernateUtil.java

License:Open Source License

public static Session getCurrentSessionSilent() {
    SessionFactory sf = getSessionFactorySilent();

    if (null == sf)
        return null;

    return sf.getCurrentSession();
}

From source file:manejadorDB.controlador.AeropuertoControlador.java

@Override
public Aeropuerto crear(Aeropuerto aeropuerto) {

    Aeropuerto a = obtener_Aeropuerto(aeropuerto.getIdaeropuerto()); //se revisa si se est insertando un nuevo aeropuerto o ya existe.
    if (a == null) {
        SessionFactory factory = Sesion.init();
        if (factory != null) {

            try {
                //crear sesion
                Session session = factory.getCurrentSession();

                //transaccion
                session.beginTransaction();

                //guardar aeropuerto
                session.save(aeropuerto);

                //commitear transaccion
                session.getTransaction().commit();

            } catch (Exception e) {
                e.printStackTrace();/*from  www  .ja  v a 2 s.  co m*/
            } finally {
                Sesion.close();
            }
        }

        return aeropuerto;
    } else {
        return a;
    }

}