Example usage for org.hibernate.persister.entity EntityPersister getIdentifierType

List of usage examples for org.hibernate.persister.entity EntityPersister getIdentifierType

Introduction

In this page you can find the example usage for org.hibernate.persister.entity EntityPersister getIdentifierType.

Prototype

Type getIdentifierType();

Source Link

Document

Get the identifier type

Usage

From source file:com.hazelcast.hibernate.region.HazelcastCacheKeysFactory.java

License:Open Source License

@Override
public Object createEntityKey(Object id, EntityPersister persister, SessionFactoryImplementor factory,
        String tenantIdentifier) {
    return new CacheKeyImpl(id, persister.getIdentifierType(), persister.getRootEntityName(), tenantIdentifier,
            factory);/*from  w ww.j  ava  2 s .c  om*/
}

From source file:fr.keyconsulting.oliphant.NotifyListener.java

License:Open Source License

public boolean isKnownToBeStaleInL2(Object object, EventSource session) {
    final EntityPersister persister = sessionFactory.getEntityPersister(session.getEntityName(object));
    String uid = getUid(object, session);
    if (!versions.containsKey(uid)) {
        return false;
    }/*from w ww .j a va 2  s.  c  o  m*/
    if (persister.isVersioned()) {
        if (persister.hasCache() && session.getCacheMode().isGetEnabled()) {
            final EntityRegionAccessStrategy cacheAccessStrategy = persister.getCacheAccessStrategy();
            if (cacheAccessStrategy == null) {
                return false;
            }
            final CacheKey ck = new CacheKey(session.getIdentifier(object), persister.getIdentifierType(),
                    persister.getRootEntityName(), session.getEntityMode(), session.getFactory());
            CacheEntry cachedObject = (CacheEntry) cacheAccessStrategy.get(ck, Long.MAX_VALUE);
            if (cachedObject == null) {
                return false;
            }
            if (Base64.encodeBytes(cachedObject.getDisassembledState()[persister.getVersionProperty()]
                    .toString().getBytes()) != versions.get(uid)) {
                return true;
            }
        }
    }
    return false;
}

From source file:fr.keyconsulting.oliphant.NotifyListener.java

License:Open Source License

public void evictFromL2(Object object, EventSource session) {
    final EntityPersister persister = sessionFactory.getEntityPersister(session.getEntityName(object));
    if (persister.isVersioned()) {
        if (persister.hasCache() && session.getCacheMode().isGetEnabled()) {
            final EntityRegionAccessStrategy cacheAccessStrategy = persister.getCacheAccessStrategy();
            if (cacheAccessStrategy == null) {
                return;
            }//from  ww  w  .  java 2s. c om
            final CacheKey ck = new CacheKey(session.getIdentifier(object), persister.getIdentifierType(),
                    persister.getRootEntityName(), session.getEntityMode(), session.getFactory());
            cacheAccessStrategy.evict(ck);
            Serializable identifier = session.getIdentifier(object);
            LOG.debug("* Object " + identifier + " evicted from L2");
        }
    }
}

From source file:org.babyfish.hibernate.collection.spi.persistence.AbstractBasePersistence.java

License:Open Source License

protected static <E> Collection<E> getOrphans(XCollection<E> oldElements, XCollection<E> currentElements,
        String entityName, SessionImplementor session) throws HibernateException {

    // short-circuit(s)
    if (currentElements.isEmpty()) {
        return oldElements; // no new elements, the old list contains only Orphans
    }//from ww w . j  av a2  s  .  c  om
    if (oldElements.size() == 0) {
        return oldElements; // no old elements, so no Orphans neither
    }

    final EntityPersister entityPersister = session.getFactory().getEntityPersister(entityName);
    final Type idType = entityPersister.getIdentifierType();

    // create the collection holding the Orphans
    Collection<E> res = new ArrayList<E>(oldElements.unifiedComparator());

    // collect EntityIdentifier(s) of the *current* elements - add them into a HashSet for fast access
    Set<Serializable> currentIds = new HashSet<Serializable>();
    Set<E> currentSaving = new HashSet<E>(ReferenceEqualityComparator.getInstance());
    for (E current : currentElements) {
        if (current != null && ForeignKeys.isNotTransient(entityName, current, null, session)) {
            EntityEntry ee = session.getPersistenceContext().getEntry(current);
            if (ee != null && ee.getStatus() == Status.SAVING) {
                currentSaving.add(current);
            } else {
                Serializable currentId = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, current,
                        session);
                currentIds.add(new TypedValue(idType, currentId));
            }
        }
    }

    // iterate over the *old* list
    for (E old : oldElements) {
        if (!currentSaving.contains(old)) {
            Serializable oldId = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, old, session);
            if (!currentIds.contains(new TypedValue(idType, oldId))) {
                res.add(old);
            }
        }
    }

    return res;
}

