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:DataLayer.CtrlUsuariRegistratDB.java

@Override
public Boolean exists(String username) {
    AnnotationConfiguration config = new AnnotationConfiguration();
    config.addAnnotatedClass(Partida.class);
    config.addAnnotatedClass(Casella.class);
    config.addAnnotatedClass(Jugador.class);
    config.addAnnotatedClass(UsuariRegistrat.class);
    config.addAnnotatedClass(Joc2048.class);
    config.configure("hibernate.cfg.xml");
    SessionFactory factory = config.buildSessionFactory();
    Session session = factory.getCurrentSession();
    session.beginTransaction();/*w w w  .  j  a v a 2  s  . co  m*/
    List<UsuariRegistrat> l = session.createQuery("from UsuariRegistrat where username = :usr")
            .setParameter("usr", username).list();
    session.getTransaction().commit();
    factory.close();
    return !l.isEmpty();
}

From source file:DataLayer.CtrlUsuariRegistratDB.java

@Override
public Set<UsuariRegistrat> all() {
    AnnotationConfiguration config = new AnnotationConfiguration();
    config.addAnnotatedClass(Partida.class);
    config.addAnnotatedClass(Casella.class);
    config.addAnnotatedClass(Jugador.class);
    config.addAnnotatedClass(UsuariRegistrat.class);
    config.addAnnotatedClass(Joc2048.class);
    config.configure("hibernate.cfg.xml");
    SessionFactory factory = config.buildSessionFactory();
    Session session = factory.getCurrentSession();
    session.beginTransaction();//from  w ww .j  ava 2s  .c om
    List<UsuariRegistrat> l = session.createQuery("from UsuariRegistrat").list();
    session.getTransaction().commit();
    factory.close();
    Set<UsuariRegistrat> r = new HashSet();
    for (UsuariRegistrat uR : l) {
        r.add(uR);
    }
    return r;
}

From source file:de.decidr.model.webservice.helper.DBAccess.java

License:Apache License

/**
 * @param dwfmID/*from www  .j  a  v  a  2  s  .c om*/
 * @param invokeNodeId
 * @return gets the relevatn DWDL and the relevant WSDL file for the proxy-service from the Database
 */
public DbDataBean getDBData(long dwfmID, long invokeNodeId) {

    DbDataBean dataBean = new DbDataBean();

    SessionFactory sf = new Configuration().configure().buildSessionFactory();

    // actial session
    Session se = sf.getCurrentSession();

    try {
        // save transaction to avoid NullPointerException on error handling.
        Transaction tr = null;

        try {
            // initialize new transaction
            tr = se.beginTransaction();

            execDeployedWorkflowModelQuery(dwfmID, dataBean, se);
            execFileQuery(getFileIDFromDwdl(dataBean, invokeNodeId), dataBean, se);
            execServerLoadViewQuery(ServerTypeEnum.Ode.toString(), dataBean, se);

            se.getTransaction().commit();

        } catch (Throwable e) {
            // if no transaction has been initialized try rollback

            if (tr != null) {
                tr.rollback();
                e.printStackTrace();
            }
        }
    } finally {
        // try to close session if this does not work 
        // at least try to close the transaction.
        try {
            if (se.isOpen()) {
                se.close();
            }
            if (!sf.isClosed()) {
                sf.close();
            }
        } catch (Throwable e) {
            se.disconnect();
        }
    }

    return dataBean;
}

From source file:de.iteratec.iteraplan.persistence.elasticeam.metamodel.IteraplanMetamodelDifferentialWriter.java

License:Open Source License

private void updateEnumLiteral(MMChange<EnumerationLiteralExpression> change) {
    AttributeValueService attributeValueService = (AttributeValueService) DefaultSpringApplicationContext
            .getSpringApplicationContext().getBean("attributeValueService");
    AttributeTypeService attributeTypeService = (AttributeTypeService) DefaultSpringApplicationContext
            .getSpringApplicationContext().getBean("attributeTypeService");
    if (change.getChangeKind() == MMChangeKind.ADD) {
        EnumAT enumAT = this.mapping.getAdditionalEnumerationExpressions()
                .get(change.getAffectedElement().getOwner());
        EnumAV enumAV = new EnumAV();
        enumAV.setAttributeTypeTwoWay(enumAT);
        enumAV.setDescription(change.getAffectedElement().getDescription());
        enumAV.setName(change.getAffectedElement().getPersistentName());
        attributeValueService.saveOrUpdate(enumAV);
        attributeTypeService.merge(enumAT);
    } else if (change.getChangeKind() == MMChangeKind.DELETE) {
        //TODO mba: remove this hack..
        EnumAV enumAV = this.mapping.getAdditionalEnumerationLiterals().get(change.getAffectedElement());
        enumAV.getAttributeType().getAttributeValues().remove(enumAV);
        SessionFactory factory = (SessionFactory) DefaultSpringApplicationContext.getSpringApplicationContext()
                .getBean("sessionFactory");
        FlushMode before = factory.getCurrentSession().getFlushMode();
        factory.getCurrentSession().setFlushMode(FlushMode.AUTO);
        Session session = factory.getCurrentSession();
        Transaction transaction = session.beginTransaction();
        attributeValueService.deleteEntity(enumAV);
        transaction.commit();//from w ww  .  jav a  2 s .co m
        factory.getCurrentSession().setFlushMode(before);
    }
}

