Java 类org.hibernate.StatelessSession 实例源码

项目:oscm    文件:HibernateEventListener.java   
private void removeLocalization(EntityPersister persister, Object entity) {
    if (entity instanceof DomainObject<?>) {
        DomainObject<?> obj = (DomainObject<?>) entity;
        List<LocalizedObjectTypes> objType = obj.getLocalizedObjectTypes();
        if (objType.size() > 0) {
            long key = obj.getKey();
            final StatelessSession session = persister.getFactory()
                    .openStatelessSession();
            Transaction tx = session.beginTransaction();
            org.hibernate.Query query = session.createQuery(
                    "DELETE FROM LocalizedResource WHERE objectKey = :objectKey AND objectType IN (:objectType)");
            query.setParameter("objectKey", key);
            query.setParameterList("objectType", objType);
            query.executeUpdate();
            tx.commit();
            session.close();
        }
    }
}
项目:oscm    文件:HibernateEventListener.java   
private void createHistory(EntityPersister persister, Object entity,
        ModificationType type) {
    if (entity instanceof DomainObject<?>) {
        DomainObject<?> obj = (DomainObject<?>) entity;
        if (obj.hasHistory()) {
            final DomainHistoryObject<?> hist = HistoryObjectFactory.create(
                    obj, type, DataServiceBean.getCurrentHistoryUser());

            final StatelessSession session = persister.getFactory()
                    .openStatelessSession();
            Transaction tx = session.beginTransaction();
            session.insert(hist);
            tx.commit();
            session.close();

            if (logger.isDebugLoggingEnabled()) {
                logger.logDebug(String.format("%s %s[%s, v=%s]", type,
                        obj.getClass().getSimpleName(), obj.getKey(),
                        hist.getObjVersion()));
            }
        }
    }
}
项目:convertigo-engine    文件:HibernateHelper.java   
public int update(final String query) {
    final int[] updated = {0};

    retry(new Runnable() {
        @Override
        public void run() {
            StatelessSession session = getSession();
            try {
                updated[0] = session.createQuery(query).executeUpdate();
            } finally {
                session.close();
            }
        }
    });
    return updated[0];
}
项目:convertigo-engine    文件:HibernateTicketManager.java   
public synchronized Ticket peekTicket() throws BillingException {
    final Ticket[] ticket = {null}; 
    hibernateHelper.retry(new Runnable() {
        @Override
        public void run() {
            StatelessSession session = hibernateHelper.getSession();
            try {
                ticket[0] = (Ticket) session.createCriteria(Ticket.class).setMaxResults(1).uniqueResult();;
                if (log.isDebugEnabled()) {
                    log.debug("(HibernateTicketManager) peekTicket " + ticket[0]);
                }
            } finally {
                session.close();
            }
        }
    });
    return ticket[0];
}
项目:openbravo-brazil    文件:DalSessionFactory.java   
/**
 * Note method sets user session information in the database and opens a connection for this.
 */