From source file:org.babyfish.hibernate.persister.UncompletedInitializedProperties.java

License:Open Source License

static void update(EntityPersisterBridge entityPersisterBridge, Object[] state, Object entity, Serializable id,
        Object rowId, SessionImplementor session) {
    FieldInterceptor fieldInterceptor = FieldInterceptionHelper.extractFieldInterceptor(entity);
    if (!(fieldInterceptor instanceof HibernateObjectModelScalarLoader)) {
        return;//  w  ww .j  a va2 s .c o  m
    }
    HibernateObjectModelScalarLoader hibernateObjectModelScalarLoader = (HibernateObjectModelScalarLoader) fieldInterceptor;
    if (!hibernateObjectModelScalarLoader.isIncompletelyInitialized()) {
        return;
    }
    ObjectModel objectModel = hibernateObjectModelScalarLoader.getObjectModel();
    JPAObjectModelMetadata objectModelMetadata = objectModel.getObjectModelMetadata();
    EntityPersister entityPersister = entityPersisterBridge.getEntityPersister();
    String[] names = entityPersister.getPropertyNames();
    Type[] types = entityPersister.getPropertyTypes();
    boolean[] updateabilities = entityPersister.getPropertyUpdateability();

    List<Integer> updatePropertyIndexList = new ArrayList<>();
    for (int propertyIndex = 0; propertyIndex < names.length; propertyIndex++) {
        if (updateabilities[propertyIndex]) {
            Property property = objectModelMetadata.getMappingSources().get(names[propertyIndex]);
            if (property instanceof ScalarProperty) {
                ScalarProperty scalarProperty = (ScalarProperty) property;
                if (scalarProperty.isDeferrable()) {
                    int propertyId = scalarProperty.getId();
                    if (!objectModel.isDisabled(propertyId) && !objectModel.isUnloaded(propertyId)) {
                        updatePropertyIndexList.add(propertyIndex);
                    }
                }
            }
        }
    }
    if (updatePropertyIndexList.isEmpty()) {
        return;
    }
    int[] updatePropertyIndexes = new int[updatePropertyIndexList.size()];
    for (int i = updatePropertyIndexList.size() - 1; i >= 0; i--) {
        updatePropertyIndexes[i] = updatePropertyIndexList.get(i);
    }

    boolean[] tableUpdateNeeded = entityPersisterBridge.getTableUpdateNeeded(updatePropertyIndexes);
    boolean[][] propertyColumnUpdateable = entityPersisterBridge.getPropertyColumnUpdateable();
    for (int tableIndex = 0; tableIndex < entityPersisterBridge.getTableSpan(); tableIndex++) {
        if (tableUpdateNeeded[tableIndex]) {
            StringBuilder builder = new StringBuilder();
            builder.append("update ").append(entityPersisterBridge.getTableName(tableIndex)).append(" set ");
            boolean addComma = false;
            for (int propertyIndex : updatePropertyIndexes) {
                if (entityPersisterBridge.isPropertyOfTable(propertyIndex, tableIndex)) {
                    String[] columnNames = entityPersisterBridge.getPropertyColumnNames(propertyIndex);
                    for (int columnIndex = 0; columnIndex < columnNames.length; columnIndex++) {
                        if (propertyColumnUpdateable[propertyIndex][columnIndex]) {
                            if (addComma) {
                                builder.append(", ");
                            } else {
                                addComma = true;
                            }
                            builder.append(columnNames[columnIndex]).append(" = ?");
                        }
                    }
                }
            }
            if (!addComma) {
                continue;
            }
            builder.append(" where ");
            addComma = false;
            if (tableIndex == 0 && rowId != null) {
                builder.append(entityPersisterBridge.getRowIdName()).append(" = ?");
            } else {
                for (String keyColumn : entityPersisterBridge.getKeyColumns(tableIndex)) {
                    if (addComma) {
                        builder.append(", ");
                    } else {
                        addComma = true;
                    }
                    builder.append(keyColumn).append(" = ?");
                }
            }
            String sql = builder.toString();
            JdbcCoordinator jdbcCoordinator = session.getTransactionCoordinator().getJdbcCoordinator();
            PreparedStatement preparedStatement = jdbcCoordinator.getStatementPreparer().prepareStatement(sql);
            try {
                int paramIndex = 1;
                for (int propertyIndex : updatePropertyIndexes) {
                    if (entityPersisterBridge.isPropertyOfTable(propertyIndex, tableIndex)) {
                        types[propertyIndex].nullSafeSet(preparedStatement, state[propertyIndex], paramIndex,
                                propertyColumnUpdateable[propertyIndex], session);
                        paramIndex += ArrayHelper.countTrue(propertyColumnUpdateable[propertyIndex]);
                    }
                }
                if (tableIndex == 0 && rowId != null) {
                    preparedStatement.setObject(paramIndex, rowId);
                } else {
                    entityPersister.getIdentifierType().nullSafeSet(preparedStatement,
                            id != null ? id
                                    : objectModel.getScalar(objectModelMetadata.getEntityIdProperty().getId()),
                            paramIndex, session);
                }
                preparedStatement.executeUpdate();
            } catch (SQLException ex) {
                throw new HibernateException(ex);
            } finally {
                jdbcCoordinator.release(preparedStatement);
            }
        }
    }
}

