org.hibernate.StatelessSession Java Examples

The following examples show how to use org.hibernate.StatelessSession. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StatelessSessionTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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();
}
 
Example #2
Source File: HibernateEventListener.java    From development with Apache License 2.0 6 votes vote down vote up
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();
        }
    }
}
 
Example #3
Source File: HibernateEventListener.java    From development with Apache License 2.0 6 votes vote down vote up
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())));
            }
        }
    }
}
 
Example #4
Source File: WorldRepository.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Collection<World> findReadonly(Set<Integer> ids) {
    try (StatelessSession s = sf.openStatelessSession()) {
        //The rules require individual load: we can't use the Hibernate feature which allows load by multiple IDs as one single operation
        ArrayList l = new ArrayList<>(ids.size());
        for (Integer id : ids) {
            l.add(singleStatelessWorldLoad(s,id));
        }
        return l;
    }
}
 
Example #5
Source File: StatelessSessionTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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();
}
 
Example #6
Source File: WorldRepository.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * This method is not required (nor specified) by the benchmark rules,
 * but is quite handy to seed a local database and be able to experiment
 * with the app locally.
 */
@Transactional
public void createData() {
    try (StatelessSession statelessSession = sf.openStatelessSession()) {
        final ThreadLocalRandom random = ThreadLocalRandom.current();
        for (int i=1; i<=10000; i++) {
            final World world = new World();
            world.setId(i);
            world.setRandomNumber(1 + random.nextInt(10000));
            statelessSession.insert(world);
        }
    }
}
 
Example #7
Source File: DeletedObjectPostDeleteEventListener.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onPostDelete( PostDeleteEvent event )
{
    if ( IdentifiableObject.class.isInstance( event.getEntity() )
        && MetadataObject.class.isInstance( event.getEntity() )
        && !EmbeddedObject.class.isInstance( event.getEntity() ) )
    {
        IdentifiableObject identifiableObject = (IdentifiableObject) event.getEntity();
        DeletedObject deletedObject = new DeletedObject( identifiableObject );
        deletedObject.setDeletedBy( getUsername() );

        StatelessSession session = event.getPersister().getFactory().openStatelessSession();
        session.beginTransaction();

        try
        {
            session.insert( deletedObject );
            session.getTransaction().commit();
        }
        catch ( Exception ex )
        {
            log.error( "Failed to save DeletedObject: "+ deletedObject );
            session.getTransaction().rollback();
        }
        finally
        {
            session.close();
        }
    }
}
 
Example #8
Source File: DeletedObjectPostInsertEventListener.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onPostInsert( PostInsertEvent event )
{
    if ( IdentifiableObject.class.isInstance( event.getEntity() )
        && MetadataObject.class.isInstance( event.getEntity() )
        && !EmbeddedObject.class.isInstance( event.getEntity() ) )
    {
        StatelessSession session = event.getPersister().getFactory().openStatelessSession();
        session.beginTransaction();

        try
        {
            List<DeletedObject> deletedObjects = deletedObjectService
                .getDeletedObjects( new DeletedObjectQuery( (IdentifiableObject) event.getEntity() ) );

            deletedObjects.forEach( deletedObject -> session.delete( deletedObject ) );

            session.getTransaction().commit();
        }
        catch ( Exception ex )
        {
            log.error( "Failed to delete DeletedObject for:" + event.getEntity() );
            session.getTransaction().rollback();
        }
        finally
        {
            session.close();
        }
    }
}
 
Example #9
Source File: FortuneRepository.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public List<Fortune> findAllStateless() {
    try (StatelessSession s = sf.openStatelessSession()) {
        CriteriaBuilder criteriaBuilder = sf.getCriteriaBuilder();
        CriteriaQuery<Fortune> fortuneQuery = criteriaBuilder.createQuery(Fortune.class);
        Root<Fortune> from = fortuneQuery.from(Fortune.class);
        fortuneQuery.select(from);
        return s.createQuery(fortuneQuery).getResultList();
    }
}
 
Example #10
Source File: AlarmSqlImpl.java    From monasca-thresh with Apache License 2.0 5 votes vote down vote up
@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);
  }
}
 
Example #11
Source File: StatelessSessionTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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();
}
 
Example #12
Source File: CacheHibernateStoreFactorySelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public StatelessSession openStatelessSession() {
    return null;
}
 
Example #13
Source File: SessionFactoryWrapper.java    From lemon with Apache License 2.0 4 votes vote down vote up
public StatelessSession openStatelessSession(Connection connection) {
    return sessionFactoryImplementor.openStatelessSession(connection);
}
 
Example #14
Source File: CacheHibernateStoreFactorySelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public StatelessSession openStatelessSession(Connection conn) {
    return null;
}
 
Example #15
Source File: CacheHibernateStoreFactorySelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public StatelessSession openStatelessSession() {
    return null;
}
 
Example #16
Source File: CacheHibernateStoreFactorySelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public StatelessSession openStatelessSession(Connection conn) {
    return null;
}
 
