List of usage examples for org.hibernate.internal CriteriaImpl uniqueResult
@Override public Object uniqueResult() throws HibernateException
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; }/* w w w. j ava2 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 /*w w w . j ava 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.candlepin.model.DetachedCandlepinQuery.java
License:Open Source License
/** * {@inheritDoc}/*from w w w . j a v a2 s . co m*/ */ @Override @SuppressWarnings({ "unchecked", "checkstyle:indentation" }) public int getRowCount() { CriteriaImpl executable = (CriteriaImpl) this.getExecutableCriteria(); // Impl note: // We're using the projection method here over using a cursor to scroll the results due to // limitations on various connectors' cursor implementations. Some don't properly support // fast-forwarding/jumping (Oracle) and others fake the whole thing by running the query // and pretending to scroll (MySQL). Until these are addressed, the hack below is going to // be far more performant and significantly safer (which makes me sad). // Remove any ordering that may be applied (since we almost certainly won't have the field // available anymore) for (Iterator iterator = executable.iterateOrderings(); iterator.hasNext();) { iterator.next(); iterator.remove(); } Projection projection = executable.getProjection(); if (projection != null && projection.isGrouped()) { // We have a projection that alters the grouping of the query. We need to rebuild the // projection such that it gets our row count and properly applies the group by // statement. // The logic for this block is largely derived from this Stack Overflow posting: // http://stackoverflow.com/ // questions/32498229/hibernate-row-count-on-criteria-with-already-set-projection // // A safer alternative may be to generate a query that uses the given criteria as a // subquery (SELECT count(*) FROM (<criteria SQL>)), but is probably less performant // than this hack. CriteriaQueryTranslator translator = new CriteriaQueryTranslator( (SessionFactoryImplementor) this.session.getSessionFactory(), executable, executable.getEntityOrClassName(), CriteriaQueryTranslator.ROOT_SQL_ALIAS); executable.setProjection( Projections.projectionList().add(Projections.rowCount()).add(Projections.sqlGroupProjection( "count(count(1))", translator.getGroupBy(), new String[] {}, new Type[] {}))); } else { executable.setProjection(Projections.rowCount()); } Long count = (Long) executable.uniqueResult(); return count != null ? count.intValue() : 0; }