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:com.github.aint.jblog.model.dao.hibernate.ValidatorHibernateDaoTest.java

License:Open Source License

@BeforeClass
public void beforeClass() {
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    validatorDao = new ValidatorHibernateDao(sessionFactory);
    session = sessionFactory.getCurrentSession();
    session.beginTransaction();//from  w w  w  .  j a v a2  s.c  o  m
}

From source file:com.github.jmnarloch.hstreams.Demo.java

License:Apache License

private SessionFactory sessionFactory() {
    SessionFactory sessionFactory = mock(SessionFactory.class);
    Session session = mock(Session.class);
    Query query = mock(Query.class);

    when(sessionFactory.getCurrentSession()).thenReturn(session);
    when(session.createQuery(any())).thenReturn(query);
    when(session.get(any(String.class), any(Long.class))).thenReturn(new Object());

    when(query.setParameter(any(), any())).thenReturn(query);
    when(query.list()).thenReturn(new ArrayList());
    when(query.uniqueResult()).thenReturn(new Object());

    return sessionFactory;
}

From source file:com.google.code.trapo.validation.UniqueConstraintValidatorTests.java

License:Apache License

private UniqueConstraintValidator validator(SessionImplementor session) {
    SessionFactory sessionFactory = mock(SessionFactory.class);
    when(sessionFactory.getCurrentSession()).thenAnswer(answer(session));
    when(sessionFactory.openSession()).thenAnswer(answer(session));

    UniqueConstraintValidator validator = new UniqueConstraintValidator();
    validator.initialize(unique(String.class, "value"));
    validator.setSessionFactory(sessionFactory);
    return validator;
}

From source file:com.leapfrog.studentenroll.dao.impl.StudentDAOImpl.java

@Override
public List<Student> getAll() {
    session = SessionFactory.getCurrentSession();
    session.getTransaction().begin();/*from  www .  j  av a2s.co m*/
    List<Student> studentList = session.createQuery("SELECT s from Student s").list();
    session.getTransaction().commit();
    return studentList;
}

From source file:com.liferay.portal.dao.orm.hibernate.PortletSessionFactoryImpl.java

License:Open Source License

@Override
public Session openSession() throws ORMException {
    SessionFactory sessionFactory = getSessionFactory();

    org.hibernate.Session session = null;

    if (PropsValues.SPRING_HIBERNATE_SESSION_DELEGATED) {
        Connection connection = CurrentConnectionUtil.getConnection(getDataSource());

        if (connection == null) {
            session = sessionFactory.getCurrentSession();
        } else {//from   www . jav  a 2 s. c o  m
            session = sessionFactory.openSession(connection);
        }
    } else {
        session = sessionFactory.openSession();
    }

    if (_log.isDebugEnabled()) {
        org.hibernate.impl.SessionImpl sessionImpl = (org.hibernate.impl.SessionImpl) session;

        _log.debug("Session is using connection release mode " + sessionImpl.getConnectionReleaseMode());
    }

    return wrapSession(session);
}

From source file:com.liferay.samplehibernate.util.HibernateUtil.java

License:Open Source License

public static Session openSession(SessionFactory sessionFactory) throws HibernateException {

    return sessionFactory.getCurrentSession();
}

From source file:com.mycompany.tareafinal.BuscarTodos.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* ww w  .j  a v  a  2 s  . co  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void doget(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    SessionFactory factory = Hibernate1.getSessionFactory();
    Session sesion = factory.getCurrentSession();
    Transaction tanza = sesion.beginTransaction();

    ArrayList<Trabajador> tra = (ArrayList<Trabajador>) sesion.createCriteria(Trabajador.class).list();
    tanza.commit();
    sesion.close();

}

From source file:com.netcore.hsmart.dlrconsumers.DlrConsumer1000.java

