Example usage for org.hibernate EntityMode POJO

List of usage examples for org.hibernate EntityMode POJO

Introduction

In this page you can find the example usage for org.hibernate EntityMode POJO.

Prototype

EntityMode POJO

To view the source code for org.hibernate EntityMode POJO.

Click Source Link

Document

The pojo entity mode describes an entity model made up of entity classes (loosely) following the java bean convention.

Usage

From source file:corner.service.EntityService.java

License:Apache License

/**
 * ?persist?/*from   w  w w .j  a  v  a 2  s  . co  m*/
 * 
 * @param entity
 *            ?
 * @return ??
 * @since 2.0.3
 */
public boolean isPersistent(final Object entity) {
    if (entity == null) {
        return false;
    }
    return ((Boolean) ((HibernateObjectRelativeUtils) getObjectRelativeUtils()).getHibernateTemplate()
            .execute(new HibernateCallback() {

                public Object doInHibernate(Session session) throws HibernateException, SQLException {
                    final ClassMetadata classMetadata = session.getSessionFactory()
                            .getClassMetadata(getEntityClass(entity));
                    return classMetadata != null
                            && classMetadata.getIdentifier(entity, EntityMode.POJO) != null;

                }
            })).booleanValue();
}

From source file:de.iteratec.hibernate.criterion.IteraplanLikeExpression.java

License:Open Source License

/**{@inheritDoc}**/
@Override//from   ww  w.  j  a va2 s  . c  om
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
    // There is exactly one TypedValue, see super implementation.
    final TypedValue basic = super.getTypedValues(criteria, criteriaQuery)[0];

    // Value of the TypedValue is a String, because it is passed in the super constructor call above.    
    String value = SqlHqlStringUtils.escapeSqlLikeSquareBrackets((String) basic.getValue(),
            criteriaQuery.getFactory().getDialect());

    // EntityMode is always POJO, see super impl. of this method, CriteriaQueryTranslater as the only impl of CriteriaQuery, 
    // and all TypedValue constructions there.
    return new TypedValue[] { new TypedValue(basic.getType(), value, EntityMode.POJO) };
}

From source file:edu.northwestern.bioinformatics.studycalendar.security.csm.internal.DefaultCsmAuthorizationManagerFactory.java

License:BSD License

private SessionFactory createCsmSessionFactory() throws Exception {
    Configuration hibConf = new DefaultCsmHibernateConfiguration();

    // these paths are copied straight from CSM's ApplicationSessionFactory
    String[] mappingPaths = {/* w w w.j  a  va 2 s  . c  o  m*/
            "gov/nih/nci/security/authorization/domainobjects/InstanceLevelMappingElement.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/Privilege.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/Application.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/FilterClause.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/Role.hbm.xml",
            "gov/nih/nci/security/dao/hibernate/RolePrivilege.hbm.xml",
            "gov/nih/nci/security/dao/hibernate/UserGroup.hbm.xml",
            "gov/nih/nci/security/dao/hibernate/ProtectionGroupProtectionElement.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/Group.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/User.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/ProtectionGroup.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/ProtectionElement.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/UserGroupRoleProtectionGroup.hbm.xml",
            "gov/nih/nci/security/authorization/domainobjects/UserProtectionElement.hbm.xml" };
    for (String mappingPath : mappingPaths) {
        hibConf.addResource(mappingPath, AuthorizationManager.class.getClassLoader());
    }

    ClassLoader originalContextCL = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        // this cast is endorsed by the Hibernate 3.6 Core docs as one of the two mechanisms to
        // add an entity name resolver.
        SessionFactoryImpl sessionFactory = (SessionFactoryImpl) hibConf.buildSessionFactory();
        sessionFactory.registerEntityNameResolver(new CglibProxyEntityNameResolver(), EntityMode.POJO);
        return sessionFactory;
    } finally {
        Thread.currentThread().setContextClassLoader(originalContextCL);
    }
}

From source file:edu.utah.further.core.data.util.HibernateUtil.java

License:Apache License

/**
 * @param sessionFactory// w  w  w  .j a  v a 2s  . c  om
 * @return
 */