Example #17
Source File: AlarmSqlImpl.java    From monasca-thresh with Apache License 2.0 4 votes vote down vote up
private List<Alarm> createAlarms(final StatelessSession session,
                                 final List<Object[]> alarmList,
                                 final LookupHelper lookupHelper) {
  final List<Alarm> alarms = Lists.newArrayListWithCapacity(alarmList.size());

  if (alarmList.isEmpty()) {
    return alarms;
  }

  List<SubAlarm> subAlarms = null;

  String prevAlarmId = null;
  Alarm alarm = null;

  final Map<String, Alarm> alarmMap = Maps.newHashMapWithExpectedSize(alarmList.size());
  final Map<String, String> tenantIdMap = Maps.newHashMapWithExpectedSize(alarmList.size());

  for (Object[] alarmRow : alarmList) {
    final String alarmId = (String) alarmRow[ALARM_ID];
    if (!alarmId.equals(prevAlarmId)) {
      if (alarm != null) {
        alarm.setSubAlarms(subAlarms);
      }
      alarm = new Alarm();
      alarm.setId(alarmId);
      alarm.setAlarmDefinitionId((String) alarmRow[ALARM_DEFINITION_ID]);
      alarm.setState((AlarmState) alarmRow[ALARM_STATE]);
      subAlarms = Lists.newArrayListWithExpectedSize(alarmList.size());
      alarms.add(alarm);
      alarmMap.put(alarmId, alarm);
      tenantIdMap.put(alarmId, (String) alarmRow[TENANT_ID]);
    }

    subAlarms.add(new SubAlarm(
        (String) alarmRow[SUB_ALARM_ID],
        alarmId,
        new SubExpression(
            (String) alarmRow[SUB_EXPRESSION_ID],
            AlarmSubExpression.of((String) alarmRow[ALARM_EXPRESSION])
        )
    ));

    prevAlarmId = alarmId;
  }

  if (alarm != null) {
    alarm.setSubAlarms(subAlarms);
  }

  if (!alarms.isEmpty()) {
    this.getAlarmedMetrics(session, alarmMap, tenantIdMap, lookupHelper);
  }

  return alarms;
}
 
Example #18
Source File: WorldRepository.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public World findSingleAndStateless(int id) {
    try (StatelessSession ss = sf.openStatelessSession()) {
        return singleStatelessWorldLoad(ss,id);
    }
}
 
Example #19
Source File: WorldRepository.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static World singleStatelessWorldLoad(final StatelessSession ss, final Integer id) {
    return (World) ss.get(World.class, id);
}
 
Example #20
Source File: SessionFactoryWrapper.java    From lemon with Apache License 2.0 4 votes vote down vote up
public StatelessSession openStatelessSession() {
    return sessionFactoryImplementor.openStatelessSession();
}
 
Example #21
Source File: LegacySessionFactory.java    From judgels with GNU General Public License v2.0 4 votes vote down vote up
@Override
public StatelessSession openStatelessSession() {
    return null;
}
 
Example #22
Source File: CacheHibernateStoreFactorySelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public StatelessSession openStatelessSession(Connection conn) {
    return null;
}
 
Example #23
Source File: CacheHibernateStoreFactorySelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override public StatelessSession openStatelessSession() {
    return null;
}
 
Example #24
Source File: StatelessSessionTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testCreateUpdateReadDelete() {
	StatelessSession ss = getSessions().openStatelessSession();
	Transaction tx = ss.beginTransaction();
	Document doc = new Document("blah blah blah", "Blahs");
	ss.insert(doc);
	assertNotNull( doc.getName() );
	Date initVersion = doc.getLastModified();
	assertNotNull( initVersion );
	tx.commit();
	
	tx = ss.beginTransaction();
	doc.setText("blah blah blah .... blah");
	ss.update(doc);
	assertNotNull( doc.getLastModified() );
	assertNotSame( doc.getLastModified(), initVersion );
	tx.commit();
	
	tx = ss.beginTransaction();
	doc.setText("blah blah blah .... blah blay");
	ss.update(doc);
	tx.commit();
	
	Document doc2 = (Document) ss.get(Document.class.getName(), "Blahs");
	assertEquals("Blahs", doc2.getName());
	assertEquals(doc.getText(), doc2.getText());
			
	doc2 = (Document) ss.createQuery("from Document where text is not null").uniqueResult();
	assertEquals("Blahs", doc2.getName());
	assertEquals(doc.getText(), doc2.getText());
	
	ScrollableResults sr = ss.createQuery("from Document where text is not null")
		.scroll(ScrollMode.FORWARD_ONLY);
	sr.next();
	doc2 = (Document) sr.get(0);
	sr.close();
	assertEquals("Blahs", doc2.getName());
	assertEquals(doc.getText(), doc2.getText());
			
	doc2 = (Document) ss.createSQLQuery("select * from Document")
		.addEntity(Document.class)
		.uniqueResult();
	assertEquals("Blahs", doc2.getName());
	assertEquals(doc.getText(), doc2.getText());
			
	doc2 = (Document) ss.createCriteria(Document.class).uniqueResult();
	assertEquals("Blahs", doc2.getName());
	assertEquals(doc.getText(), doc2.getText());
	
	sr = ss.createCriteria(Document.class).scroll(ScrollMode.FORWARD_ONLY);
	sr.next();
	doc2 = (Document) sr.get(0);
	sr.close();
	assertEquals("Blahs", doc2.getName());
	assertEquals(doc.getText(), doc2.getText());

	tx = ss.beginTransaction();
	ss.delete(doc);
	tx.commit();
	ss.close();

}
 
Example #25
Source File: SessionFactoryImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public StatelessSession openStatelessSession(Connection connection) {
	return new StatelessSessionImpl( connection, this );
}
 
Example #26
Source File: SessionFactoryImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public StatelessSession openStatelessSession() {
	return new StatelessSessionImpl( null, this );
}
 
Example #27
Source File: SessionFactoryStub.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public StatelessSession openStatelessSession(Connection conn) {
	return getImpl().openStatelessSession(conn);
}
 
Example #28
Source File: SessionFactoryStub.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public StatelessSession openStatelessSession() {
	return getImpl().openStatelessSession();
}
 
Example #29
Source File: SessionFactoryImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public StatelessSession openStatelessSession() {
	return new StatelessSessionImpl( sessionFactory, this );
}
 
Example #30
Source File: SessionFactoryImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public StatelessSession openStatelessSession(Connection connection) {
	return withStatelessOptions().connection( connection ).openStatelessSession();
}