private static boolean invokeApiCall(Map<String, String> dataToPost) {
    Logger logger = LoggerFactory.getLogger(DlrConsumer1000.class);

    try {//from  w  ww  . ja  v  a 2  s. co  m

        //convert dlr time to IST time zone
        String dlrTimeIST = getISTDlrTime(dataToPost.get("scts"));

        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|IST_DLR_TIME:" + dlrTimeIST);

        //get dm status 
        Map<String, String> dmData = null;

        if (dataToPost.get("status") == null) {
            logger.info("REF_ID:" + dataToPost.get("ref_id") + "|EMPTY_STATUS,SETTING TO DEFAULT");
            dmData = getDmStatusDetails(DEFAULT_VENDOR_STATUS);
        } else {
            dmData = getDmStatusDetails(dataToPost.get("status"));
        }

        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PK_ID_MAPPED:" + dmData.get("id"));
        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|DM_STATUS:" + dmData.get("dm_status"));

        ClientConfig clientConfig = new ClientConfig();
        clientConfig.connectorProvider(new GrizzlyConnectorProvider());
        Client client = ClientBuilder.newClient(clientConfig);
        WebTarget webTarget = client.target(AppConstants.getDmDlrReturnApi());

        WebTarget dlrTimeParam = webTarget.queryParam("delivery_time", dlrTimeIST);
        WebTarget statusParam = dlrTimeParam.queryParam("status", dmData.get("dm_status"));
        WebTarget gatewayIdParam = statusParam.queryParam("gateway_id", dataToPost.get("gateway_id"));
        WebTarget txnIdParam = gatewayIdParam.queryParam("transaction_id", dataToPost.get("ref_id"));
        WebTarget errorParam = txnIdParam.queryParam("error_code", dmData.get("dm_status"));

        URI u = errorParam.getUri();

        Invocation.Builder invocationBuilder = errorParam.request().header("Content-Length",
                u.getQuery().length());
        long startTime = System.currentTimeMillis();
        Response response = invocationBuilder.get();
        long elapsedTime = System.currentTimeMillis() - startTime;
        String responseText = response.readEntity(String.class);
        Integer responseStatus = response.getStatus();

        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|HTTP_STATUS:" + responseStatus);
        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|RESPONSE_TEXT:" + responseText);

        response.close();
        client.close();

        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|URI:" + u.toString() + "|LENGTH:"
                + u.getQuery().length());
        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|LATENCY:" + elapsedTime + "ms");

        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|DB operation started");
        SessionFactory factory = HibernateUtil.getSessionFactory();

        try (Session session = factory.getCurrentSession()) {
            session.getTransaction().begin();
            DlrResponseData res = new DlrResponseData();

            res.setRefId(dataToPost.get("ref_id"));

            DateFormat dateFormat = new SimpleDateFormat(EXPECTED_DLR_TIME_FORMAT);
            Date inputDate = dateFormat.parse(dlrTimeIST);

            res.setDlrTime(inputDate);
            res.setStatusMapId(dmData.get("id"));

            Date now = new Date();
            res.setCreatedTime(now);
            session.save(res);
            session.getTransaction().commit();

            logger.info("REF_ID:" + dataToPost.get("ref_id") + "|DATA_SAVED");
            return true;
        } catch (Exception e) {
            logger.info("REF_ID:" + dataToPost.get("ref_id") + "|DB_ERROR:" + e.getMessage());
            return false;
        }

    } catch (ProcessingException e) {
        logger.error("ERROR:" + e.getMessage() + Arrays.toString(e.getStackTrace()));
        return false;

    } catch (Exception ex) {

        java.util.logging.Logger.getLogger(DlrConsumer1000.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }

}

From source file:com.netcore.hsmart.smsconsumers.SmsConsumer1000.java

private static boolean saveRequestData() {
    Logger logger = LoggerFactory.getLogger(SmsConsumer1000.class);

    logger.info("REF_ID:" + API_CALL_STATS.get("ref_id") + "|DB operation started");
    SessionFactory factory = HibernateUtil.getSessionFactory();
    try (Session session = factory.getCurrentSession()) {
        session.getTransaction().begin();
        SmsRequestData req = new SmsRequestData();
        req.setRefId(API_CALL_STATS.get("ref_id"));
        req.setGatewayId(GATEWAY_ID);/*from   w  w w  . java2s.c o m*/
        //req.setEncText(encRefId);
        req.setUri(API_CALL_STATS.get("uri"));
        req.setHttpStatus(API_CALL_STATS.get("http_status"));
        req.setResponseText(API_CALL_STATS.get("response_text"));
        req.setLatency(API_CALL_STATS.get("latency"));
        req.setApiCallStatus(API_CALL_STATS.get("api_call_status"));
        req.setMsgCount(API_CALL_STATS.get("msg_count"));
        req.setMsgId(API_CALL_STATS.get("msg_id"));
        req.setPrice(API_CALL_STATS.get("price"));
        req.setBalance(API_CALL_STATS.get("balance"));
        req.setApiCallErrorText(API_CALL_STATS.get("api_call_error_text"));

        Date now = new Date();
        req.setCreatedTime(now);
        session.save(req);
        session.getTransaction().commit();

        logger.info("REF_ID:" + API_CALL_STATS.get("ref_id") + "|DATA_SAVED");
        return true;
    } catch (Exception e) {
        logger.info("REF_ID:" + API_CALL_STATS.get("ref_id") + "|DB_ERROR:" + e.getMessage());
        return false;
    }

}

From source file:com.onlineshopping.Models.CartService.java

public List<Cart> getCartsByUserId(long userId) {
    List<Cart> carts = new ArrayList<Cart>();
    SessionFactory factory = HibernateUtil.getSessionFactory();
    Session session = factory.getCurrentSession();
    Transaction tx = null;//from  w ww  .j  av a 2  s.  c  om
    try {
        tx = session.getTransaction();
        tx.begin();
        carts = session.createQuery("from Cart where userid='" + userId + "'").list();
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }
        e.printStackTrace();
    }
    return carts;
}