@SuppressWarnings("unchecked")
public static Set<Class<? extends PersistentEntity<?>>> getEntityClasses(final SessionFactory sessionFactory) {
    final Set<Class<? extends PersistentEntity<?>>> entityClasses = CollectionUtil.newSet();
    for (final Object persister : sessionFactory.getAllClassMetadata().values()) {
        final Class<?> entityClass = ((EntityPersister) persister).getClassMetadata()
                .getMappedClass(EntityMode.POJO);
        // Must perform an unchecked cast because a) Hibernate's API uses raw types
        // and b) Hibernate is not aware of our PersistentEntity<?> at compile-time,
        // although effectively enforces it on all mapped classes at runtime.
        entityClasses.add((Class<? extends PersistentEntity<?>>) entityClass);
    }
    return entityClasses;
}

From source file:es.logongas.ix3.dao.impl.rules.EventListenerImplRuleEngine.java

License:Apache License

private void fireRules(RuleContext ruleContext, EntityPersister entityPersister, Object[] state,
        EntityMode mode, Class<?>... groups) {
    if (ruleContext.getEntity() == null || mode != EntityMode.POJO) {
        return;/* w w w  .j ava  2s.co m*/
    }

    try {
        stateToEntity(state, ruleContext.getEntity(), entityPersister);

        RuleEngine ruleEngine = ruleEngineFactory.getRuleEngine(ruleContext.getEntity().getClass());
        ruleEngine.fireConstraintRules(ruleContext.getEntity(), ruleContext, groups);
        ruleEngine.fireActionRules(ruleContext.getEntity(), ruleContext, groups);

        entityToState(ruleContext.getEntity(), state, entityPersister);

    } catch (BusinessException ex) {
        UnckeckException.throwCkeckedExceptionAsUnckeckedException(ex);
    }
}

From source file:gov.nih.nci.caarray.dao.HibernateIntegrationTestCleanUpUtility.java

License:BSD License

@SuppressWarnings("unchecked")
private static void retrieveClassMetadata() {
    Map<String, ClassMetadata> classMetadataMap = hibernateHelper.getSessionFactory().getAllClassMetadata();

    classesToRemove = new LinkedList<Class<?>>();
    for (ClassMetadata classMetadata : classMetadataMap.values()) {
        classesToRemove.add(classMetadata.getMappedClass(EntityMode.POJO));
    }/*from   w  w  w.  j  av a2s .c om*/
}

From source file:gov.nih.nci.caarray.validation.UniqueConstraintValidator.java

License:BSD License

/**
 * {@inheritDoc}//w  ww.  ja va2  s.c om
 */
@SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.ExcessiveMethodLength" })
public boolean isValid(final Object o) {
    UnfilteredCallback unfilteredCallback = new UnfilteredCallback() {
        public Object doUnfiltered(Session s) {
            FlushMode fm = s.getFlushMode();
            try {
                s.setFlushMode(FlushMode.MANUAL);
                Class<?> classWithConstraint = findClassDeclaringConstraint(
                        hibernateHelper.unwrapProxy(o).getClass());
                Criteria crit = s.createCriteria(classWithConstraint);
                ClassMetadata metadata = hibernateHelper.getSessionFactory()
                        .getClassMetadata(classWithConstraint);
                for (UniqueConstraintField field : uniqueConstraint.fields()) {
                    Object fieldVal = metadata.getPropertyValue(o, field.name(), EntityMode.POJO);
                    if (fieldVal == null) {
                        if (field.nullsEqual()) {
                            // nulls are equal, so add it to to criteria
                            crit.add(Restrictions.isNull(field.name()));
                        } else {
                            // nulls are never equal, so uniqueness is automatically satisfied
                            return true;
                        }
                    } else {
                        // special casing for entity-type properties - only include them in the criteria if they are
                        // already
                        // persistent
                        // otherwise, short-circuit the process and return true immediately since if the
                        // entity-type property
                        // is not persistent then it will be a new value and thus different from any currently in 
                        // the db, thus satisfying uniqueness
                        ClassMetadata fieldMetadata = hibernateHelper.getSessionFactory()
                                .getClassMetadata(hibernateHelper.unwrapProxy(fieldVal).getClass());
                        if (fieldMetadata == null
                                || fieldMetadata.getIdentifier(fieldVal, EntityMode.POJO) != null) {
                            crit.add(Restrictions.eq(field.name(),
                                    ReflectHelper.getGetter(o.getClass(), field.name()).get(o)));
                        } else {
                            return true;
                        }
                    }
                }
                // if object is already persistent, then add condition to exclude it matching itself
                Object id = metadata.getIdentifier(o, EntityMode.POJO);
                if (id != null) {
                    crit.add(Restrictions.ne(metadata.getIdentifierPropertyName(), id));
                }

                int numMatches = crit.list().size();
                return numMatches == 0;
            } finally {
                s.setFlushMode(fm);
            }
        }
    };
    return (Boolean) hibernateHelper.doUnfiltered(unfilteredCallback);

}