public StatelessSession openStatelessSession(Connection connection) {
  // NOTE: workaround for this issue:
  // http://opensource.atlassian.com/projects/hibernate/browse/HHH-3529
  final StatelessSession session = delegateSessionFactory.openStatelessSession(connection);
  final ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
  try {
    Thread.currentThread().setContextClassLoader(BorrowedConnectionProxy.class.getClassLoader());
    Connection conn = ((SessionImplementor) session).connection();
    SessionInfo.initDB(conn, OBPropertiesProvider.getInstance().getOpenbravoProperties()
        .getProperty("bbdd.rdbms"));
    SessionInfo.setDBSessionInfo(conn);
  } finally {
    Thread.currentThread().setContextClassLoader(currentLoader);
  }
  return session;
}
项目:development    文件:HibernateEventListener.java   
private void removeLocalization(EntityPersister persister, Object entity) {
    if (entity instanceof DomainObject<?>) {
        DomainObject<?> obj = (DomainObject<?>) entity;
        List<LocalizedObjectTypes> objType = obj.getLocalizedObjectTypes();
        if (objType.size() > 0) {
            long key = obj.getKey();
            final StatelessSession session = persister.getFactory()
                    .openStatelessSession();
            Transaction tx = session.beginTransaction();
            org.hibernate.Query query = session
                    .createQuery("DELETE FROM LocalizedResource WHERE objectKey = :objectKey AND objectType IN (:objectType)");
            query.setParameter("objectKey", Long.valueOf(key));
            query.setParameterList("objectType", objType);
            query.executeUpdate();
            tx.commit();
            session.close();
        }
    }
}
项目:development    文件:HibernateEventListener.java   
private void createHistory(EntityPersister persister, Object entity,
        ModificationType type) {
    if (entity instanceof DomainObject<?>) {
        DomainObject<?> obj = (DomainObject<?>) entity;
        if (obj.hasHistory()) {
            final DomainHistoryObject<?> hist = HistoryObjectFactory
                    .create(obj, type,
                            DataServiceBean.getCurrentHistoryUser());

            final StatelessSession session = persister.getFactory()
                    .openStatelessSession();
            Transaction tx = session.beginTransaction();
            session.insert(hist);
            tx.commit();
            session.close();

            if (logger.isDebugLoggingEnabled()) {
                logger.logDebug(String.format("%s %s[%s, v=%s]", type, obj
                        .getClass().getSimpleName(), Long.valueOf(obj
                        .getKey()), Long.valueOf(hist.getObjVersion())));
            }
        }
    }
}
项目:xap-openspaces    文件:StatelessHibernateExternalDataSource.java   
private void executePartialUpdate(StatelessSession session, BulkItem bulkItem) {
    if (logger.isTraceEnabled()) {
        logger.trace("Partial Update Entry [" + bulkItem.toString() + "]");
    }

    // filter non mapped properties 
    final Map<String, Object> itemValues = filterItemValue(bulkItem.getTypeName(), bulkItem.getItemValues());

    String hql = getPartialUpdateHQL(bulkItem, itemValues);

    Query query = session.createQuery(hql);

    for (Map.Entry<String, Object> updateEntry : itemValues.entrySet()) {
        query.setParameter(updateEntry.getKey(), updateEntry.getValue());
    }
    query.setParameter("id_" +bulkItem.getIdPropertyName() ,bulkItem.getIdPropertyValue());
    query.executeUpdate();
}
项目:xap-openspaces    文件:StatelessHibernateExternalDataSource.java   
protected boolean exists(BulkItem bulkItem, StatelessSession session) {

    Criteria criteria = null;
    switch (bulkItem.getOperation()) {
        case BulkItem.REMOVE:
        case BulkItem.WRITE:
        case BulkItem.UPDATE:
            Object entry = bulkItem.getItem();
            criteria = session.createCriteria(entry.getClass().getName());
            ClassMetadata classMetaData = getSessionFactory().getClassMetadata(entry.getClass());
            criteria.add(Restrictions.idEq(classMetaData.getIdentifier(entry)));
            criteria.setProjection(Projections.rowCount());
            return ((Number) criteria.uniqueResult()).intValue() > 0;
        case BulkItem.PARTIAL_UPDATE:
            criteria = session.createCriteria(bulkItem.getTypeName());
            criteria.add(Restrictions.idEq(bulkItem.getIdPropertyValue()));
            criteria.setProjection(Projections.rowCount());
            return ((Number) criteria.uniqueResult()).intValue() > 0;
       default:
            return false;
    }
}
项目:cacheonix-core    文件:StatelessSessionTest.java   
public void testRefresh() {
    StatelessSession ss = getSessions().openStatelessSession();
    Transaction tx = ss.beginTransaction();
    Paper paper = new Paper();
    paper.setColor( "whtie" );
    ss.insert( paper );
    tx.commit();
    ss.close();

    ss = getSessions().openStatelessSession();
    tx = ss.beginTransaction();
    Paper p2 = ( Paper ) ss.get( Paper.class, paper.getId() );
    p2.setColor( "White" );
    ss.update( p2 );
    tx.commit();
    ss.close();

    ss = getSessions().openStatelessSession();
    tx = ss.beginTransaction();
    assertEquals( "whtie", paper.getColor() );
    ss.refresh( paper );
    assertEquals( "White", paper.getColor() );
    ss.delete( paper );
    tx.commit();
    ss.close();
}
项目:GameServerFramework    文件:DataSource.java   
static boolean usingStatelessSession(Consumer<StatelessSession> action) {
    if (sessionFactory != null) {
        StatelessSession session = sessionFactory.openStatelessSession();
        try {
            Transaction transaction = session.beginTransaction();
            action.accept(session);
            transaction.commit();
            return true;
        } catch (Throwable e) {
            return false;
        } finally {
            session.close();
        }
    }
    return false;
}
项目:cosmo    文件:ItemDaoImpl.java   
@SuppressWarnings("unchecked")
public <STAMP_TYPE extends Stamp> STAMP_TYPE findStampByInternalItemUid(String internalItemUid,
        Class<STAMP_TYPE> clazz) {
    try (StatelessSession session = this.openStatelessSession()){

        List<Stamp> stamps = (List<Stamp>) session.createNamedQuery("item.stamps.by.uid")
                .setParameter("uid", internalItemUid)
                .setHint(AvailableSettings.JPA_SHARED_CACHE_STORE_MODE, null)
                .setHint(AvailableSettings.JPA_SHARED_CACHE_RETRIEVE_MODE, null)
                .getResultList();
        for (Stamp stamp : stamps) {
            if (clazz.isInstance(stamp)) {
                return clazz.cast(stamp);
            }
        }
    } catch (HibernateException e) {
        throw SessionFactoryUtils.convertHibernateAccessException(e);
    }
    return null;
}
项目:java-classic-playground    文件:Program.java   
private static void runStatelessHql() throws Exception {
  Stopwatch watch = Stopwatch.createStarted();
  StatelessSession statelessSession = sessionFactory.openStatelessSession();
  try {
    statelessSession.getTransaction().begin();
    Query query = statelessSession
        .createQuery(
            " SELECT d.id, d.firstName, d.lastName, c.id, c.make " + " FROM Driver d "
                + " LEFT JOIN d.cars c WHERE index(c) LIKE 'Good'").setFetchSize(0).setReadOnly(true);

    ScrollableResults scroll = query.scroll(ScrollMode.FORWARD_ONLY);
    while (scroll.next()) {
      LOG.info("Entry " + scroll.get(0));
    }
    statelessSession.getTransaction().commit();
  } catch (Exception ex) {
    statelessSession.getTransaction().rollback();
    throw ex;
  } finally {
    statelessSession.close();
  }
  LOG.info("StatelessHql:=" + watch.toString());
}
项目:debop4j    文件:StatelessTool.java   
/**
 * 지정한 session으로부터 StatelessSession을 생성한 후 작업을 수행하고, 닫습니다.  @param session the session
 *
 * @param action the action
 */