From source file:de.iteratec.iteraplan.persistence.elasticeam.model.diff.EMFInstanceExpressionCreation.java

License:Open Source License

private void save() throws IllegalAccessException, InvocationTargetException {
    SessionFactory sessionFactory = (SessionFactory) DefaultSpringApplicationContext
            .getSpringApplicationContext().getBean("sessionFactory");
    Session session = sessionFactory.getCurrentSession();
    if (hbClass.isReleaseClass()) {
        Object base = hbClass.getReleaseBaseProperty().getGetMethod().invoke(buildingBlock);
        session.save(base);/*from w  ww.  j av a2 s  .c  om*/
    }
    session.save(buildingBlock);
}

From source file:de.iteratec.iteraplan.persistence.elasticeam.model.diff.EMFModelWriter.java

License:Open Source License

/**
 * In case of persisting changes to the iteraplan db, a new transaction should be created before applying any changes
 *///from w ww . ja v a  2 s  .c  o m
private void beginTransation() {
    if (session == null && transaction == null) {
        //TODO remove context.getBean(...)
        SessionFactory sessionFactory = (SessionFactory) DefaultSpringApplicationContext
                .getSpringApplicationContext().getBean("sessionFactory");
        this.session = sessionFactory.getCurrentSession();
        session.setFlushMode(FlushMode.COMMIT);
        if (!session.isOpen()) {
            session = sessionFactory.openSession();
        }
        this.transaction = this.session.beginTransaction();
    } else {
        throw new IteraplanTechnicalException(IteraplanErrorMessages.GENERAL_TECHNICAL_ERROR,
                "Cannot begin new transaction while there is another active one alive");
    }

}

From source file:de.iteratec.iteraplan.presentation.problemreports.DatabaseProblemReportPart.java

License:Open Source License