From source file:gov.nih.nci.protexpress.test.ProtExpressBaseHibernateTest.java

License:BSD License

/**
 * {@inheritDoc}//  w w w .j  a  v  a 2s . c  o  m
 */
@Override
protected void onSetUp() throws Exception {
    super.onSetUp();
    this.csmInitializer.dropAndCreateCsmDb();
    User u = new User();
    u.setLoginName("~unittestuser~");
    UserHolder.setUser(u);
    LocalSessionFactoryBean theSessionFactoryBean = (LocalSessionFactoryBean) getApplicationContext()
            .getBean("&sessionFactory");
    theSessionFactoryBean.dropDatabaseSchema();
    theSessionFactoryBean.createDatabaseSchema();
    this.theSessionFactory = (SessionFactory) theSessionFactoryBean.getObject();
    this.theSessionFactory.evictQueries();
    for (Object o : this.theSessionFactory.getAllClassMetadata().values()) {
        ClassMetadata cm = (ClassMetadata) o;
        this.theSessionFactory.evict(cm.getMappedClass(EntityMode.POJO));
    }

    this.theSession = this.theSessionFactory.openSession();
    TransactionSynchronizationManager.bindResource(this.theSessionFactory, new SessionHolder(this.theSession));
}

From source file:gr.interamerican.bo2.impl.open.hibernate.HibernateBo2Utils.java

License:Open Source License

/**
 * Checks if the persistence context contains an object.
 * /*  w ww.j a  v  a  2  s. c  o m*/
 * This utility does not use a strictly public hibernate API.
 * 
 * @param object
 *        Object to check for.
 * @param s
 *        Session instance.
 *        
 * @return Returns true, if this object is contained in the persistence context.
 */
@SuppressWarnings("nls")
public static boolean sessionContains(Object object, Session s) {
    Serializable identifier = null;
    String entityName = null;

    if (object instanceof HibernateProxy) {
        HibernateProxy proxy = (HibernateProxy) object;
        identifier = proxy.getHibernateLazyInitializer().getIdentifier();
        entityName = proxy.getHibernateLazyInitializer().getEntityName();
    } else if (object instanceof PersistentObject) {
        PersistentObject<?> po = (PersistentObject<?>) object;
        identifier = po.getKey();
        entityName = Factory.declarationTypeName(object.getClass());
    }

    if (identifier == null) {
        return false;
    }

    SessionImplementor sessionImpl = (SessionImplementor) s;
    EntityPersister entityPersister = sessionImpl.getFactory().getEntityPersister(entityName);
    PersistenceContext persistenceContext = sessionImpl.getPersistenceContext();
    EntityKey entityKey = new EntityKey(identifier, entityPersister, EntityMode.POJO);
    Object entity = persistenceContext.getEntity(entityKey);

    boolean contains = entity != null;
    boolean differentInstances = object != entity;

    if (contains && differentInstances && logger.isDebugEnabled()) {
        logger.warn("Entity with identifier " + identifier
                + " was already associated with the Session as another instance.");
    }

    return contains;
}

From source file:gr.interamerican.bo2.impl.open.hibernate.HibernateBo2Utils.java

License:Open Source License

/**
 * Gets the persistent object with the specified key from the session.
 * // w  ww  . j a v  a 2  s .c  o  m
 * This utility does not use a strictly public hibernate API.
 * 
 * @param identifier 
 *        Id of the object to check for.
 * @param clazz 
 *        Mapped persistent type of the object being checked for.
 * @param s
 *        Session instance.
 *        
 * @return Returns true, if this object is contained in the persistence context.
 */
public static Object getFromSession(Serializable identifier, Class<?> clazz, Session s) {
    String entityName = clazz.getName();

    if (identifier == null) {
        return null;
    }

    SessionImplementor sessionImpl = (SessionImplementor) s;
    EntityPersister entityPersister = sessionImpl.getFactory().getEntityPersister(entityName);
    PersistenceContext persistenceContext = sessionImpl.getPersistenceContext();
    EntityKey entityKey = new EntityKey(identifier, entityPersister, EntityMode.POJO);
    Object entity = persistenceContext.getEntity(entityKey);
    return entity;
}