public static void executeTransactional(Session session, Action1<StatelessSession> action) {
    if (log.isDebugEnabled())
        log.debug("StatelessSession을 이용하여 Transaction 하에서 특정 작업을 수행합니다.");

    StatelessSession stateless = openStatelessSession(session);
    Transaction tx = null;

    try {
        tx = stateless.beginTransaction();
        action.perform(stateless);
        tx.commit();
    } catch (Exception e) {
        log.error("StatelessSession을 이용한 작업에 실패했습니다. rollback 합니다.", e);
        if (tx != null)
            tx.rollback();
        throw new RuntimeException(e);
    } finally {
        stateless.close();
    }
}
项目:debop4j    文件:StatelessTool.java   
/**
 * Execute transactional.
 *
 * @param session the session
 * @param actions the actions
 */
public static void executeTransactional(Session session, Iterable<Action1<StatelessSession>> actions) {
    if (log.isDebugEnabled())
        log.debug("StatelessSession을 이용하여 Transaction 하에서 특정 작업을 수행합니다.");

    StatelessSession stateless = openStatelessSession(session);
    Transaction tx = null;

    try {
        tx = stateless.beginTransaction();
        for (Action1<StatelessSession> action : actions) {
            action.perform(stateless);
        }
        tx.commit();
    } catch (Exception e) {
        log.error("StatelessSession에서 작업이 실패했습니다. rollback 합니다.", e);
        if (tx != null)
            tx.rollback();
        throw new RuntimeException(e);
    } finally {
        stateless.close();
    }
}
项目:debop4j    文件:StatelessTool.java   
/**
 * Execute the actions.
 *
 * @param session the session
 * @param actions the actions
 */