static ProblemReportPart generateDatabaseReport(String filename, HttpServletRequest request) {
    DatabaseProblemReportPart reportPart = new DatabaseProblemReportPart(filename);
    PrintWriter dbWriter = reportPart.getWriter();

    ApplicationContext context = DefaultSpringApplicationContext.getSpringApplicationContext();
    Object sessionFactoryObject = context.getBean("sessionFactory");

    if (sessionFactoryObject instanceof SessionFactory) {
        SessionFactory sessionFactory = (SessionFactory) sessionFactoryObject;
        Session currentSession = sessionFactory.getCurrentSession();
        Map<String, ClassMetadata> allClassMetadata = sessionFactory.getAllClassMetadata();
        final Set<String> tableNames = Sets.newHashSet();
        for (ClassMetadata cm : allClassMetadata.values()) {
            if (cm instanceof AbstractEntityPersister) {
                AbstractEntityPersister aep = (AbstractEntityPersister) cm;
                tableNames.add(aep.getTableName());
            }//from   ww w .  java  2s  . co m
        }

        ByteArrayOutputStream dbInfoBuffer = new ByteArrayOutputStream();
        final PrintWriter dbInfoWriter = new PrintWriter(dbInfoBuffer);
        Work work = new Work() {

            @Override
            public void execute(Connection connection) throws SQLException {

                try {
                    DatabaseMetaData metaData = connection.getMetaData();
                    dbInfoWriter.println("Database Name: " + metaData.getDatabaseProductName() + "  "
                            + metaData.getDatabaseMajorVersion() + "." + metaData.getDatabaseMinorVersion());
                    dbInfoWriter.println("Database Product Version: " + metaData.getDatabaseProductVersion());
                    dbInfoWriter.println("JDBC URL: " + metaData.getURL());
                    dbInfoWriter.println("JDBC API: " + metaData.getJDBCMajorVersion() + "."
                            + metaData.getJDBCMinorVersion());
                    dbInfoWriter.println("JDBC-Driver Name: " + metaData.getDriverName() + "  "
                            + metaData.getDriverMajorVersion() + "." + metaData.getDriverMinorVersion());
                    dbInfoWriter.println("JDBC-Driver Version: " + metaData.getDriverVersion());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        try {
            TimeLimiter timeLimiter = new SimpleTimeLimiter();
            Session sessionProxy = timeLimiter.newProxy(currentSession, Session.class, TIMEOUT_IN_SECONDS,
                    TimeUnit.SECONDS);
            sessionProxy.doWork(work);
        } catch (UncheckedTimeoutException e) {
            dbInfoWriter.println("Couldn't gather database information from conncetion within "
                    + TIMEOUT_IN_SECONDS + " seconds.");
        } catch (Exception e) {
            dbInfoWriter.println("Couldn't gather database information from connection.");
        }

        dbInfoWriter.close();
        dbWriter.print(dbInfoBuffer);
    }

    dbWriter.close();
    return reportPart;
}

From source file:DomainLayer.DomainControllers.CtrlJugarPartida.java

private void actualitzarDB(Partida p, Jugador jg, Boolean crea, Joc2048 joc) {
    AnnotationConfiguration config = new AnnotationConfiguration();
    config.addAnnotatedClass(Partida.class);
    config.addAnnotatedClass(Casella.class);
    config.addAnnotatedClass(Jugador.class);
    config.addAnnotatedClass(UsuariRegistrat.class);
    config.addAnnotatedClass(Joc2048.class);
    config.configure("hibernate.cfg.xml");
    SessionFactory factory = config.buildSessionFactory();
    Session session = factory.getCurrentSession();
    session.beginTransaction();/* w w w.j a v  a 2 s  .c o m*/
    if (crea) {
        session.save(p);
        session.update(joc);
    } else
        session.update(p);
    session.update(jg);
    Casella caselles[][] = p.getMatriu();
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            if (crea)
                session.save(caselles[i][j]);
            else
                session.update(caselles[i][j]);
        }
    }
    session.getTransaction().commit();
    factory.close();
}

From source file:DomainLayer.DomainModel.Joc2048.java

public static synchronized Joc2048 joc2048() {
    if (instance == null) {
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Partida.class);
        config.addAnnotatedClass(Casella.class);
        config.addAnnotatedClass(Jugador.class);
        config.addAnnotatedClass(UsuariRegistrat.class);
        config.addAnnotatedClass(Joc2048.class);
        config.configure("hibernate.cfg.xml");
        SessionFactory factory = config.buildSessionFactory();
        Session session = factory.getCurrentSession();
        session.beginTransaction();/*from w w w. ja  v a  2s .com*/
        List<Joc2048> l = session.createQuery("from Joc2048").list();
        if (l.isEmpty()) {
            instance = new Joc2048();
            instance.setIdPartida(0);
            session.save(instance);
        } else
            instance = l.get(0);
        session.getTransaction().commit();
        factory.close();
    }
    return instance;
}

From source file:edu.duke.cabig.c3pr.grid.registrationservice.service.impl.C3PRRegistrationServiceImpl.java

License:BSD License

public List<PlannedNotification> getPlannedNotifications(String nciInstituteCode) {
    List<PlannedNotification> result;
    List<String> nciCodeList = new ArrayList<String>();
    nciCodeList.add(nciInstituteCode);// ww w .  j a  va  2 s .c  o m

    SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
    Session session = sessionFactory.openSession(sessionFactory.getCurrentSession().connection());
    session.setFlushMode(FlushMode.MANUAL);
    result = new ArrayList<PlannedNotification>();
    try {
        //Query query =  session.createQuery("select p from PlannedNotification p, HealthcareSite o where p.id = o.plannedNotificationsInternal.id and o.nciInstituteCode = ?");
        Query query = session.createQuery(
                "select p from PlannedNotification p, HealthcareSite o where p.id = o.plannedNotificationsInternal.id and o.identifiersAssignedToOrganization.typeInternal='CTEP' and o.identifiersAssignedToOrganization.value in (:nciCodeList)")
                .setParameterList("nciCodeList", nciCodeList);
        Query query1 = session.createQuery(
                "select p from PlannedNotification p, HealthcareSite o where p.id = o.plannedNotificationsInternal.id and o.identifiersAssignedToOrganization.typeInternal='CTEP' and o.identifiersAssignedToOrganization.value="
                        + "'" + nciInstituteCode + "'");
        //          Query query = session.createQuery("Select p from PlannedNotification as p, o from HealthcareSite as o where p.id = o.plannedNotificationsInternal.id and" +
        //                "o.nci_institute_code in (:nciCodeList)").setParameterList("nciCodeList",nciCodeList);
        //          query.setEntity(0, nciCodeList);
        result = query.list();
    } catch (DataAccessResourceFailureException e) {
        logger.error(e.getMessage());
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (HibernateException e) {
        logger.error(e.getMessage());
    } catch (Exception e) {
        logger.error(e.getMessage());
    } finally {
        session.close();
    }
    return result;
    //result = organizationDao.getByNciIdentifier(configuration.get(Configuration.LOCAL_NCI_INSTITUTE_CODE)).get(0).getPlannedNotifications();
    //return result;
}