Example usage for org.hibernate.internal CriteriaImpl CriteriaImpl

List of usage examples for org.hibernate.internal CriteriaImpl CriteriaImpl

Introduction

In this page you can find the example usage for org.hibernate.internal CriteriaImpl CriteriaImpl.

Prototype

public CriteriaImpl(String entityOrClassName, SharedSessionContractImplementor session) 

Source Link

Usage

From source file:com.amalto.core.storage.hibernate.ManyFieldCriterionTest.java

License:Open Source License

public void testToSqlString() {
    RDBMSDataSource dataSource = new RDBMSDataSource("", "MySQL", "", "", "", 0, 0, "", "", null, "create", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$//$NON-NLS-5$//$NON-NLS-6$//$NON-NLS-7$//$NON-NLS-8$
            false, null, "", "", null, //$NON-NLS-1$ //$NON-NLS-2$ 
            "", "", "", false); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    Criteria criteria = new CriteriaImpl(getName(), null);
    TableResolver tableResolver = new TableResolverForTest();
    CriteriaQuery criteriaQuery = new CriteriaQueryForTest();
    FieldMetadata field = new ReferenceFieldMetadata(null, false, false, false, "Song", null, //$NON-NLS-1$
            new SimpleTypeFieldMetadata(null, false, false, false, "Song", //$NON-NLS-1$
                    new SimpleTypeMetadata("", "x_songname"), null, null, null, ""), //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
            null, "", false, false, null, null, //$NON-NLS-1$
            null, null, "", ""); //$NON-NLS-1$ //$NON-NLS-2$
    ManyFieldCriterion cirCriterion = new ManyFieldCriterion(dataSource, criteria, tableResolver, field,
            "Hell Ain't A Bad Place To Be", -1); //$NON-NLS-1$
    assertEquals("(null.null = Hell Ain\\'t A Bad Place To Be)", //$NON-NLS-1$
            cirCriterion.toSqlString(criteria, criteriaQuery));
}

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

License:Open Source License

@SuppressWarnings("unchecked")
public Ref<V> visionallyRead(K key) {

    Arguments.mustNotBeNull("key", key);
    String role = this.getNonNullRole();

    SessionImplementor session = this.getSession();
    if (session == null || !session.isOpen() || !session.isConnected()) {
        return null;
    }//from  w  w  w .  java 2  s. co  m

    SessionFactoryImplementor sessionFactory = session.getFactory();
    QueryableCollection collection = (QueryableCollection) sessionFactory.getCollectionPersister(role);
    EntityPersister elementPersister = collection.getElementPersister();

    String[] indexNames = collection.getIndexColumnNames();
    if (indexNames == null || indexNames[0] == null) {
        indexNames = collection.getIndexFormulas();
    }
    CriteriaImpl criteria = new CriteriaImpl(elementPersister.getEntityName(), session);

    //ownerKey, not ownerId
    Object ownerKey = collection.getCollectionType().getKeyOfOwner(this.getOwner(), session);
    //In Hibernate, isOneToMany means that there is no middle table
    //The @OneToMany of JPA with middle table is consider as many-to-many in Hibernate
    if (sessionFactory.getCollectionPersister(role).isOneToMany()) {
        String[] joinOwnerColumns = collection.getKeyColumnNames();
        StringBuilder sqlBuilder = new StringBuilder();
        for (int i = 0; i < joinOwnerColumns.length; i++) {
            if (i != 0) {
                sqlBuilder.append(" and ");
            }
            sqlBuilder.append("{alias}.").append(joinOwnerColumns[i]).append(" = ?");
        }
        criteria.add(Restrictions.sqlRestriction(sqlBuilder.toString(), ownerKey, collection.getKeyType()));

        sqlBuilder = new StringBuilder();
        for (int i = 0; i < indexNames.length; i++) {
            if (i != 0) {
                sqlBuilder.append(" and ");
            }
            sqlBuilder.append("{alias}.").append(indexNames[i]).append(" = ?");
        }
        criteria.add(Restrictions.sqlRestriction(sqlBuilder.toString(), key, collection.getIndexType()));
    } else {
        String lhsPropertyName = collection.getCollectionType().getLHSPropertyName();
        int lhsPropertyIndex = -1;
        if (lhsPropertyName != null) {
            String[] propertyNames = collection.getOwnerEntityPersister().getPropertyNames();
            for (int i = propertyNames.length - 1; i >= 0; i--) {
                if (propertyNames[i].equals(lhsPropertyName)) {
                    lhsPropertyIndex = i;
                    break;
                }
            }
        }
        String[] lhsColumnNames = JoinHelper.getLHSColumnNames(collection.getCollectionType(), lhsPropertyIndex,
                (OuterJoinLoadable) elementPersister, sessionFactory);
        String[] joinElementColumnNames = collection.getElementColumnNames();
        String[] joinOwnerColumnNames = collection.getKeyColumnNames();

        StringBuilder subQueryBuilder = new StringBuilder();
        subQueryBuilder.append("exists(select * from ").append(collection.getTableName()).append(" as ")
                .append(MIDDLE_TABLE_ALIAS).append(" where ");
        for (int i = 0; i < joinElementColumnNames.length; i++) {
            if (i != 0) {
                subQueryBuilder.append(" and ");
            }
            subQueryBuilder.append("{alias}.").append(lhsColumnNames[i]).append(" = ")
                    .append(MIDDLE_TABLE_ALIAS).append(".").append(joinElementColumnNames[i]);
        }
        for (int i = 0; i < joinOwnerColumnNames.length; i++) {
            subQueryBuilder.append(" and ").append(MIDDLE_TABLE_ALIAS).append('.')
                    .append(joinOwnerColumnNames[i]).append(" = ?");
        }
        for (int i = 0; i < indexNames.length; i++) {
            subQueryBuilder.append(" and ").append(MIDDLE_TABLE_ALIAS).append('.').append(indexNames[i])
                    .append(" = ?");
        }
        subQueryBuilder.append(')');
        criteria.add(Restrictions.sqlRestriction(subQueryBuilder.toString(), new Object[] { ownerKey, key },
                new Type[] { collection.getKeyType(), collection.getIndexType() }));
    }
    FlushMode oldFlushMode = session.getFlushMode();
    session.setFlushMode(FlushMode.MANUAL);
    try {
        return new Ref<V>((V) criteria.uniqueResult());
    } finally {
        session.setFlushMode(oldFlushMode);
    }
}

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

