public final String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { String entityName = criteriaQuery.getEntityName(criteria, propertyName); String actualPropertyName = criteriaQuery.getPropertyName(propertyName); String sqlAlias = criteriaQuery.getSQLAlias(criteria, propertyName); SessionFactoryImplementor factory = criteriaQuery.getFactory(); QueryableCollection collectionPersister = getQueryableCollection(entityName, actualPropertyName, factory); String[] collectionKeys = collectionPersister.getKeyColumnNames(); String[] ownerKeys = ((Loadable) factory.getEntityPersister(entityName)).getIdentifierColumnNames(); String innerSelect = "(select 1 from " + collectionPersister.getTableName() + " where " + new ConditionFragment() .setTableAlias(sqlAlias) .setCondition(ownerKeys, collectionKeys) .toFragmentString() + ")"; return excludeEmpty() ? "exists " + innerSelect : "not exists " + innerSelect; }
@Test public void testServiceContributorDiscovery() throws Exception { final ServiceReference sr = bundleContext.getServiceReference(SessionFactory.class.getName()); final SessionFactoryImplementor sfi = (SessionFactoryImplementor) bundleContext.getService(sr); assertNotNull(sfi.getServiceRegistry().getService(SomeService.class)); }
private void addEntityCheckCache(SessionFactoryImplementor sessionFactory) throws Exception { Item item = new Item("chris", "Chris's Item"); beginTx(); try { Session s = sessionFactory.openSession(); s.getTransaction().begin(); s.persist(item); s.getTransaction().commit(); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } beginTx(); try { Session s = sessionFactory.openSession(); Item found = (Item) s.load(Item.class, item.getId()); Statistics stats = sessionFactory.getStatistics(); log.info(stats.toString()); assertEquals(item.getDescription(), found.getDescription()); assertEquals(0, stats.getSecondLevelCacheMissCount()); assertEquals(1, stats.getSecondLevelCacheHitCount()); s.delete(found); s.close(); } catch (Exception e) { setRollbackOnlyTx(e); } finally { commitOrRollbackTx(); } }
@Override public void lock( Serializable id, Object version, Object object, int timeout, SessionImplementor session) { final String sql = determineSql(timeout); SessionFactoryImplementor factory = session.getFactory(); try { try { PreparedStatement st = session .getTransactionCoordinator() .getJdbcCoordinator() .getStatementPreparer() .prepareStatement(sql); try { getLockable().getIdentifierType().nullSafeSet(st, id, 1, session); if (getLockable().isVersioned()) { getLockable() .getVersionType() .nullSafeSet( st, version, getLockable().getIdentifierType().getColumnSpan(factory) + 1, session); } ResultSet rs = session .getTransactionCoordinator() .getJdbcCoordinator() .getResultSetReturn() .extract(st); try { if (!rs.next()) { if (factory.getStatistics().isStatisticsEnabled()) { factory.getStatisticsImplementor().optimisticFailure(getLockable().getEntityName()); } throw new StaleObjectStateException(getLockable().getEntityName(), id); } } finally { session.getTransactionCoordinator().getJdbcCoordinator().release(rs, st); } } finally { session.getTransactionCoordinator().getJdbcCoordinator().release(st); } } catch (SQLException e) { throw session .getFactory() .getSQLExceptionHelper() .convert( e, "could not lock: " + MessageHelper.infoString(getLockable(), id, session.getFactory()), sql); } } catch (JDBCException e) { throw new PessimisticEntityLockException(object, "could not obtain pessimistic lock", e); } }
protected void cleanupCache() { if (sessionFactory != null) { sessionFactory.getCache().evictCollectionRegions(); sessionFactory.getCache().evictDefaultQueryRegion(); sessionFactory.getCache().evictEntityRegions(); sessionFactory.getCache().evictQueryRegions(); sessionFactory.getCache().evictNaturalIdRegions(); } }
private void comparePropertyAndRaiseSOSE( Serializable id, Object oldField, SessionFactoryImplementor factory, boolean b) { // TODO support other entity modes if (b) { if (factory.getStatistics().isStatisticsEnabled()) { factory.getStatisticsImplementor().optimisticFailure(getEntityName()); } throw new StaleObjectStateException(getEntityName(), id); } }
@Override public void sessionFactoryCreated(SessionFactory factory) { SessionFactoryImplementor factoryImplementor = (SessionFactoryImplementor) factory; GridDialect gridDialect = factoryImplementor.getServiceRegistry().getService(GridDialect.class); SessionFactoryLifecycleAwareDialect sessionFactoryAwareDialect = GridDialects.getDialectFacetOrNull(gridDialect, SessionFactoryLifecycleAwareDialect.class); if (sessionFactoryAwareDialect != null) { sessionFactoryAwareDialect.sessionFactoryCreated(factoryImplementor); } }
@Override @SuppressWarnings("unchecked") public <T> T unwrap(Class<T> cls) { if (RegionFactory.class.isAssignableFrom(cls)) { return (T) sessionFactory.getSettings().getRegionFactory(); } if (org.hibernate.Cache.class.isAssignableFrom(cls)) { return (T) sessionFactory.getCache(); } throw new PersistenceException("Hibernate cannot unwrap Cache as " + cls.getName()); }
public void checkVersionAndRaiseSOSE( Serializable id, Object oldVersion, SessionImplementor session, Tuple resultset) { final Object resultSetVersion = gridVersionType.nullSafeGet(resultset, getVersionColumnName(), session, null); final SessionFactoryImplementor factory = getFactory(); if (!gridVersionType.isEqual(oldVersion, resultSetVersion, factory)) { if (factory.getStatistics().isStatisticsEnabled()) { factory.getStatisticsImplementor().optimisticFailure(getEntityName()); } throw new StaleObjectStateException(getEntityName(), id); } }
public Type getHibernateType(int columnPos) throws SQLException { int columnType = resultSetMetaData.getColumnType(columnPos); int scale = resultSetMetaData.getScale(columnPos); int precision = resultSetMetaData.getPrecision(columnPos); int length = precision; if (columnType == 1 && precision == 0) { length = resultSetMetaData.getColumnDisplaySize(columnPos); } return factory .getTypeResolver() .heuristicType( factory.getDialect().getHibernateTypeName(columnType, length, precision, scale)); }
private void evictCache( Object entity, EntityPersister persister, EventSource session, Object[] oldState) { try { SessionFactoryImplementor factory = persister.getFactory(); Set<String> collectionRoles = factory.getCollectionRolesByEntityParticipant(persister.getEntityName()); if (collectionRoles == null || collectionRoles.isEmpty()) { return; } for (String role : collectionRoles) { CollectionPersister collectionPersister = factory.getCollectionPersister(role); if (!collectionPersister.hasCache()) { // ignore collection if no caching is used continue; } // this is the property this OneToMany relation is mapped by String mappedBy = collectionPersister.getMappedByProperty(); if (mappedBy != null) { int i = persister.getEntityMetamodel().getPropertyIndex(mappedBy); Serializable oldId = null; if (oldState != null) { // in case of updating an entity we perhaps have to decache 2 entity collections, this // is the // old one oldId = session.getIdentifier(oldState[i]); } Object ref = persister.getPropertyValue(entity, i); Serializable id = null; if (ref != null) { id = session.getIdentifier(ref); } // only evict if the related entity has changed if (id != null && !id.equals(oldId)) { evict(id, collectionPersister, session); if (oldId != null) { evict(oldId, collectionPersister, session); } } } else { LOG.debug("Evict CollectionRegion " + role); collectionPersister.getCacheAccessStrategy().evictAll(); } } } catch (Exception e) { // don't let decaching influence other logic LOG.error("", e); } }
public void evictAll() { sessionFactory.getCache().evictEntityRegions(); // TODO : if we want to allow an optional clearing of all cache data, the additional calls // would be: // sessionFactory.getCache().evictCollectionRegions(); // sessionFactory.getCache().evictQueryRegions(); }
@SuppressWarnings({"UnnecessaryBoxing", "UnnecessaryUnboxing"}) protected void assertAllDataRemoved() { if (!createSchema()) { return; // no tables were created... } if (!Boolean.getBoolean(VALIDATE_DATA_CLEANUP)) { return; } Session tmpSession = sessionFactory.openSession(); try { List list = tmpSession.createQuery("select o from java.lang.Object o").list(); Map<String, Integer> items = new HashMap<String, Integer>(); if (!list.isEmpty()) { for (Object element : list) { Integer l = items.get(tmpSession.getEntityName(element)); if (l == null) { l = 0; } l = l + 1; items.put(tmpSession.getEntityName(element), l); System.out.println("Data left: " + element); } fail("Data is left in the database: " + items.toString()); } } finally { try { tmpSession.close(); } catch (Throwable t) { // intentionally empty } } }
/** * Create a new SpringSessionContext for the given Hibernate SessionFactory. * * @param sessionFactory the SessionFactory to provide current Sessions for */ public SpringSessionContext(SessionFactoryImplementor sessionFactory) { this.sessionFactory = sessionFactory; JtaPlatform jtaPlatform = sessionFactory.getServiceRegistry().getService(JtaPlatform.class); TransactionManager transactionManager = jtaPlatform.retrieveTransactionManager(); this.jtaSessionContext = (transactionManager != null ? new SpringJtaSessionContext(sessionFactory) : null); }
private void integrate( SessionFactoryServiceRegistry serviceRegistry, SessionFactoryImplementor sessionFactory) { if (!sessionFactory.getSettings().isAutoEvictCollectionCache()) { // feature is disabled return; } if (!sessionFactory.getSettings().isSecondLevelCacheEnabled()) { // Nothing to do, if caching is disabled return; } EventListenerRegistry eventListenerRegistry = serviceRegistry.getService(EventListenerRegistry.class); eventListenerRegistry.appendListeners(EventType.POST_INSERT, this); eventListenerRegistry.appendListeners(EventType.POST_DELETE, this); eventListenerRegistry.appendListeners(EventType.POST_UPDATE, this); }
@Test public void testExtensionPoints() throws Exception { final ServiceReference sr = bundleContext.getServiceReference(SessionFactory.class.getName()); final SessionFactoryImplementor sfi = (SessionFactoryImplementor) bundleContext.getService(sr); assertTrue(TestIntegrator.passed()); Class impl = sfi.getServiceRegistry() .getService(StrategySelector.class) .selectStrategyImplementor(Calendar.class, TestStrategyRegistrationProvider.GREGORIAN); assertNotNull(impl); BasicType basicType = sfi.getTypeResolver().basic(TestTypeContributor.NAME); assertNotNull(basicType); }
@Test public void testTableIdentifiers() { Session session = getNewSession("jboss"); session.beginTransaction(); Invoice orderJboss = new Invoice(); session.save(orderJboss); Assert.assertEquals(Long.valueOf(1), orderJboss.getId()); session.getTransaction().commit(); session.close(); session = getNewSession("acme"); session.beginTransaction(); Invoice orderAcme = new Invoice(); session.save(orderAcme); Assert.assertEquals(Long.valueOf(1), orderAcme.getId()); session.getTransaction().commit(); session.close(); session = getNewSession("jboss"); session.beginTransaction(); session.delete(orderJboss); session.getTransaction().commit(); session.close(); session = getNewSession("acme"); session.beginTransaction(); session.delete(orderAcme); session.getTransaction().commit(); session.close(); sessionFactory.getStatisticsImplementor().clear(); }
/** * Initialize the role of the collection. * * @param collection The collection to be updated by reachability. * @param type The type of the collection. * @param entity The owner of the collection. * @param session The session from which this request originates */ public static void processReachableCollection( PersistentCollection collection, CollectionType type, Object entity, SessionImplementor session) { collection.setOwner(entity); CollectionEntry ce = session.getPersistenceContext().getCollectionEntry(collection); if (ce == null) { // refer to comment in StatefulPersistenceContext.addCollection() throw new HibernateException( "Found two representations of same collection: " + type.getRole()); } // The CollectionEntry.isReached() stuff is just to detect any silly users // who set up circular or shared references between/to collections. if (ce.isReached()) { // We've been here before throw new HibernateException("Found shared references to a collection: " + type.getRole()); } ce.setReached(true); SessionFactoryImplementor factory = session.getFactory(); CollectionPersister persister = factory.getCollectionPersister(type.getRole()); ce.setCurrentPersister(persister); ce.setCurrentKey( type.getKeyOfOwner(entity, session)); // TODO: better to pass the id in as an argument? if (LOG.isDebugEnabled()) { if (collection.wasInitialized()) LOG.debugf( "Collection found: %s, was: %s (initialized)", MessageHelper.collectionInfoString(persister, ce.getCurrentKey(), factory), MessageHelper.collectionInfoString( ce.getLoadedPersister(), ce.getLoadedKey(), factory)); else LOG.debugf( "Collection found: %s, was: %s (uninitialized)", MessageHelper.collectionInfoString(persister, ce.getCurrentKey(), factory), MessageHelper.collectionInfoString( ce.getLoadedPersister(), ce.getLoadedKey(), factory)); } prepareCollectionForUpdate(collection, ce, factory); }
@Test public void testRedeployment() throws Exception { addEntityCheckCache(sessionFactory()); sessionFactory().close(); bindToJndi = false; SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) configuration().buildSessionFactory(serviceRegistry()); addEntityCheckCache(sessionFactory); JndiInfinispanRegionFactory regionFactory = (JndiInfinispanRegionFactory) sessionFactory.getSettings().getRegionFactory(); Cache cache = regionFactory .getCacheManager() .getCache("org.hibernate.test.cache.infinispan.functional.Item"); assertEquals(ComponentStatus.RUNNING, cache.getStatus()); }
/** Get all second-level cache region names */ @Override public String[] getSecondLevelCacheRegionNames() { if (sessionFactory == null) { return ArrayHelper.toStringArray(secondLevelCacheStatistics.keySet()); } else { return ArrayHelper.toStringArray(sessionFactory.getAllSecondLevelCacheRegions().keySet()); } }
/** Get the names of all entities */ @Override public String[] getEntityNames() { if (sessionFactory == null) { return ArrayHelper.toStringArray(entityStatistics.keySet()); } else { return ArrayHelper.toStringArray(sessionFactory.getAllClassMetadata().keySet()); } }
protected EntityManager createEntityManager(Map properties) { // always reopen a new EM and close the existing one if (em != null && em.isOpen()) { em.close(); } em = entityManagerFactory.createEntityManager(properties); return em; }
/** * Takes a chance to determine the entity persister from the proxy handler contract. * * <p>{@inheritDoc} */ @Override public EntityPersister getSubclassEntityPersister( Object instance, SessionFactoryImplementor factory) { if (instance instanceof IEntity) { return factory.getEntityPersister(((IEntity) instance).getComponentContract().getName()); } return super.getSubclassEntityPersister(instance, factory); }
/** Get the names of all collection roles */ @Override public String[] getCollectionRoleNames() { if (sessionFactory == null) { return ArrayHelper.toStringArray(collectionStatistics.keySet()); } else { return ArrayHelper.toStringArray(sessionFactory.getAllCollectionMetadata().keySet()); } }
@After public void tearDown() throws Exception { if (sessionFactory != null) { sessionFactory.close(); } if (serviceRegistry != null) { ServiceRegistryBuilder.destroy(serviceRegistry); } }
/* 77: */ /* 78: */ protected String generateLockString(int lockTimeout) /* 79: */ { /* 80:122 */ SessionFactoryImplementor factory = getLockable().getFactory(); /* 81:123 */ LockOptions lockOptions = new LockOptions(getLockMode()); /* 82:124 */ lockOptions.setTimeOut(lockTimeout); /* 83:125 */ SimpleSelect select = new SimpleSelect(factory.getDialect()) .setLockOptions(lockOptions) .setTableName(getLockable().getRootTableName()) .addColumn(getLockable().getRootTableIdentifierColumnNames()[0]) .addCondition(getLockable().getRootTableIdentifierColumnNames(), "=?"); /* 84:130 */ if (getLockable().isVersioned()) { /* 85:131 */ select.addCondition(getLockable().getVersionColumnName(), "=?"); /* 86: */ } /* 87:133 */ if (factory.getSettings().isCommentsEnabled()) { /* 88:134 */ select.setComment(getLockMode() + " lock " + getLockable().getEntityName()); /* 89: */ } /* 90:136 */ return select.toStatementString(); /* 91: */ }
protected String generateLockString(int lockTimeout) { SessionFactoryImplementor factory = getLockable().getFactory(); LockOptions lockOptions = new LockOptions(getLockMode()); lockOptions.setTimeOut(lockTimeout); SimpleSelect select = new SimpleSelect(factory.getDialect()) .setLockOptions(lockOptions) .setTableName(getLockable().getRootTableName()) .addColumn(getLockable().getRootTableIdentifierColumnNames()[0]) .addCondition(getLockable().getRootTableIdentifierColumnNames(), "=?"); if (getLockable().isVersioned()) { select.addCondition(getLockable().getVersionColumnName(), "=?"); } if (factory.getSettings().isCommentsEnabled()) { select.setComment(getLockMode() + " lock " + getLockable().getEntityName()); } return select.toStatementString(); }
@Override public Set<EntityKeyMetadata> getAllEntityKeyMetadata() { Set<EntityKeyMetadata> allEntityKeyMetadata = new HashSet<>(); for (EntityPersister entityPersister : factory.getEntityPersisters().values()) { allEntityKeyMetadata.add(((OgmEntityPersister) entityPersister).getEntityKeyMetadata()); } return allEntityKeyMetadata; }
public String getColumnName(int position) throws HibernateException { try { return factory .getDialect() .getColumnAliasExtractor() .extractColumnAlias(resultSetMetaData, position); } catch (SQLException e) { throw new HibernateException("Could not resolve column name [" + position + "]", e); } }
@Override public Reference getReference() throws NamingException { // Expect Hibernate Core to use one StringRefAddr based address String uuid = String.valueOf(delegate.getReference().get(0).getContent()); return new Reference( OgmSessionFactory.class.getName(), new StringRefAddr("uuid", uuid), OgmSessionFactoryObjectFactory.class.getName(), null); }