public static void execute(Session session, Iterable<Action1<StatelessSession>> actions) {
    if (log.isDebugEnabled())
        log.debug("StatelessSession을 이용하여 특정 작업을 수행합니다.");

    StatelessSession stateless = openStatelessSession(session);
    try {
        for (Action1<StatelessSession> action : actions)
            action.perform(stateless);
    } catch (Exception e) {
        log.error("StatelessSession에서 작업이 실패했습니다.", e);
        throw new RuntimeException(e);
    } finally {
        stateless.close();
    }
}
项目:caelum-fj91-projeto    文件:Gera1MDeRegistros.java   
@Path("/gerarTransacoes")
public void gerar() throws IOException {
    StatelessSession session = sessionFactory.openStatelessSession();
    Random random = new Random();
    Transaction transaction = session.beginTransaction();
    for (int i = 0; i < 1000000; i++) {
        System.out.println("Adicionando transacao " + i);
        Transacao transacao = new Transacao();
        transacao.setTipoDeTransacao(Tipo.values()[random.nextInt(2)]);
        transacao.setData(new GregorianCalendar(random.nextInt(6) + 2006,
                random.nextInt(12), random.nextInt(29)));
        transacao.setValor(new BigDecimal(random.nextDouble() * 10000));
        session.insert(transacao);
    }
    transaction.commit();
}
项目:caelum-fj91-projeto    文件:AumentarValoresDasTransacoes.java   
@Path("/stateless")
public void aumentarStatelessSession(){
    long antes = System.currentTimeMillis();
    StatelessSession statelessSession = factory.openStatelessSession();
    ScrollableResults results = statelessSession.createCriteria(Transacao.class).setFetchSize(QTD_REGISTROS).scroll();

    Transaction transaction = statelessSession.beginTransaction();

    while(results.next()) {
        Transacao transacao = (Transacao) results.get()[0];
        transacao.setValor(transacao.getValor().multiply(new BigDecimal("1.1")));
        statelessSession.update(transacao);
    }
    transaction.commit();

    long tempo = System.currentTimeMillis()-antes;
    System.out.printf("Tempo gasto %dms%n", tempo);
    result.include("mensagem", "Atualizacao realizada com sucesso (" + tempo + "ms)");
    result.forwardTo(IndexController.class).index();
}
项目:convertigo-engine    文件:HibernateHelper.java   
public void insert(final Object obj) {
    retry(new Runnable() {
        @Override
        public void run() {
            StatelessSession session = getSession();
            try {
                session.insert(obj);
            } finally {
                session.close();
            }
        }
    });
}
项目:convertigo-engine    文件:HibernateHelper.java   
public void delete(final Object obj) {
    retry(new Runnable() {
        @Override
        public void run() {
            StatelessSession session = getSession();
            try {
                session.delete(obj);
            } finally {
                session.close();
            }
        }
    });
}
项目:convertigo-engine    文件:HibernateHelper.java   
public synchronized StatelessSession getSession() {
    if (sessionFactory == null) {
        try {
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (HibernateException e) {
            log.warn("(HibernateHelper) Hibernate session factory creation failed", e);
            throw new RuntimeException("(HibernateHelper) Hibernate session factory creation failed", e);
        }
    }
    return sessionFactory.openStatelessSession();
}
项目:interview-preparation    文件:StatelessSessionExample.java   
public static void main(String[] args) {

        final SessionFactory sessionFactory = JavaHibernateUtil.getSessionFactory();
        final StatelessSession session = sessionFactory.openStatelessSession();
        final Transaction transaction = session.getTransaction();
        transaction.begin();
        final User user = new User();
        user.setUsername("Stateless Session creation");
        session.insert(user);
        transaction.commit();
        // session.close();
        sessionFactory.close();
    }
项目:openbravo-brazil    文件:DalSessionFactory.java   
/**
 * Note method sets user session information in the database and opens a connection for this.
 */
public StatelessSession openStatelessSession() {
  // NOTE: workaround for this issue:
  // http://opensource.atlassian.com/projects/hibernate/browse/HHH-3529
  final StatelessSession session = delegateSessionFactory.openStatelessSession();
  final ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
  try {
    Thread.currentThread().setContextClassLoader(BorrowedConnectionProxy.class.getClassLoader());
    Connection conn = ((SessionImplementor) session).connection();
    SessionInfo.initDB(conn, OBPropertiesProvider.getInstance().getOpenbravoProperties()
        .getProperty("bbdd.rdbms"));
    SessionInfo.setDBSessionInfo(conn);
  } finally {
    Thread.currentThread().setContextClassLoader(currentLoader);
  }
  return session;
}
项目:openbravo-brazil    文件:DalPerformanceProxyTest.java   
@Test
public void testStatelessBPCreate() {
  try {
    setTestAdminContext();

    final StatelessSession session = SessionFactoryController.getInstance().getSessionFactory()
        .openStatelessSession();
    session.beginTransaction();
    for (int i = 0; i < CNT; i++) {
      BusinessPartner bp = OBProvider.getInstance().get(BusinessPartner.class);

      // Generating random strings for testing
      UUID name = UUID.randomUUID();
      UUID key = UUID.randomUUID();

      bp.setName(name.toString());
      bp.setSearchKey(key.toString());

      bp.setBusinessPartnerCategory(createReferencedObject(Category.class, TEST_BP_CATEGORY_ID));

      // note the following things are currently done in the OBInterceptor
      // it is quite easy to add a util method which can do this in a generic
      // way for any business object
      bp.setOrganization(createReferencedObject(Organization.class, TEST_ORG_ID));
      bp.setClient(createReferencedObject(Client.class, TEST_CLIENT_ID));
      bp.setCreatedBy(createReferencedObject(User.class, "100"));
      bp.setCreationDate(new Date());
      bp.setUpdatedBy(createReferencedObject(User.class, "100"));
      bp.setUpdated(new Date());

      session.insert(BusinessPartner.ENTITY_NAME, bp);
      // session.refresh(BusinessPartner.ENTITY_NAME, bp);
      Assert.assertTrue(bp.getId() != null);
    }
    session.getTransaction().commit();
  } catch (Exception e) {
    throw new OBException(e);
  }
}
项目:ephesoft    文件:DynamicHibernateDao.java   
/**
 * To create, update or insert query.
 * 
 * @param session StatelessSession
 * @param queryString String
 * @param params Object
 * @return SQLQuery
 */
public SQLQuery createUpdateOrInsertQuery(StatelessSession session, String queryString, Object... params) {
    SQLQuery sqlQuery = session.createSQLQuery(queryString);

    if (params != null) {
        int pos = 1;
        for (Object p : params) {
            sqlQuery.setParameter(pos++, p);
        }
    }
    return sqlQuery;
}
项目:xap-openspaces    文件:StatelessHibernateExternalDataSource.java   
private void executeWriteIfExists(StatelessSession session, BulkItem bulkItem) {
    Object entry = bulkItem.getItem();
    if (exists(bulkItem, session)) {
        if (logger.isTraceEnabled()) {
            logger.trace("[Exists WRITE] Update Entry [" + entry + "]");
        }
        session.update(entry);
    } else {
        if (logger.isTraceEnabled()) {
            logger.trace("[Exists WRITE] Insert Entry [" + entry + "]");
        }
        session.insert(entry);
    }
}
项目:xap-openspaces    文件:StatelessHibernateExternalDataSource.java   
private void executeUpdateIfExists(StatelessSession session, BulkItem bulkItem) {
    Object entry = bulkItem.getItem();
    if (exists(bulkItem, session)) {
        if (logger.isTraceEnabled()) {
            logger.trace("[Exists UPDATE] Update Entry [" + entry + "]");
        }
        session.update(entry);
    } else {
        if (logger.isTraceEnabled()) {
            logger.trace("[Exists UPDATE] Insert Entry [" + entry + "]");
        }
        session.insert(entry);
    }
}
项目:xap-openspaces    文件:StatelessHibernateExternalDataSource.java   
private void executeRemoveIfExists(StatelessSession session, BulkItem bulkItem) {
    Object entry = bulkItem.getItem();
    if (exists(bulkItem, session)) {
        if (logger.isTraceEnabled()) {
            logger.trace("[Exists REMOVE] Deleting Entry [" + entry + "]");
        }
        session.delete(entry);
    }
}
项目:xap-openspaces    文件:StatelessHibernateExternalDataSource.java   
private void executeUpdate(StatelessSession session, BulkItem bulkItem) {
    Object entry = bulkItem.getItem();

    if (logger.isTraceEnabled()) {
        logger.trace("[Optimistic UPDATE] Update Entry [" + entry + "]");
    }
    session.update(entry);
}
项目:xap-openspaces    文件:StatelessHibernateExternalDataSource.java   
private void executeWrite(StatelessSession session, BulkItem bulkItem) {
    Object entry = bulkItem.getItem();

    if (logger.isTraceEnabled()) {
        logger.trace("[Optimistic WRITE] Write Entry [" + entry + "]");
    }
    session.insert(entry);
}
项目:xap-openspaces    文件:StatelessHibernateExternalDataSource.java   
private void executeRemove(StatelessSession session, BulkItem bulkItem) {
    Object entry = bulkItem.getItem();
    if (logger.isTraceEnabled()) {
        logger.trace("[Optimistic REMOVE] Deleting Entry [" + entry + "]");
    }
    session.delete(entry);
}
项目:xap-openspaces    文件:HibernateIteratorUtils.java   
public static Query createQueryFromSQLQuery(SQLQuery<?> sqlQuery, StatelessSession session) {
    String select = sqlQuery.getFromQuery();
    Query query = session.createQuery(select);
    Object[] preparedValues = sqlQuery.getParameters();
    if (preparedValues != null) {
        for (int i = 0; i < preparedValues.length; i++) {
            query.setParameter(i, preparedValues[i]);
        }
    }
    query.setReadOnly(true);
    return query;
}
项目:xap-openspaces    文件:HibernateIteratorUtils.java   
public static Query createQueryFromDataSourceSQLQuery(DataSourceSQLQuery dataSourceSQLQuery, StatelessSession session) {
    String select = dataSourceSQLQuery.getFromQuery();
    Query query = session.createQuery(select);
    Object[] preparedValues = dataSourceSQLQuery.getQueryParameters();
    if (preparedValues != null) {
        for (int i = 0; i < preparedValues.length; i++) {
            query.setParameter(i, preparedValues[i]);
        }
    }
    query.setReadOnly(true);
    return query;
}
项目:cacheonix-core    文件:StatelessSessionTest.java   
public void testHqlBulk() {
    StatelessSession ss = getSessions().openStatelessSession();
    Transaction tx = ss.beginTransaction();
    Document doc = new Document("blah blah blah", "Blahs");
    ss.insert(doc);
    Paper paper = new Paper();
    paper.setColor( "White" );
    ss.insert(paper);
    tx.commit();

    tx = ss.beginTransaction();
    int count = ss.createQuery( "update Document set name = :newName where name = :oldName" )
            .setString( "newName", "Foos" )
            .setString( "oldName", "Blahs" )
            .executeUpdate();
    assertEquals( "hql-update on stateless session", 1, count );
    count = ss.createQuery( "update Paper set color = :newColor" )
            .setString( "newColor", "Goldenrod" )
            .executeUpdate();
    assertEquals( "hql-update on stateless session", 1, count );
    tx.commit();

    tx = ss.beginTransaction();
    count = ss.createQuery( "delete Document" ).executeUpdate();
    assertEquals( "hql-delete on stateless session", 1, count );
    count = ss.createQuery( "delete Paper" ).executeUpdate();
    assertEquals( "hql-delete on stateless session", 1, count );
    tx.commit();
    ss.close();
}
项目:cacheonix-core    文件:StatelessSessionTest.java   
public void testInitId() {
    StatelessSession ss = getSessions().openStatelessSession();
    Transaction tx = ss.beginTransaction();
    Paper paper = new Paper();
    paper.setColor( "White" );
    ss.insert(paper);
    assertNotNull( paper.getId() );
    tx.commit();

    tx = ss.beginTransaction();
    ss.delete( ss.get( Paper.class, paper.getId() ) );
    tx.commit();
    ss.close();
}
项目:GameServerFramework    文件:DataSource.java   
/**
 * 打开会话
 *
 * @return Hibernate 数据会话
 */
public static StatelessSession openStatelessSession() {

    if (sessionFactory == null) {
        log.error("[DataSource]  Plase First Call Initialize Function . !");
        return null;
    }

    StatelessSession session = sessionFactory.openStatelessSession();
    return session;
}
项目:monasca-thresh    文件:AlarmSqlImpl.java   
@SuppressWarnings("unchecked")
private void getAlarmedMetrics(final StatelessSession session,
                               final Map<String, Alarm> alarmMap,
                               final Map<String, String> tenantIdMap,
                               final LookupHelper binder) {

  String rawHQLQuery =
      "select a.id, md.name as metric_def_name, mdg.id.name, mdg.value, mdg.id.dimensionSetId from MetricDefinitionDb as md, "
          + "MetricDefinitionDimensionsDb as mdd, " + "AlarmMetricDb as am, " + "AlarmDb as a, "
          + "MetricDimensionDb as mdg where md.id = mdd.metricDefinition.id and mdd.id = am.alarmMetricId.metricDefinitionDimensions.id and "
          + "am.alarmMetricId.alarm.id = a.id and mdg.id.dimensionSetId = mdd.metricDimensionSetId and %s";

  final Query query = binder.apply(session.createQuery(binder.formatHQL(rawHQLQuery)));
  final List<Object[]> metricRows = query.list();
  final HashSet<String> existingAlarmId = Sets.newHashSet();
  final Map<String, List<MetricDefinition>> alarmMetrics = this.getAlarmedMetrics(metricRows);

  for (final Object[] row : metricRows) {
    final String alarmId = (String) row[ALARM_ID];
    final Alarm alarm = alarmMap.get(alarmId);
    // This shouldn't happen but it is possible an Alarm gets created after the AlarmDefinition is
    // marked deleted and any existing alarms are deleted but before the Threshold Engine gets the
    // AlarmDefinitionDeleted message
    if (alarm == null) {
      continue;
    }
    if (!existingAlarmId.contains(alarmId)) {
      List<MetricDefinition> mdList = alarmMetrics.get(alarmId);
      for (MetricDefinition md : mdList) {
        alarm.addAlarmedMetric(new MetricDefinitionAndTenantId(md, tenantIdMap.get(alarmId)));
      }

    }
    existingAlarmId.add(alarmId);
  }
}
项目:monasca-api    文件:AlarmDefinitionSqlRepoImpl.java   
@Override
public String exists(final String tenantId,
                     final String name) {
  logger.trace(ORM_LOG_MARKER, "exists(...) entering...");

  StatelessSession session = null;
  try {
    session = sessionFactory.openStatelessSession();

    List<?> ids = session
        .createCriteria(AlarmDefinitionDb.class)
        .add(Restrictions.eq("tenantId", tenantId))
        .add(Restrictions.eq("name", name))
        .add(Restrictions.isNull("deletedAt"))
        .setProjection(Projections.property("id"))
        .setMaxResults(1)
        .list();

    final String existingId = CollectionUtils.isEmpty(ids) ? null : (String) ids.get(0);

    if (null == existingId) {
      logger.debug(ORM_LOG_MARKER, "No AlarmDefinition matched tenantId={} and name={}", tenantId, name);
    }

    return existingId;
  } finally {
    if (session != null) {
      session.close();
    }
  }
}
项目:monasca-api    文件:AlarmHibernateUtils.java   
public List<String> findAlarmIds(String tenantId, Map<String, String> dimensions) {
  logger.trace(BaseSqlRepo.ORM_LOG_MARKER, "findAlarmIds(...) entering");
  List<String> alarmIdList = null;

  StatelessSession session = null;
  try {
    session = sessionFactory.openStatelessSession();

    final String sql = this.findAlarmQueryString(dimensions);
    final Query query = session
        .createSQLQuery(sql)
        .setString("tenantId", tenantId);

    this.bindDimensionsToQuery(query, dimensions);

    @SuppressWarnings("unchecked") List<Object[]> rows = query.list();
    alarmIdList = Lists.newArrayListWithCapacity(rows.size());
    for (Object[] row : rows) {
      String id = (String) row[0];
      alarmIdList.add(id);
    }

  } finally {
    if (session != null) {
      session.close();
    }
  }

  // no need to check if alarmIdList != null, because in case of exception method
  // will leave immediately, otherwise list wont be null.
  return alarmIdList;
}
项目:debop4j    文件:StatelessTool.java   
/**
 * Execute the action.
 *
 * @param session the session
 * @param action  the action
 */
public static void execute(Session session, Action1<StatelessSession> action) {
    if (log.isDebugEnabled())
        log.debug("StatelessSession을 이용하여 특정 작업을 수행합니다.");

    StatelessSession stateless = openStatelessSession(session);
    try {
        action.perform(stateless);
    } catch (Exception e) {
        log.error("StatelessSession에서 작업이 실패했습니다.", e);
        throw new RuntimeException(e);
    } finally {
        stateless.close();
    }
}