License:Open Source License

/**
 * This method is used to replace /*from  ww  w .  j  av a 2s .  c  om*/
 * "org.hibernate.collection.AbstractPersistentCollection#readElementExistence(Object element)"
 * @param element The example element to be read
 * @return The ref or readed element
 * <ul>
 *  <li>NonNull: Read successfully, check the value of ref to check the read value is null or not</li>
 *  <li>Null: Read failed</li>
 * </ul>
 */
@SuppressWarnings("unchecked")
public Ref<E> visionallyRead(E element) {

    Arguments.mustNotBeNull("element", element);
    String role = this.getNonNullRole();

    SessionImplementor session = this.getSession();
    if (session == null || !session.isOpen() || !session.isConnected()) {
        return null;
    }

    SessionFactoryImplementor sessionFactory = session.getFactory();
    QueryableCollection collection = (QueryableCollection) sessionFactory.getCollectionPersister(role);
    EntityPersister elementPersister = collection.getElementPersister();
    Object elementId = elementPersister.getIdentifier(element, this.getSession());
    if (elementId == null) {
        return new Ref<>();
    }
    if (elementPersister.getEntityMetamodel().getIdentifierProperty().getUnsavedValue()
            .isUnsaved((Serializable) elementId)) {
        return new Ref<>();
    }

    CriteriaImpl criteria = new CriteriaImpl(elementPersister.getEntityName(), session);

    /*
     * Add the condition of element.
     */
    criteria.add(Restrictions.idEq(elementId));

    //ownerKey, not ownerId
    Object ownerKey = collection.getCollectionType().getKeyOfOwner(this.getOwner(), session);
    //In Hibernate, isOneToMany means that there is no middle table
    //The @OneToMany of JPA with middle table is consider as many-to-many in Hibernate
    if (sessionFactory.getCollectionPersister(role).isOneToMany()) {
        String[] joinOwnerColumns = collection.getKeyColumnNames();
        StringBuilder sqlBuilder = new StringBuilder();
        for (int i = 0; i < joinOwnerColumns.length; i++) {
            if (i != 0) {
                sqlBuilder.append(" and ");
            }
            sqlBuilder.append("{alias}.").append(joinOwnerColumns[i]).append(" = ?");
        }
        criteria.add(Restrictions.sqlRestriction(sqlBuilder.toString(), ownerKey, collection.getKeyType()));
    } else {
        String lhsPropertyName = collection.getCollectionType().getLHSPropertyName();
        int lhsPropertyIndex = -1;
        if (lhsPropertyName != null) {
            String[] propertyNames = collection.getOwnerEntityPersister().getPropertyNames();
            for (int i = propertyNames.length - 1; i >= 0; i--) {
                if (propertyNames[i].equals(lhsPropertyName)) {
                    lhsPropertyIndex = i;
                    break;
                }
            }
        }
        String[] lhsColumnNames = JoinHelper.getLHSColumnNames(collection.getCollectionType(), lhsPropertyIndex,
                (OuterJoinLoadable) elementPersister, sessionFactory);
        String[] joinElementColumnNames = collection.getElementColumnNames();
        String[] joinOwnerColumnNames = collection.getKeyColumnNames();
        StringBuilder subQueryBuilder = new StringBuilder();
        subQueryBuilder.append("exists(select * from ").append(collection.getTableName()).append(" as ")
                .append(MIDDLE_TABLE_ALIAS).append(" where ");
        for (int i = 0; i < joinElementColumnNames.length; i++) {
            if (i != 0) {
                subQueryBuilder.append(" and ");
            }
            subQueryBuilder.append("{alias}.").append(lhsColumnNames[i]).append(" = ")
                    .append(MIDDLE_TABLE_ALIAS).append('.').append(joinElementColumnNames[i]);
        }
        for (int i = 0; i < joinOwnerColumnNames.length; i++) {
            subQueryBuilder.append(" and ").append(MIDDLE_TABLE_ALIAS).append(".")
                    .append(joinOwnerColumnNames[i]).append(" = ?");
        }
        subQueryBuilder.append(')');
        criteria.add(
                Restrictions.sqlRestriction(subQueryBuilder.toString(), ownerKey, collection.getKeyType()));
    }
    FlushMode oldFlushMode = session.getFlushMode();
    session.setFlushMode(FlushMode.MANUAL);
    try {
        return new Ref<>((E) criteria.uniqueResult());
    } finally {
        session.setFlushMode(oldFlushMode);
    }
}