From source file:org.infinispan.test.hibernate.cache.CacheKeySerializationTest.java

License:LGPL

private void testId(CacheKeysFactory cacheKeysFactory, String entityName, Object id) throws Exception {
    final SessionFactoryImplementor sessionFactory = getSessionFactory(cacheKeysFactory.getClass().getName());
    final EntityPersister persister = sessionFactory.getEntityPersister(entityName);
    final Object key = cacheKeysFactory.createEntityKey(id, persister, sessionFactory, null);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(key);//from ww w. ja  va  2 s .  c o m

    final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
    final Object keyClone = ois.readObject();

    try {
        assertEquals(key, keyClone);
        assertEquals(keyClone, key);

        assertEquals(key.hashCode(), keyClone.hashCode());

        final Object idClone = cacheKeysFactory.getEntityId(keyClone);

        assertEquals(id.hashCode(), idClone.hashCode());
        assertEquals(id, idClone);
        assertEquals(idClone, id);
        assertTrue(persister.getIdentifierType().isEqual(id, idClone, sessionFactory));
        assertTrue(persister.getIdentifierType().isEqual(idClone, id, sessionFactory));
        sessionFactory.close();
    } finally {
        sessionFactory.close();
    }
}

From source file:org.seasar.hibernate.jpa.metadata.HibernateAttributeDesc.java

License:Apache License

/**
 * <code>value</code>?ID???<code>allValues</code>?????
 * //www. j  a v  a 2 s.  co  m
 * @param allValues
 *            ID??
 * @param type
 *            Hibernate?
 * @param value
 *            ?ID???????ID?
 */
protected void gatherIdAttributeValues(final List<Object> allValues, final Type type, final Object value) {

    if (type.isEntityType()) {
        final EntityType entityType = EntityType.class.cast(type);
        final String name = entityType.getAssociatedEntityName();
        final EntityPersister ep = factory.getEntityPersister(name);
        final Type idType = ep.getIdentifierType();
        final Serializable id = ep.getIdentifier(value, EntityMode.POJO);
        gatherIdAttributeValues(allValues, idType, id);

    } else if (type.isComponentType()) {
        final AbstractComponentType componentType = AbstractComponentType.class.cast(type);
        final Object[] subvalues = componentType.getPropertyValues(value, EntityMode.POJO);
        final Type[] subtypes = componentType.getSubtypes();
        for (int i = 0; i < subtypes.length; i++) {
            gatherIdAttributeValues(allValues, subtypes[i], subvalues[i]);
        }

    } else {
        allValues.add(convert(type, value));
    }
}