From source file:org.babyfish.hibernate.model.loader.HibernateObjectModelScalarLoader.java

License:Open Source License

@SuppressWarnings("unchecked")
private void loadScalarsImpl(Collection<ObjectModel> objectModels, int[] scalarPropertyIds) {
    boolean batch = objectModels.size() > 1;
    ObjectModel firstObjectModel = objectModels.iterator().next();
    JPAObjectModelMetadata jpaObjectModelMetadata = (JPAObjectModelMetadata) firstObjectModel
            .getObjectModelMetadata();//from w ww .  j a va  2s .  c o  m
    JPAScalarProperty entityIdProperty = jpaObjectModelMetadata.getEntityIdProperty();
    Map<Object, ObjectModel> idMap = new LinkedHashMap<>();
    for (ObjectModel objectModel : objectModels) {
        idMap.put(objectModel.getScalar(entityIdProperty.getId()), objectModel);
    }

    CriteriaImpl criteria = new CriteriaImpl(jpaObjectModelMetadata.getOwnerClass().getName(), session);
    ProjectionList projectionList = Projections.projectionList();
    if (batch) {
        String ownerIdPropertyName = entityIdProperty.getOwnerProperty().getName();
        projectionList.add(Projections.property(ownerIdPropertyName));
    }
    for (int scalarPropertyId : scalarPropertyIds) {
        String ownerPropertyName = jpaObjectModelMetadata.getScalarProperty(scalarPropertyId).getOwnerProperty()
                .getName();
        projectionList.add(Projections.property(ownerPropertyName));
    }
    if (batch) {
        criteria.add(Restrictions.in(entityIdProperty.getOwnerProperty().getName(), idMap.keySet()));
    } else {
        criteria.add(Restrictions.eq(entityIdProperty.getOwnerProperty().getName(),
                idMap.keySet().iterator().next()));
    }
    criteria.setProjection(projectionList).setResultTransformer(new ResultTransformer() {

        private static final long serialVersionUID = -1387181124646452221L;

        @Override
        public Object transformTuple(Object[] tuple, String[] aliases) {
            return tuple;
        }

        @SuppressWarnings("rawtypes")
        @Override
        public List transformList(List collection) {
            return collection;
        }
    });
    List<Object[]> tuples;
    FlushMode oldFlushMode = session.getFlushMode();
    session.setFlushMode(FlushMode.MANUAL);
    try {
        tuples = (List<Object[]>) criteria.list();
    } finally {
        session.setFlushMode(oldFlushMode);
    }
    if (batch) {
        for (Object[] tuple : tuples) {
            ObjectModel objectModel = idMap.get(tuple[0]);
            for (int i = scalarPropertyIds.length - 1; i >= 0; i--) {
                objectModel.setScalar(scalarPropertyIds[i], tuple[i + 1]);
            }
        }
    } else {
        Object[] firstTuple = tuples.get(0);
        for (int i = scalarPropertyIds.length - 1; i >= 0; i--) {
            firstObjectModel.setScalar(scalarPropertyIds[i], firstTuple[i]);
        }
    }
}

From source file:pe.com.bbva.pic.dominio.Busqueda.java

License:Open Source License

protected Busqueda(String entityName) {
    criteriaImpl = new CriteriaImpl(entityName, null);
    criteria = criteriaImpl;
}

From source file:pe.com.vical.examplevaadin.util.Busqueda.java

License:Open Source License

protected Busqueda(String entityName) {
    impl = new CriteriaImpl(entityName, null);
    criteria = impl;
}