HHH-7387 - Integrate Draft 6 of the JPA 2.1 spec : UPDATE/DELETE criterias

This commit is contained in:
Steve Ebersole 2012-06-23 20:41:50 -05:00
parent 2adab60d15
commit 4174c14675
74 changed files with 1597 additions and 722 deletions

View File

@ -723,7 +723,7 @@ castedIdentPrimaryBase
aggregate aggregate
: ( SUM^ | AVG^ | MAX^ | MIN^ ) OPEN! additiveExpression CLOSE! { #aggregate.setType(AGGREGATE); } : ( SUM^ | AVG^ | MAX^ | MIN^ ) OPEN! additiveExpression CLOSE! { #aggregate.setType(AGGREGATE); }
// Special case for count - It's 'parameters' can be keywords. // Special case for count - It's 'parameters' can be keywords.
| COUNT^ OPEN! ( STAR { #STAR.setType(ROW_STAR); } | ( ( DISTINCT | ALL )? ( path | collectionExpr ) ) ) CLOSE! | COUNT^ OPEN! ( STAR { #STAR.setType(ROW_STAR); } | ( ( DISTINCT | ALL )? ( path | collectionExpr | NUM_INT ) ) ) CLOSE!
| collectionExpr | collectionExpr
; ;

View File

@ -23,15 +23,6 @@
*/ */
package org.hibernate.ejb; package org.hibernate.ejb;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.CacheRetrieveMode; import javax.persistence.CacheRetrieveMode;
import javax.persistence.CacheStoreMode; import javax.persistence.CacheStoreMode;
import javax.persistence.EntityExistsException; import javax.persistence.EntityExistsException;
@ -55,13 +46,24 @@ import javax.persistence.Tuple;
import javax.persistence.TupleElement; import javax.persistence.TupleElement;
import javax.persistence.TypedQuery; import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaDelete;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.criteria.Selection; import javax.persistence.criteria.Selection;
import javax.persistence.metamodel.Metamodel; import javax.persistence.metamodel.Metamodel;
import javax.persistence.spi.PersistenceUnitTransactionType; import javax.persistence.spi.PersistenceUnitTransactionType;
import javax.transaction.Status; import javax.transaction.Status;
import javax.transaction.SystemException; import javax.transaction.SystemException;
import javax.transaction.TransactionManager; import javax.transaction.TransactionManager;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
@ -86,8 +88,9 @@ import org.hibernate.cfg.Environment;
import org.hibernate.dialect.lock.LockingStrategyException; import org.hibernate.dialect.lock.LockingStrategyException;
import org.hibernate.dialect.lock.OptimisticEntityLockException; import org.hibernate.dialect.lock.OptimisticEntityLockException;
import org.hibernate.dialect.lock.PessimisticEntityLockException; import org.hibernate.dialect.lock.PessimisticEntityLockException;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ValueHandlerFactory; import org.hibernate.ejb.criteria.ValueHandlerFactory;
import org.hibernate.ejb.criteria.compile.CompilableCriteria;
import org.hibernate.ejb.criteria.compile.CriteriaCompiler;
import org.hibernate.ejb.criteria.expression.CompoundSelectionImpl; import org.hibernate.ejb.criteria.expression.CompoundSelectionImpl;
import org.hibernate.ejb.internal.EntityManagerMessageLogger; import org.hibernate.ejb.internal.EntityManagerMessageLogger;
import org.hibernate.ejb.util.CacheModeHelper; import org.hibernate.ejb.util.CacheModeHelper;
@ -452,7 +455,9 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage
org.hibernate.Query hqlQuery = getSession().createQuery( jpaqlString ); org.hibernate.Query hqlQuery = getSession().createQuery( jpaqlString );
if ( options.getValueHandlers() == null ) { if ( options.getValueHandlers() == null ) {
options.getResultMetadataValidator().validate( hqlQuery.getReturnTypes() ); if ( options.getResultMetadataValidator() != null ) {
options.getResultMetadataValidator().validate( hqlQuery.getReturnTypes() );
}
} }
// determine if we need a result transformer // determine if we need a result transformer
@ -578,13 +583,27 @@ public abstract class AbstractEntityManagerImpl implements HibernateEntityManage
} }
} }
private CriteriaQueryCompiler criteriaQueryCompiler; private CriteriaCompiler criteriaCompiler;
protected CriteriaCompiler criteriaCompiler() {
if ( criteriaCompiler == null ) {
criteriaCompiler = new CriteriaCompiler( this );
}
return criteriaCompiler;
}
public <T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery) { public <T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery) {
if ( criteriaQueryCompiler == null ) { return (TypedQuery<T>) criteriaCompiler().compile( (CompilableCriteria) criteriaQuery );
criteriaQueryCompiler = new CriteriaQueryCompiler( this ); }
}
return criteriaQueryCompiler.compile( criteriaQuery ); @Override
public Query createQuery(CriteriaUpdate criteriaUpdate) {
return criteriaCompiler().compile( (CompilableCriteria) criteriaUpdate );
}
@Override
public Query createQuery(CriteriaDelete criteriaDelete) {
return criteriaCompiler().compile( (CompilableCriteria) criteriaDelete );
} }
public Query createNamedQuery(String name) { public Query createNamedQuery(String name) {

View File

@ -28,8 +28,6 @@ import javax.persistence.PersistenceContextType;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import javax.persistence.Query; import javax.persistence.Query;
import javax.persistence.StoredProcedureQuery; import javax.persistence.StoredProcedureQuery;
import javax.persistence.criteria.CriteriaDelete;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.spi.PersistenceUnitTransactionType; import javax.persistence.spi.PersistenceUnitTransactionType;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
@ -131,16 +129,6 @@ public class EntityManagerImpl extends AbstractEntityManagerImpl implements Sess
return session; return session;
} }
@Override
public Query createQuery(CriteriaUpdate updateQuery) {
throw new NotYetImplementedException();
}
@Override
public Query createQuery(CriteriaDelete deleteQuery) {
throw new NotYetImplementedException();
}
@Override @Override
public StoredProcedureQuery createNamedStoredProcedureQuery(String name) { public StoredProcedureQuery createNamedStoredProcedureQuery(String name) {
throw new NotYetImplementedException(); throw new NotYetImplementedException();

View File

@ -0,0 +1,171 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2012, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ejb.criteria;
import javax.persistence.Query;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
import javax.persistence.metamodel.EntityType;
import java.util.List;
import java.util.Map;
import org.hibernate.cfg.NotYetImplementedException;
import org.hibernate.ejb.HibernateEntityManagerImplementor;
import org.hibernate.ejb.QueryImpl;
import org.hibernate.ejb.criteria.compile.CompilableCriteria;
import org.hibernate.ejb.criteria.compile.CriteriaInterpretation;
import org.hibernate.ejb.criteria.compile.ImplicitParameterBinding;
import org.hibernate.ejb.criteria.compile.InterpretedParameterMetadata;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.path.RootImpl;
/**
* Base class for commonality between {@link javax.persistence.criteria.CriteriaUpdate} and
* {@link javax.persistence.criteria.CriteriaDelete}
*
* @author Steve Ebersole
*/
public abstract class AbstractManipulationCriteriaQuery<T> implements CompilableCriteria {
private final CriteriaBuilderImpl criteriaBuilder;
private RootImpl<T> root;
private Predicate restriction;
private List<Subquery<?>> subQueries;
protected AbstractManipulationCriteriaQuery(CriteriaBuilderImpl criteriaBuilder) {
this.criteriaBuilder = criteriaBuilder;
}
protected CriteriaBuilderImpl criteriaBuilder() {
return criteriaBuilder;
}
// Root ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public Root from(Class<T> entityClass) {
EntityType<T> entityType = criteriaBuilder.getEntityManagerFactory()
.getMetamodel()
.entity( entityClass );
if ( entityType == null ) {
throw new IllegalArgumentException( entityClass + " is not an entity" );
}
return from( entityType );
}
public Root<T> from(EntityType<T> entityType) {
root = new RootImpl<T>( criteriaBuilder, entityType, false );
return root;
}
public Root<T> getRoot() {
return root;
}
// Restriction ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
protected void setRestriction(Expression<Boolean> restriction) {
this.restriction = criteriaBuilder.wrap( restriction );
}
public void setRestriction(Predicate... restrictions) {
this.restriction = criteriaBuilder.and( restrictions );
}
public Predicate getRestriction() {
return restriction;
}
public <U> Subquery<U> subquery(Class<U> type) {
// Need clarification on spec in terms of how the built Subquery.getParent should be handled since getParent
// returns an AbstractQuery whereas neither CriteriaUpdate nor CriteriaDelete extend AbstractQuery
throw new NotYetImplementedException( "Need clarification on spec" );
}
// compiling ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public void validate() {
if ( root == null ) {
throw new IllegalStateException( "UPDATE/DELETE criteria must name root entity" );
}
}
@Override
public CriteriaInterpretation interpret(RenderingContext renderingContext) {
final String jpaqlString = renderQuery( renderingContext );
return new CriteriaInterpretation() {
@Override
@SuppressWarnings("unchecked")
public Query buildCompiledQuery(
HibernateEntityManagerImplementor entityManager,
final InterpretedParameterMetadata interpretedParameterMetadata) {
QueryImpl jpaqlQuery = entityManager.createQuery(
jpaqlString,
null,
null,
new HibernateEntityManagerImplementor.Options() {
@Override
public List<ValueHandlerFactory.ValueHandler> getValueHandlers() {
return null;
}
@Override
public Map<String, Class> getNamedParameterExplicitTypes() {
return interpretedParameterMetadata.implicitParameterTypes();
}
@Override
public ResultMetadataValidator getResultMetadataValidator() {
return null;
}
}
);
for ( ImplicitParameterBinding implicitParameterBinding : interpretedParameterMetadata.implicitParameterBindings() ) {
implicitParameterBinding.bind( jpaqlQuery );
}
return jpaqlQuery;
}
};
}
protected abstract String renderQuery(RenderingContext renderingContext);
protected void renderRoot(StringBuilder jpaql, RenderingContext renderingContext) {
jpaql.append( ( (FromImplementor) root ).renderTableExpression( renderingContext ) );
}
protected void renderRestrictions(StringBuilder jpaql, RenderingContext renderingContext) {
if ( getRestriction() != null) {
jpaql.append( " where " )
.append( ( (Renderable) getRestriction() ).render( renderingContext ) );
}
}
}

View File

@ -137,12 +137,12 @@ public class CriteriaBuilderImpl implements CriteriaBuilder, Serializable {
@Override @Override
public <T> CriteriaUpdate<T> createCriteriaUpdate(Class<T> targetEntity) { public <T> CriteriaUpdate<T> createCriteriaUpdate(Class<T> targetEntity) {
throw new NotYetImplementedException(); return new CriteriaUpdateImpl<T>( this );
} }
@Override @Override
public <T> CriteriaDelete<T> createCriteriaDelete(Class<T> targetEntity) { public <T> CriteriaDelete<T> createCriteriaDelete(Class<T> targetEntity) {
throw new NotYetImplementedException(); return new CriteriaDeleteImpl<T>( this );
} }

View File

@ -0,0 +1,62 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2012, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ejb.criteria;
import javax.persistence.criteria.CriteriaDelete;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/**
* Hibernate implementation of the JPA 2.1 {@link CriteriaDelete} contract.
*
* @author Steve Ebersole
*/
public class CriteriaDeleteImpl<T> extends AbstractManipulationCriteriaQuery<T> implements CriteriaDelete<T> {
protected CriteriaDeleteImpl(CriteriaBuilderImpl criteriaBuilder) {
super( criteriaBuilder );
}
@Override
public CriteriaDelete<T> where(Expression<Boolean> restriction) {
setRestriction( restriction );
return this;
}
@Override
public CriteriaDelete<T> where(Predicate... restrictions) {
setRestriction( restrictions );
return this;
}
@Override
protected String renderQuery(RenderingContext renderingContext) {
final StringBuilder jpaql = new StringBuilder( "delete " );
renderRoot( jpaql, renderingContext );
renderRestrictions( jpaql, renderingContext );
return jpaql.toString();
}
}

View File

@ -1,477 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
* third-party contributors as indicated by either @author tags or express
* copyright attribution statements applied by the authors. All
* third-party contributions are distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ejb.criteria;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.FlushModeType;
import javax.persistence.LockModeType;
import javax.persistence.Parameter;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.ParameterExpression;
import org.jboss.logging.Logger;
import org.hibernate.Query;
import org.hibernate.ejb.HibernateEntityManagerImplementor;
import org.hibernate.ejb.HibernateQuery;
import org.hibernate.ejb.QueryImpl;
import org.hibernate.ejb.internal.EntityManagerMessageLogger;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.type.Type;
/**
* Compiles a JPA criteria query into an executable {@link TypedQuery}. Its single contract is the {@link #compile}
* method.
* <p/>
* NOTE : This is a temporary implementation which simply translates the criteria query into a JPAQL query string. A
* better, long-term solution is being implemented as part of refactoring the JPAQL/HQL translator.
*
* @author Steve Ebersole
*/
public class CriteriaQueryCompiler implements Serializable {
private static final EntityManagerMessageLogger LOG = Logger.getMessageLogger(EntityManagerMessageLogger.class,
CriteriaQueryCompiler.class.getName());
/**
* Used to describe implicit (not defined in criteria query) parameters.
*/
public static interface ImplicitParameterBinding {
/**
* Retrieve the generated name of the implicit parameter.
*
* @return The parameter name.
*/
public String getParameterName();
/**
* Get the java type of the "thing" that led to the implicit parameter. Used from
* {@link org.hibernate.ejb.HibernateEntityManagerImplementor.Options#getNamedParameterExplicitTypes()}
* in determining "guessed type" overriding.
*
* @return The java type
*/
public Class getJavaType();
/**
* Bind the implicit parameter's value to the JPA query.
*
* @param typedQuery The JPA query.
*/
public void bind(TypedQuery typedQuery);
}
/**
* Used to provide a context and services to the rendering.
*/
public static interface RenderingContext {
/**
* Generate a correlation name.
*
* @return The generated correlation name
*/
public String generateAlias();
/**
* Register parameters explicitly encountered in the criteria query.
*
* @param criteriaQueryParameter The parameter expression
*
* @return The JPA-QL parameter name
*/
public String registerExplicitParameter(ParameterExpression<?> criteriaQueryParameter);
/**
* Register a parameter that was not part of the criteria query (at least not as a parameter).
*
* @param literal The literal value
* @param javaType The java type as whcih to handle the literal value.
*
* @return The JPA-QL parameter name
*/
public String registerLiteralParameterBinding(Object literal, Class javaType);
/**
* Given a java type, determine the proper cast type name.
*
* @param javaType The java type.
*
* @return The cast type name.
*/
public String getCastType(Class javaType);
}
public static interface RenderedCriteriaQuery {
public String getQueryString();
public List<ValueHandlerFactory.ValueHandler> getValueHandlers();
public HibernateEntityManagerImplementor.Options.ResultMetadataValidator getResultMetadataValidator();
}
private final HibernateEntityManagerImplementor entityManager;
public CriteriaQueryCompiler(HibernateEntityManagerImplementor entityManager) {
this.entityManager = entityManager;
}
public <T> TypedQuery<T> compile(CriteriaQuery<T> criteriaQuery) {
CriteriaQueryImpl<T> criteriaQueryImpl = ( CriteriaQueryImpl<T> ) criteriaQuery;
criteriaQueryImpl.validate();
final Map<ParameterExpression<?>,String> explicitParameterMapping = new HashMap<ParameterExpression<?>,String>();
final Map<String,ParameterExpression<?>> explicitParameterNameMapping = new HashMap<String,ParameterExpression<?>>();
final List<ImplicitParameterBinding> implicitParameterBindings = new ArrayList<ImplicitParameterBinding>();
final Map<String,Class> implicitParameterTypes = new HashMap<String, Class>();
RenderingContext renderingContext = new RenderingContext() {
private int aliasCount = 0;
private int explicitParameterCount = 0;
public String generateAlias() {
return "generatedAlias" + aliasCount++;
}
public String generateParameterName() {
return "param" + explicitParameterCount++;
}
public String registerExplicitParameter(ParameterExpression<?> criteriaQueryParameter) {
final String jpaqlParameterName;
if ( explicitParameterMapping.containsKey( criteriaQueryParameter ) ) {
jpaqlParameterName = explicitParameterMapping.get( criteriaQueryParameter );
}
else {
jpaqlParameterName = generateParameterName();
explicitParameterMapping.put( criteriaQueryParameter, jpaqlParameterName );
}
if ( StringHelper.isNotEmpty( criteriaQueryParameter.getName() ) ) {
explicitParameterNameMapping.put(
criteriaQueryParameter.getName(),
criteriaQueryParameter
);
}
return jpaqlParameterName;
}
public String registerLiteralParameterBinding(final Object literal, final Class javaType) {
final String parameterName = generateParameterName();
final ImplicitParameterBinding binding = new CriteriaQueryCompiler.ImplicitParameterBinding() {
public String getParameterName() {
return parameterName;
}
public Class getJavaType() {
return javaType;
}
public void bind(TypedQuery typedQuery) {
typedQuery.setParameter( parameterName, literal );
}
};
implicitParameterBindings.add( binding );
implicitParameterTypes.put( parameterName, javaType );
return parameterName;
}
public String getCastType(Class javaType) {
SessionFactoryImplementor factory =
( SessionFactoryImplementor ) entityManager.getFactory().getSessionFactory();
Type hibernateType = factory.getTypeResolver().heuristicType( javaType.getName() );
if ( hibernateType == null ) {
throw new IllegalArgumentException(
"Could not convert java type [" + javaType.getName() + "] to Hibernate type"
);
}
return hibernateType.getName();
}
};
final RenderedCriteriaQuery renderedCriteriaQuery = criteriaQueryImpl.render( renderingContext );
LOG.debugf("Rendered criteria query -> %s", renderedCriteriaQuery.getQueryString());
QueryImpl<T> jpaqlQuery = entityManager.createQuery(
renderedCriteriaQuery.getQueryString(),
criteriaQuery.getResultType(),
criteriaQuery.getSelection(),
new HibernateEntityManagerImplementor.Options() {
public List<ValueHandlerFactory.ValueHandler> getValueHandlers() {
return renderedCriteriaQuery.getValueHandlers();
}
public Map<String, Class> getNamedParameterExplicitTypes() {
return implicitParameterTypes;
}
public ResultMetadataValidator getResultMetadataValidator() {
return renderedCriteriaQuery.getResultMetadataValidator();
}
}
);
for ( ImplicitParameterBinding implicitParameterBinding : implicitParameterBindings ) {
implicitParameterBinding.bind( jpaqlQuery );
}
return new CriteriaQueryTypeQueryAdapter<T>( jpaqlQuery, explicitParameterMapping, explicitParameterNameMapping );
}
public static class CriteriaQueryTypeQueryAdapter<X> implements TypedQuery<X>, HibernateQuery {
private final QueryImpl<X> jpaqlQuery;
private final Map<ParameterExpression<?>, String> explicitParameterMapping;
private final Map<String, ParameterExpression<?>> explicitParameterNameMapping;
public CriteriaQueryTypeQueryAdapter(
QueryImpl<X> jpaqlQuery,
Map<ParameterExpression<?>, String> explicitParameterMapping,
Map<String, ParameterExpression<?>> explicitParameterNameMapping) {
this.jpaqlQuery = jpaqlQuery;
this.explicitParameterMapping = explicitParameterMapping;
this.explicitParameterNameMapping = explicitParameterNameMapping;
}
@Override
public Query getHibernateQuery() {
return jpaqlQuery.getHibernateQuery();
}
public List<X> getResultList() {
return jpaqlQuery.getResultList();
}
public X getSingleResult() {
return jpaqlQuery.getSingleResult();
}
public int getMaxResults() {
return jpaqlQuery.getMaxResults();
}
public TypedQuery<X> setMaxResults(int i) {
jpaqlQuery.setMaxResults( i );
return this;
}
public int getFirstResult() {
return jpaqlQuery.getFirstResult();
}
public TypedQuery<X> setFirstResult(int i) {
jpaqlQuery.setFirstResult( i );
return this;
}
public Map<String, Object> getHints() {
return jpaqlQuery.getHints();
}
public TypedQuery<X> setHint(String name, Object value) {
jpaqlQuery.setHint( name, value);
return this;
}
public FlushModeType getFlushMode() {
return jpaqlQuery.getFlushMode();
}
public TypedQuery<X> setFlushMode(FlushModeType flushModeType) {
jpaqlQuery.setFlushMode( flushModeType );
return this;
}
public LockModeType getLockMode() {
return jpaqlQuery.getLockMode();
}
public TypedQuery<X> setLockMode(LockModeType lockModeType) {
jpaqlQuery.setLockMode( lockModeType );
return this;
}
@SuppressWarnings({ "unchecked" })
public Set getParameters() {
return explicitParameterMapping.keySet();
}
public boolean isBound(Parameter<?> param) {
return jpaqlQuery.isBound( param );
}
@SuppressWarnings({ "unchecked" })
public <T> T getParameterValue(Parameter<T> param) {
return ( T ) jpaqlQuery.getParameterValue( mapToNamedParameter( param ) );
}
@SuppressWarnings({ "unchecked" })
public <T> TypedQuery<X> setParameter(Parameter<T> param, T t) {
jpaqlQuery.setParameter( mapToNamedParameter( param ), t );
return this;
}
@SuppressWarnings({ "RedundantCast" })
private Parameter mapToNamedParameter(Parameter criteriaParameter) {
return jpaqlQuery.getParameter(
explicitParameterMapping.get( criteriaParameter )
);
}
@SuppressWarnings({ "unchecked" })
public TypedQuery<X> setParameter(Parameter<Calendar> param, Calendar calendar, TemporalType temporalType) {
jpaqlQuery.setParameter( mapToNamedParameter( param ), calendar, temporalType );
return this;
}
@SuppressWarnings({ "unchecked" })
public TypedQuery<X> setParameter(Parameter<Date> param, Date date, TemporalType temporalType) {
jpaqlQuery.setParameter( mapToNamedParameter( param ), date, temporalType );
return this;
}
public <T> T unwrap(Class<T> cls) {
return jpaqlQuery.unwrap( cls );
}
@SuppressWarnings({ "unchecked" })
public Object getParameterValue(String name) {
return getParameterValue( resolveExplicitCriteriaParameterName( name ) );
}
private Parameter resolveExplicitCriteriaParameterName(String name) {
Parameter parameter = explicitParameterNameMapping.get( name );
if ( parameter == null ) {
throw new IllegalArgumentException( "Named parameter [" + name + "] not encountered" );
}
return parameter;
}
public Parameter<?> getParameter(String name) {
return mapToNamedParameter( resolveExplicitCriteriaParameterName( name ) );
}
@SuppressWarnings({ "unchecked" })
public <T> Parameter<T> getParameter(String name, Class<T> type) {
Parameter parameter = resolveExplicitCriteriaParameterName( name );
if ( type.isAssignableFrom( parameter.getParameterType() ) ) {
return parameter;
}
throw new IllegalArgumentException(
"Named parameter [" + name + "] type is not assignanle to request type ["
+ type.getName() + "]"
);
}
@SuppressWarnings({ "unchecked" })
public TypedQuery<X> setParameter(String name, Object value) {
setParameter(
resolveExplicitCriteriaParameterName( name, value ),
value
);
return this;
}
private Parameter resolveExplicitCriteriaParameterName(String name, Object value) {
Parameter parameter = resolveExplicitCriteriaParameterName( name );
// todo : is null valid?
if ( value != null ) {
if ( ! parameter.getParameterType().isInstance( value ) ) {
throw new IllegalArgumentException(
"Named parameter [" + name + "] type mismatch; expecting ["
+ parameter.getParameterType().getName() + "], found ["
+ value.getClass().getName() + "]"
);
}
}
return parameter;
}
@SuppressWarnings({ "unchecked" })
public TypedQuery<X> setParameter(String name, Calendar calendar, TemporalType temporalType) {
Parameter parameter = resolveExplicitCriteriaParameterName( name );
if ( ! Calendar.class.isAssignableFrom( parameter.getParameterType() ) ) {
throw new IllegalArgumentException(
"Named parameter [" + name + "] type mismatch; expecting ["
+ Calendar.class.getName() + "], found ["
+ parameter.getParameterType().getName() + "]"
);
}
setParameter( parameter, calendar, temporalType );
return this;
}
@SuppressWarnings({ "unchecked" })
public TypedQuery<X> setParameter(String name, Date date, TemporalType temporalType) {
Parameter parameter = resolveExplicitCriteriaParameterName( name );
if ( ! Date.class.isAssignableFrom( parameter.getParameterType() ) ) {
throw new IllegalArgumentException(
"Named parameter [" + name + "] type mismatch; expecting ["
+ Date.class.getName() + "], found ["
+ parameter.getParameterType().getName() + "]"
);
}
setParameter( parameter, date, temporalType );
return this;
}
// unsupported stuff ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public int executeUpdate() {
throw new IllegalArgumentException( "Criteria queries do not support update queries" );
}
public TypedQuery<X> setParameter(int i, Object o) {
throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" );
}
public TypedQuery<X> setParameter(int i, Calendar calendar, TemporalType temporalType) {
throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" );
}
public TypedQuery<X> setParameter(int i, Date date, TemporalType temporalType) {
throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" );
}
public Object getParameterValue(int position) {
throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" );
}
public Parameter<?> getParameter(int position) {
throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" );
}
public <T> Parameter<T> getParameter(int position, Class<T> type) {
throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" );
}
}
}

View File

@ -27,7 +27,9 @@ import java.io.Serializable;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.persistence.Query;
import javax.persistence.Tuple; import javax.persistence.Tuple;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
@ -39,7 +41,16 @@ import javax.persistence.criteria.Selection;
import javax.persistence.criteria.Subquery; import javax.persistence.criteria.Subquery;
import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.EntityType;
import org.jboss.logging.Logger;
import org.hibernate.ejb.HibernateEntityManagerImplementor; import org.hibernate.ejb.HibernateEntityManagerImplementor;
import org.hibernate.ejb.QueryImpl;
import org.hibernate.ejb.criteria.compile.CompilableCriteria;
import org.hibernate.ejb.criteria.compile.CriteriaInterpretation;
import org.hibernate.ejb.criteria.compile.CriteriaQueryTypeQueryAdapter;
import org.hibernate.ejb.criteria.compile.ImplicitParameterBinding;
import org.hibernate.ejb.criteria.compile.InterpretedParameterMetadata;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.type.Type; import org.hibernate.type.Type;
/** /**
@ -48,7 +59,9 @@ import org.hibernate.type.Type;
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class CriteriaQueryImpl<T> extends AbstractNode implements CriteriaQuery<T>, Serializable { public class CriteriaQueryImpl<T> extends AbstractNode implements CriteriaQuery<T>, CompilableCriteria, Serializable {
private static final Logger log = Logger.getLogger( CriteriaQueryImpl.class );
private final Class<T> returnType; private final Class<T> returnType;
private final QueryStructure<T> queryStructure; private final QueryStructure<T> queryStructure;
@ -334,60 +347,89 @@ public class CriteriaQueryImpl<T> extends AbstractNode implements CriteriaQuery<
return true; return true;
} }
public CriteriaQueryCompiler.RenderedCriteriaQuery render(CriteriaQueryCompiler.RenderingContext renderingContext) { @Override
final StringBuilder jpaqlQuery = new StringBuilder(); public CriteriaInterpretation interpret(RenderingContext renderingContext) {
final StringBuilder jpaqlBuffer = new StringBuilder();
queryStructure.render( jpaqlQuery, renderingContext ); queryStructure.render( jpaqlBuffer, renderingContext );
if ( ! getOrderList().isEmpty() ) { if ( ! getOrderList().isEmpty() ) {
jpaqlQuery.append( " order by " ); jpaqlBuffer.append( " order by " );
String sep = ""; String sep = "";
for ( Order orderSpec : getOrderList() ) { for ( Order orderSpec : getOrderList() ) {
jpaqlQuery.append( sep ) jpaqlBuffer.append( sep )
.append( ( ( Renderable ) orderSpec.getExpression() ).render( renderingContext ) ) .append( ( ( Renderable ) orderSpec.getExpression() ).render( renderingContext ) )
.append( orderSpec.isAscending() ? " asc" : " desc" ); .append( orderSpec.isAscending() ? " asc" : " desc" );
sep = ", "; sep = ", ";
} }
} }
return new CriteriaQueryCompiler.RenderedCriteriaQuery() { final String jpaqlString = jpaqlBuffer.toString();
public String getQueryString() {
return jpaqlQuery.toString();
}
@SuppressWarnings({ "unchecked" }) log.debugf( "Rendered criteria query -> %s", jpaqlString );
public List<ValueHandlerFactory.ValueHandler> getValueHandlers() {
SelectionImplementor selection = (SelectionImplementor) queryStructure.getSelection();
return selection == null
? null
: selection.getValueHandlers();
}
public HibernateEntityManagerImplementor.Options.ResultMetadataValidator getResultMetadataValidator() { return new CriteriaInterpretation() {
return new HibernateEntityManagerImplementor.Options.ResultMetadataValidator() { @Override
public void validate(Type[] returnTypes) { @SuppressWarnings("unchecked")
SelectionImplementor selection = (SelectionImplementor) queryStructure.getSelection(); public Query buildCompiledQuery(HibernateEntityManagerImplementor entityManager, final InterpretedParameterMetadata parameterMetadata) {
if ( selection != null ) {
if ( selection.isCompoundSelection() ) { QueryImpl jpaqlQuery = entityManager.createQuery(
if ( returnTypes.length != selection.getCompoundSelectionItems().size() ) { jpaqlString,
throw new IllegalStateException( getResultType(),
"Number of return values [" + returnTypes.length + getSelection(),
"] did not match expected [" + new HibernateEntityManagerImplementor.Options() {
selection.getCompoundSelectionItems().size() + "]" @Override
); public List<ValueHandlerFactory.ValueHandler> getValueHandlers() {
} SelectionImplementor selection = (SelectionImplementor) queryStructure.getSelection();
return selection == null
? null
: selection.getValueHandlers();
} }
else {
if ( returnTypes.length > 1 ) { @Override
throw new IllegalStateException( public Map<String, Class> getNamedParameterExplicitTypes() {
"Number of return values [" + returnTypes.length + return parameterMetadata.implicitParameterTypes();
"] did not match expected [1]"
);
}
} }
@Override
public ResultMetadataValidator getResultMetadataValidator() {
return new HibernateEntityManagerImplementor.Options.ResultMetadataValidator() {
@Override
public void validate(Type[] returnTypes) {
SelectionImplementor selection = (SelectionImplementor) queryStructure.getSelection();
if ( selection != null ) {
if ( selection.isCompoundSelection() ) {
if ( returnTypes.length != selection.getCompoundSelectionItems().size() ) {
throw new IllegalStateException(
"Number of return values [" + returnTypes.length +
"] did not match expected [" +
selection.getCompoundSelectionItems().size() + "]"
);
}
}
else {
if ( returnTypes.length > 1 ) {
throw new IllegalStateException(
"Number of return values [" + returnTypes.length +
"] did not match expected [1]"
);
}
}
}
}
}; }
} }
} );
};
for ( ImplicitParameterBinding implicitParameterBinding : parameterMetadata.implicitParameterBindings() ) {
implicitParameterBinding.bind( jpaqlQuery );
}
return new CriteriaQueryTypeQueryAdapter(
jpaqlQuery,
parameterMetadata.explicitParameterMapping(),
parameterMetadata.explicitParameterNameMapping()
);
} }
}; };
} }

View File

@ -39,6 +39,7 @@ import javax.persistence.criteria.SetJoin;
import javax.persistence.criteria.Subquery; import javax.persistence.criteria.Subquery;
import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.EntityType;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.ExpressionImpl; import org.hibernate.ejb.criteria.expression.ExpressionImpl;
import org.hibernate.ejb.criteria.path.RootImpl; import org.hibernate.ejb.criteria.path.RootImpl;
@ -277,14 +278,14 @@ public class CriteriaSubqueryImpl<T> extends ExpressionImpl<T> implements Subque
return queryStructure.subquery( subqueryType ); return queryStructure.subquery( subqueryType );
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
StringBuilder subqueryBuffer = new StringBuilder( "(" ); StringBuilder subqueryBuffer = new StringBuilder( "(" );
queryStructure.render( subqueryBuffer, renderingContext ); queryStructure.render( subqueryBuffer, renderingContext );
subqueryBuffer.append( ')' ); subqueryBuffer.append( ')' );
return subqueryBuffer.toString(); return subqueryBuffer.toString();
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
throw new IllegalStateException( "Subquery cannot occur in select clause" ); throw new IllegalStateException( "Subquery cannot occur in select clause" );
} }
} }

View File

@ -0,0 +1,147 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2012, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ejb.criteria;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SingularAttribute;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.path.SingularAttributePath;
/**
* Hibernate implementation of the JPA 2.1 {@link CriteriaUpdate} contract.
*
* @author Steve Ebersole
*/
public class CriteriaUpdateImpl<T> extends AbstractManipulationCriteriaQuery<T> implements CriteriaUpdate<T> {
private List<Assignment> assignments = new ArrayList<Assignment>();
public CriteriaUpdateImpl(CriteriaBuilderImpl criteriaBuilder) {
super( criteriaBuilder );
}
@Override
public <Y, X extends Y> CriteriaUpdate<T> set(SingularAttribute<? super T, Y> singularAttribute, X value) {
addAssignment( getRoot().get( singularAttribute ), criteriaBuilder().literal( value ) );
return this;
}
@Override
public <Y> CriteriaUpdate<T> set(
SingularAttribute<? super T, Y> singularAttribute,
Expression<? extends Y> value) {
addAssignment( getRoot().get( singularAttribute ), value );
return this;
}
@Override
public <Y, X extends Y> CriteriaUpdate<T> set(Path<Y> attributePath, X value) {
addAssignment( attributePath, criteriaBuilder().literal( value ) );
return this;
}
@Override
public <Y> CriteriaUpdate<T> set(Path<Y> attributePath, Expression<? extends Y> value) {
addAssignment( attributePath, value );
return this;
}
@Override
public CriteriaUpdate<T> set(String attributeName, Object value) {
addAssignment( getRoot().get( attributeName ), criteriaBuilder().literal( value ) );
return this;
}
protected <Y> void addAssignment(Path<Y> attributePath, Expression<? extends Y> value) {
if ( ! PathImplementor.class.isInstance( attributePath ) ) {
throw new IllegalArgumentException( "Unexpected path implementation type : " + attributePath.getClass().getName() );
}
if ( ! SingularAttributePath.class.isInstance( attributePath ) ) {
throw new IllegalArgumentException(
"Attribute path for assignment must represent a singular attribute ["
+ ( (PathImplementor) attributePath ).getPathIdentifier() + "]"
);
}
assignments.add( new Assignment<Y>( (SingularAttributePath<Y>) attributePath, value ) );
}
@Override
public CriteriaUpdate<T> where(Expression<Boolean> restriction) {
setRestriction( restriction );
return this;
}
@Override
public CriteriaUpdate<T> where(Predicate... restrictions) {
setRestriction( restrictions );
return this;
}
@Override
public void validate() {
super.validate();
if ( assignments.isEmpty() ) {
throw new IllegalStateException( "No assignments specified as part of UPDATE criteria" );
}
}
@Override
protected String renderQuery(RenderingContext renderingContext) {
final StringBuilder jpaql = new StringBuilder( "update " );
renderRoot( jpaql, renderingContext );
renderAssignments( jpaql, renderingContext );
renderRestrictions( jpaql, renderingContext );
return jpaql.toString();
}
private void renderAssignments(StringBuilder jpaql, RenderingContext renderingContext) {
jpaql.append( " set " );
boolean first = true;
for ( Assignment assignment : assignments ) {
jpaql.append( assignment.attributePath.render( renderingContext ) )
.append( " = " )
.append( assignment.value.render( renderingContext ) );
if ( ! first ) {
jpaql.append( ", " );
}
first = false;
}
}
private class Assignment<A> {
private final SingularAttributePath<A> attributePath;
private final ExpressionImplementor<? extends A> value;
private Assignment(SingularAttributePath<A> attributePath, Expression<? extends A> value) {
this.attributePath = attributePath;
this.value = (ExpressionImplementor) value;
}
}
}

View File

@ -24,14 +24,16 @@
package org.hibernate.ejb.criteria; package org.hibernate.ejb.criteria;
import javax.persistence.criteria.From; import javax.persistence.criteria.From;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Implementation contract for the JPA {@link From} interface. * Implementation contract for the JPA {@link From} interface.
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public interface FromImplementor<Z,X> extends PathImplementor<X>, From<Z,X> { public interface FromImplementor<Z,X> extends PathImplementor<X>, From<Z,X> {
public void prepareAlias(CriteriaQueryCompiler.RenderingContext renderingContext); public void prepareAlias(RenderingContext renderingContext);
public String renderTableExpression(CriteriaQueryCompiler.RenderingContext renderingContext); public String renderTableExpression(RenderingContext renderingContext);
public FromImplementor<Z,X> correlateTo(CriteriaSubqueryImpl subquery); public FromImplementor<Z,X> correlateTo(CriteriaSubqueryImpl subquery);

View File

@ -24,13 +24,15 @@
package org.hibernate.ejb.criteria; package org.hibernate.ejb.criteria;
import javax.persistence.criteria.Path; import javax.persistence.criteria.Path;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Implementation contract for things which can be the source (parent, left-hand-side, etc) of a path * Implementation contract for things which can be the source (parent, left-hand-side, etc) of a path
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public interface PathSource<X> extends Path<X> { public interface PathSource<X> extends Path<X> {
public void prepareAlias(CriteriaQueryCompiler.RenderingContext renderingContext); public void prepareAlias(RenderingContext renderingContext);
/** /**
* Get the string representation of this path as a navigation from one of the * Get the string representation of this path as a navigation from one of the

View File

@ -44,6 +44,7 @@ import javax.persistence.criteria.Selection;
import javax.persistence.criteria.Subquery; import javax.persistence.criteria.Subquery;
import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.EntityType;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.path.RootImpl; import org.hibernate.ejb.criteria.path.RootImpl;
/** /**
@ -240,7 +241,7 @@ public class QueryStructure<T> implements Serializable {
} }
@SuppressWarnings({ "unchecked" }) @SuppressWarnings({ "unchecked" })
public void render(StringBuilder jpaqlQuery, CriteriaQueryCompiler.RenderingContext renderingContext) { public void render(StringBuilder jpaqlQuery, RenderingContext renderingContext) {
jpaqlQuery.append( "select " ); jpaqlQuery.append( "select " );
if ( isDistinct() ) { if ( isDistinct() ) {
jpaqlQuery.append( "distinct " ); jpaqlQuery.append( "distinct " );
@ -300,7 +301,7 @@ public class QueryStructure<T> implements Serializable {
} }
@SuppressWarnings({ "unchecked" }) @SuppressWarnings({ "unchecked" })
private void renderFromClause(StringBuilder jpaqlQuery, CriteriaQueryCompiler.RenderingContext renderingContext) { private void renderFromClause(StringBuilder jpaqlQuery, RenderingContext renderingContext) {
jpaqlQuery.append( " from " ); jpaqlQuery.append( " from " );
String sep = ""; String sep = "";
for ( Root root : getRoots() ) { for ( Root root : getRoots() ) {
@ -342,7 +343,7 @@ public class QueryStructure<T> implements Serializable {
@SuppressWarnings({ "unchecked" }) @SuppressWarnings({ "unchecked" })
private void renderJoins( private void renderJoins(
StringBuilder jpaqlQuery, StringBuilder jpaqlQuery,
CriteriaQueryCompiler.RenderingContext renderingContext, RenderingContext renderingContext,
Collection<Join<?,?>> joins) { Collection<Join<?,?>> joins) {
if ( joins == null ) { if ( joins == null ) {
return; return;
@ -375,7 +376,7 @@ public class QueryStructure<T> implements Serializable {
@SuppressWarnings({ "unchecked" }) @SuppressWarnings({ "unchecked" })
private void renderFetches( private void renderFetches(
StringBuilder jpaqlQuery, StringBuilder jpaqlQuery,
CriteriaQueryCompiler.RenderingContext renderingContext, RenderingContext renderingContext,
Collection<Fetch> fetches) { Collection<Fetch> fetches) {
if ( fetches == null ) { if ( fetches == null ) {
return; return;

View File

@ -24,12 +24,14 @@
package org.hibernate.ejb.criteria; package org.hibernate.ejb.criteria;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* TODO : javadoc * TODO : javadoc
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public interface Renderable { public interface Renderable {
public String render(CriteriaQueryCompiler.RenderingContext renderingContext); public String render(RenderingContext renderingContext);
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext); public String renderProjection(RenderingContext renderingContext);
} }

View File

@ -0,0 +1,34 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2012, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ejb.criteria.compile;
/**
* @author Steve Ebersole
*/
public interface CompilableCriteria {
public void validate();
public CriteriaInterpretation interpret(RenderingContext renderingContext);
}

View File

@ -0,0 +1,154 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
* third-party contributors as indicated by either @author tags or express
* copyright attribution statements applied by the authors. All
* third-party contributions are distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ejb.criteria.compile;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.ParameterExpression;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.ejb.HibernateEntityManagerImplementor;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.type.Type;
/**
* Compiles a JPA criteria query into an executable {@link TypedQuery}. Its single contract is the {@link #compile}
* method.
* <p/>
* NOTE : This is a temporary implementation which simply translates the criteria query into a JPAQL query string. A
* better, long-term solution is being implemented as part of refactoring the JPAQL/HQL translator.
*
* @author Steve Ebersole
*/
public class CriteriaCompiler implements Serializable {
private final HibernateEntityManagerImplementor entityManager;
public CriteriaCompiler(HibernateEntityManagerImplementor entityManager) {
this.entityManager = entityManager;
}
public Query compile(CompilableCriteria criteria) {
criteria.validate();
final Map<ParameterExpression<?>,String> explicitParameterMapping = new HashMap<ParameterExpression<?>,String>();
final Map<String,ParameterExpression<?>> explicitParameterNameMapping = new HashMap<String,ParameterExpression<?>>();
final List<ImplicitParameterBinding> implicitParameterBindings = new ArrayList<ImplicitParameterBinding>();
final Map<String,Class> implicitParameterTypes = new HashMap<String, Class>();
RenderingContext renderingContext = new RenderingContext() {
private int aliasCount = 0;
private int explicitParameterCount = 0;
public String generateAlias() {
return "generatedAlias" + aliasCount++;
}
public String generateParameterName() {
return "param" + explicitParameterCount++;
}
public String registerExplicitParameter(ParameterExpression<?> criteriaQueryParameter) {
final String jpaqlParameterName;
if ( explicitParameterMapping.containsKey( criteriaQueryParameter ) ) {
jpaqlParameterName = explicitParameterMapping.get( criteriaQueryParameter );
}
else {
jpaqlParameterName = generateParameterName();
explicitParameterMapping.put( criteriaQueryParameter, jpaqlParameterName );
}
if ( StringHelper.isNotEmpty( criteriaQueryParameter.getName() ) ) {
explicitParameterNameMapping.put(
criteriaQueryParameter.getName(),
criteriaQueryParameter
);
}
return jpaqlParameterName;
}
public String registerLiteralParameterBinding(final Object literal, final Class javaType) {
final String parameterName = generateParameterName();
final ImplicitParameterBinding binding = new ImplicitParameterBinding() {
public String getParameterName() {
return parameterName;
}
public Class getJavaType() {
return javaType;
}
public void bind(TypedQuery typedQuery) {
typedQuery.setParameter( parameterName, literal );
}
};
implicitParameterBindings.add( binding );
implicitParameterTypes.put( parameterName, javaType );
return parameterName;
}
public String getCastType(Class javaType) {
SessionFactoryImplementor factory =
( SessionFactoryImplementor ) entityManager.getFactory().getSessionFactory();
Type hibernateType = factory.getTypeResolver().heuristicType( javaType.getName() );
if ( hibernateType == null ) {
throw new IllegalArgumentException(
"Could not convert java type [" + javaType.getName() + "] to Hibernate type"
);
}
return hibernateType.getName();
}
};
return criteria.interpret( renderingContext ).buildCompiledQuery(
entityManager,
new InterpretedParameterMetadata() {
@Override
public Map<ParameterExpression<?>, String> explicitParameterMapping() {
return explicitParameterMapping;
}
@Override
public Map<String, ParameterExpression<?>> explicitParameterNameMapping() {
return explicitParameterNameMapping;
}
@Override
public List<ImplicitParameterBinding> implicitParameterBindings() {
return implicitParameterBindings;
}
@Override
public Map<String, Class> implicitParameterTypes() {
return implicitParameterTypes;
}
}
);
}
}

View File

@ -0,0 +1,47 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2012, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ejb.criteria.compile;
import javax.persistence.Query;
import org.hibernate.ejb.HibernateEntityManagerImplementor;
/**
* The interpretation of a JPA criteria object.
*
* @author Steve Ebersole
*/
public interface CriteriaInterpretation {
/**
* Generate a {@link javax.persistence.Query} instance given the interpreted criteria compiled against the
* passed EntityManager.
*
*
* @param entityManager The EntityManager against which to create the Query instance.
* @param interpretedParameterMetadata parameter metadata
*
* @return The created Query instance.
*/
public Query buildCompiledQuery(HibernateEntityManagerImplementor entityManager, InterpretedParameterMetadata interpretedParameterMetadata);
}

View File

@ -0,0 +1,271 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2012, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ejb.criteria.compile;
import javax.persistence.FlushModeType;
import javax.persistence.LockModeType;
import javax.persistence.Parameter;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.ParameterExpression;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.Query;
import org.hibernate.ejb.HibernateQuery;
import org.hibernate.ejb.QueryImpl;
/**
* @author Steve Ebersole
*/
public class CriteriaQueryTypeQueryAdapter<X> implements TypedQuery<X>, HibernateQuery {
private final QueryImpl<X> jpaqlQuery;
private final Map<ParameterExpression<?>, String> explicitParameterMapping;
private final Map<String, ParameterExpression<?>> explicitParameterNameMapping;
public CriteriaQueryTypeQueryAdapter(
QueryImpl<X> jpaqlQuery,
Map<ParameterExpression<?>, String> explicitParameterMapping,
Map<String, ParameterExpression<?>> explicitParameterNameMapping) {
this.jpaqlQuery = jpaqlQuery;
this.explicitParameterMapping = explicitParameterMapping;
this.explicitParameterNameMapping = explicitParameterNameMapping;
}
@Override
public Query getHibernateQuery() {
return jpaqlQuery.getHibernateQuery();
}
public List<X> getResultList() {
return jpaqlQuery.getResultList();
}
public X getSingleResult() {
return jpaqlQuery.getSingleResult();
}
public int getMaxResults() {
return jpaqlQuery.getMaxResults();
}
public TypedQuery<X> setMaxResults(int i) {
jpaqlQuery.setMaxResults( i );
return this;
}
public int getFirstResult() {
return jpaqlQuery.getFirstResult();
}
public TypedQuery<X> setFirstResult(int i) {
jpaqlQuery.setFirstResult( i );
return this;
}
public Map<String, Object> getHints() {
return jpaqlQuery.getHints();
}
public TypedQuery<X> setHint(String name, Object value) {
jpaqlQuery.setHint( name, value);
return this;
}
public FlushModeType getFlushMode() {
return jpaqlQuery.getFlushMode();
}
public TypedQuery<X> setFlushMode(FlushModeType flushModeType) {
jpaqlQuery.setFlushMode( flushModeType );
return this;
}
public LockModeType getLockMode() {
return jpaqlQuery.getLockMode();
}
public TypedQuery<X> setLockMode(LockModeType lockModeType) {
jpaqlQuery.setLockMode( lockModeType );
return this;
}
@SuppressWarnings({ "unchecked" })
public Set getParameters() {
return explicitParameterMapping.keySet();
}
public boolean isBound(Parameter<?> param) {
return jpaqlQuery.isBound( param );
}
@SuppressWarnings({ "unchecked" })
public <T> T getParameterValue(Parameter<T> param) {
return ( T ) jpaqlQuery.getParameterValue( mapToNamedParameter( param ) );
}
@SuppressWarnings({ "unchecked" })
public <T> TypedQuery<X> setParameter(Parameter<T> param, T t) {
jpaqlQuery.setParameter( mapToNamedParameter( param ), t );
return this;
}
@SuppressWarnings({ "RedundantCast" })
private Parameter mapToNamedParameter(Parameter criteriaParameter) {
return jpaqlQuery.getParameter(
explicitParameterMapping.get( criteriaParameter )
);
}
@SuppressWarnings({ "unchecked" })
public TypedQuery<X> setParameter(Parameter<Calendar> param, Calendar calendar, TemporalType temporalType) {
jpaqlQuery.setParameter( mapToNamedParameter( param ), calendar, temporalType );
return this;
}
@SuppressWarnings({ "unchecked" })
public TypedQuery<X> setParameter(Parameter<Date> param, Date date, TemporalType temporalType) {
jpaqlQuery.setParameter( mapToNamedParameter( param ), date, temporalType );
return this;
}
public <T> T unwrap(Class<T> cls) {
return jpaqlQuery.unwrap( cls );
}
@SuppressWarnings({ "unchecked" })
public Object getParameterValue(String name) {
return getParameterValue( resolveExplicitCriteriaParameterName( name ) );
}
private Parameter resolveExplicitCriteriaParameterName(String name) {
Parameter parameter = explicitParameterNameMapping.get( name );
if ( parameter == null ) {
throw new IllegalArgumentException( "Named parameter [" + name + "] not encountered" );
}
return parameter;
}
public Parameter<?> getParameter(String name) {
return mapToNamedParameter( resolveExplicitCriteriaParameterName( name ) );
}
@SuppressWarnings({ "unchecked" })
public <T> Parameter<T> getParameter(String name, Class<T> type) {
Parameter parameter = resolveExplicitCriteriaParameterName( name );
if ( type.isAssignableFrom( parameter.getParameterType() ) ) {
return parameter;
}
throw new IllegalArgumentException(
"Named parameter [" + name + "] type is not assignanle to request type ["
+ type.getName() + "]"
);
}
@SuppressWarnings({ "unchecked" })
public TypedQuery<X> setParameter(String name, Object value) {
setParameter(
resolveExplicitCriteriaParameterName( name, value ),
value
);
return this;
}
private Parameter resolveExplicitCriteriaParameterName(String name, Object value) {
Parameter parameter = resolveExplicitCriteriaParameterName( name );
// todo : is null valid?
if ( value != null ) {
if ( ! parameter.getParameterType().isInstance( value ) ) {
throw new IllegalArgumentException(
"Named parameter [" + name + "] type mismatch; expecting ["
+ parameter.getParameterType().getName() + "], found ["
+ value.getClass().getName() + "]"
);
}
}
return parameter;
}
@SuppressWarnings({ "unchecked" })
public TypedQuery<X> setParameter(String name, Calendar calendar, TemporalType temporalType) {
Parameter parameter = resolveExplicitCriteriaParameterName( name );
if ( ! Calendar.class.isAssignableFrom( parameter.getParameterType() ) ) {
throw new IllegalArgumentException(
"Named parameter [" + name + "] type mismatch; expecting ["
+ Calendar.class.getName() + "], found ["
+ parameter.getParameterType().getName() + "]"
);
}
setParameter( parameter, calendar, temporalType );
return this;
}
@SuppressWarnings({ "unchecked" })
public TypedQuery<X> setParameter(String name, Date date, TemporalType temporalType) {
Parameter parameter = resolveExplicitCriteriaParameterName( name );
if ( ! Date.class.isAssignableFrom( parameter.getParameterType() ) ) {
throw new IllegalArgumentException(
"Named parameter [" + name + "] type mismatch; expecting ["
+ Date.class.getName() + "], found ["
+ parameter.getParameterType().getName() + "]"
);
}
setParameter( parameter, date, temporalType );
return this;
}
// unsupported stuff ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public int executeUpdate() {
throw new IllegalArgumentException( "Criteria queries do not support update queries" );
}
public TypedQuery<X> setParameter(int i, Object o) {
throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" );
}
public TypedQuery<X> setParameter(int i, Calendar calendar, TemporalType temporalType) {
throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" );
}
public TypedQuery<X> setParameter(int i, Date date, TemporalType temporalType) {
throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" );
}
public Object getParameterValue(int position) {
throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" );
}
public Parameter<?> getParameter(int position) {
throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" );
}
public <T> Parameter<T> getParameter(int position, Class<T> type) {
throw new IllegalArgumentException( "Criteria queries do not support positioned parameters" );
}
}

View File

@ -0,0 +1,56 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2012, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ejb.criteria.compile;
import javax.persistence.TypedQuery;
/**
* Used to describe implicit (not defined in criteria query) parameters.
*
* @author Steve Ebersole
*/
public interface ImplicitParameterBinding {
/**
* Retrieve the generated name of the implicit parameter.
*
* @return The parameter name.
*/
public String getParameterName();
/**
* Get the java type of the "thing" that led to the implicit parameter. Used from
* {@link org.hibernate.ejb.HibernateEntityManagerImplementor.Options#getNamedParameterExplicitTypes()}
* in determining "guessed type" overriding.
*
* @return The java type
*/
public Class getJavaType();
/**
* Bind the implicit parameter's value to the JPA query.
*
* @param typedQuery The JPA query.
*/
public void bind(TypedQuery typedQuery);
}

View File

@ -0,0 +1,38 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2012, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ejb.criteria.compile;
import javax.persistence.criteria.ParameterExpression;
import java.util.List;
import java.util.Map;
/**
* @author Steve Ebersole
*/
public interface InterpretedParameterMetadata {
public Map<ParameterExpression<?>,String> explicitParameterMapping();
public Map<String,ParameterExpression<?>> explicitParameterNameMapping();
public List<ImplicitParameterBinding> implicitParameterBindings();
public Map<String,Class> implicitParameterTypes();
}

View File

@ -0,0 +1,68 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2012, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ejb.criteria.compile;
import javax.persistence.criteria.ParameterExpression;
/**
* Used to provide a context and services to the rendering.
*
* @author Steve Ebersole
*/
public interface RenderingContext {
/**
* Generate a correlation name.
*
* @return The generated correlation name
*/
public String generateAlias();
/**
* Register parameters explicitly encountered in the criteria query.
*
* @param criteriaQueryParameter The parameter expression
*
* @return The JPA-QL parameter name
*/
public String registerExplicitParameter(ParameterExpression<?> criteriaQueryParameter);
/**
* Register a parameter that was not part of the criteria query (at least not as a parameter).
*
* @param literal The literal value
* @param javaType The java type as whcih to handle the literal value.
*
* @return The JPA-QL parameter name
*/
public String registerLiteralParameterBinding(Object literal, Class javaType);
/**
* Given a java type, determine the proper cast type name.
*
* @param javaType The java type.
*
* @return The cast type name.
*/
public String getCastType(Class javaType);
}

View File

@ -27,9 +27,9 @@ import java.io.Serializable;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.predicate.ImplicitNumericExpressionTypeDeterminer; import org.hibernate.ejb.criteria.predicate.ImplicitNumericExpressionTypeDeterminer;
/** /**
@ -228,14 +228,14 @@ public class BinaryArithmeticOperation<N extends Number>
Helper.possibleParameter( getLeftHandOperand(), registry ); Helper.possibleParameter( getLeftHandOperand(), registry );
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return getOperator().apply( return getOperator().apply(
( (Renderable) getLeftHandOperand() ).render( renderingContext ), ( (Renderable) getLeftHandOperand() ).render( renderingContext ),
( (Renderable) getRightHandOperand() ).render( renderingContext ) ( (Renderable) getRightHandOperand() ).render( renderingContext )
); );
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -30,9 +30,9 @@ import javax.persistence.criteria.CriteriaBuilder.Coalesce;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Models an ANSI SQL <tt>COALESCE</tt> expression. <tt>COALESCE</tt> is a specialized <tt>CASE</tt> statement. * Models an ANSI SQL <tt>COALESCE</tt> expression. <tt>COALESCE</tt> is a specialized <tt>CASE</tt> statement.
@ -83,7 +83,7 @@ public class CoalesceExpression<T> extends ExpressionImpl<T> implements Coalesce
} }
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
StringBuilder buffer = new StringBuilder( "coalesce(" ); StringBuilder buffer = new StringBuilder( "coalesce(" );
String sep = ""; String sep = "";
for ( Expression expression : getExpressions() ) { for ( Expression expression : getExpressions() ) {
@ -94,7 +94,7 @@ public class CoalesceExpression<T> extends ExpressionImpl<T> implements Coalesce
return buffer.append( ")" ).toString(); return buffer.append( ")" ).toString();
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -31,11 +31,11 @@ import javax.persistence.criteria.CompoundSelection;
import javax.persistence.criteria.Selection; import javax.persistence.criteria.Selection;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.TupleElementImplementor; import org.hibernate.ejb.criteria.TupleElementImplementor;
import org.hibernate.ejb.criteria.ValueHandlerFactory; import org.hibernate.ejb.criteria.ValueHandlerFactory;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* The Hibernate implementation of the JPA {@link CompoundSelection} * The Hibernate implementation of the JPA {@link CompoundSelection}
@ -89,7 +89,7 @@ public class CompoundSelectionImpl<X>
} }
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
StringBuilder buff = new StringBuilder(); StringBuilder buff = new StringBuilder();
if ( isConstructor ) { if ( isConstructor ) {
buff.append( "new " ).append( getJavaType().getName() ).append( '(' ); buff.append( "new " ).append( getJavaType().getName() ).append( '(' );
@ -106,7 +106,7 @@ public class CompoundSelectionImpl<X>
return buff.toString(); return buff.toString();
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -27,9 +27,9 @@ import java.io.Serializable;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* A string concatenation. * A string concatenation.
@ -80,13 +80,13 @@ public class ConcatExpression extends ExpressionImpl<String> implements Serializ
Helper.possibleParameter( getString2(), registry ); Helper.possibleParameter( getString2(), registry );
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return ( (Renderable) getString1() ).render( renderingContext ) return ( (Renderable) getString1() ).render( renderingContext )
+ " || " + " || "
+ ( (Renderable) getString2() ).render( renderingContext ); + ( (Renderable) getString2() ).render( renderingContext );
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -26,8 +26,8 @@ package org.hibernate.ejb.criteria.expression;
import java.io.Serializable; import java.io.Serializable;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* TODO : javadoc * TODO : javadoc
@ -43,12 +43,12 @@ public class EntityTypeExpression<T> extends ExpressionImpl<T> implements Serial
// nothign to do // nothign to do
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
// todo : is it valid for this to get rendered into the query itself? // todo : is it valid for this to get rendered into the query itself?
throw new IllegalArgumentException( "Unexpected call on EntityTypeExpression#render" ); throw new IllegalArgumentException( "Unexpected call on EntityTypeExpression#render" );
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -27,9 +27,9 @@ import java.io.Serializable;
import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.ListAttribute;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.PathImplementor; import org.hibernate.ejb.criteria.PathImplementor;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
@ -58,13 +58,13 @@ public class ListIndexExpression extends ExpressionImpl<Integer> implements Seri
// nothing to do // nothing to do
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return "index(" return "index("
+ origin.getPathIdentifier() + '.' + getListAttribute().getName() + origin.getPathIdentifier() + '.' + getListAttribute().getName()
+ ")"; + ")";
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -26,9 +26,9 @@ package org.hibernate.ejb.criteria.expression;
import java.io.Serializable; import java.io.Serializable;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.ValueHandlerFactory; import org.hibernate.ejb.criteria.ValueHandlerFactory;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Represents a literal expression. * Represents a literal expression.
@ -62,7 +62,7 @@ public class LiteralExpression<T> extends ExpressionImpl<T> implements Serializa
} }
@SuppressWarnings({ "unchecked" }) @SuppressWarnings({ "unchecked" })
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
if ( ValueHandlerFactory.isNumeric( literal ) ) { if ( ValueHandlerFactory.isNumeric( literal ) ) {
return ValueHandlerFactory.determineAppropriateHandler( (Class) literal.getClass() ).render( literal ); return ValueHandlerFactory.determineAppropriateHandler( (Class) literal.getClass() ).render( literal );
} }
@ -73,7 +73,7 @@ public class LiteralExpression<T> extends ExpressionImpl<T> implements Serializa
} }
@SuppressWarnings({ "unchecked" }) @SuppressWarnings({ "unchecked" })
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
// some drivers/servers do not like parameters in the select clause // some drivers/servers do not like parameters in the select clause
final ValueHandlerFactory.ValueHandler handler = final ValueHandlerFactory.ValueHandler handler =
ValueHandlerFactory.determineAppropriateHandler( literal.getClass() ); ValueHandlerFactory.determineAppropriateHandler( literal.getClass() );

View File

@ -29,10 +29,10 @@ import javax.persistence.criteria.Expression;
import javax.persistence.metamodel.MapAttribute; import javax.persistence.metamodel.MapAttribute;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.PathImplementor; import org.hibernate.ejb.criteria.PathImplementor;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* TODO : javadoc * TODO : javadoc
@ -64,16 +64,16 @@ public class MapEntryExpression<K,V>
// none to register // none to register
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
// don't think this is valid outside of select clause... // don't think this is valid outside of select clause...
throw new IllegalStateException( "illegal reference to map entry outside of select clause." ); throw new IllegalStateException( "illegal reference to map entry outside of select clause." );
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return "entry(" + path( renderingContext ) + ")"; return "entry(" + path( renderingContext ) + ")";
} }
private String path(CriteriaQueryCompiler.RenderingContext renderingContext) { private String path(RenderingContext renderingContext) {
return origin.getPathIdentifier() return origin.getPathIdentifier()
+ '.' + '.'
+ ( (Renderable) getAttribute() ).renderProjection( renderingContext ); + ( (Renderable) getAttribute() ).renderProjection( renderingContext );

View File

@ -26,8 +26,8 @@ package org.hibernate.ejb.criteria.expression;
import java.io.Serializable; import java.io.Serializable;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Represents a <tt>NULL</tt>literal expression. * Represents a <tt>NULL</tt>literal expression.
@ -43,11 +43,11 @@ public class NullLiteralExpression<T> extends ExpressionImpl<T> implements Seria
// nothing to do // nothing to do
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return "null"; return "null";
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -27,9 +27,9 @@ import java.io.Serializable;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Models an ANSI SQL <tt>NULLIF</tt> expression. <tt>NULLIF</tt> is a specialized <tt>CASE</tt> statement. * Models an ANSI SQL <tt>NULLIF</tt> expression. <tt>NULLIF</tt> is a specialized <tt>CASE</tt> statement.
@ -77,7 +77,7 @@ public class NullifExpression<T> extends ExpressionImpl<T> implements Serializab
Helper.possibleParameter( getSecondaryExpression(), registry ); Helper.possibleParameter( getSecondaryExpression(), registry );
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return "nullif(" return "nullif("
+ ( (Renderable) getPrimaryExpression() ).render( renderingContext ) + ( (Renderable) getPrimaryExpression() ).render( renderingContext )
+ ',' + ','
@ -85,7 +85,7 @@ public class NullifExpression<T> extends ExpressionImpl<T> implements Serializab
+ ")"; + ")";
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -27,8 +27,8 @@ import java.io.Serializable;
import javax.persistence.criteria.ParameterExpression; import javax.persistence.criteria.ParameterExpression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Defines a parameter specification, or the information about a parameter (where it occurs, what is * Defines a parameter specification, or the information about a parameter (where it occurs, what is
@ -84,12 +84,12 @@ public class ParameterExpressionImpl<T>
registry.registerParameter( this ); registry.registerParameter( this );
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
final String jpaqlParamName = renderingContext.registerExplicitParameter( this ); final String jpaqlParamName = renderingContext.registerExplicitParameter( this );
return ':' + jpaqlParamName; return ':' + jpaqlParamName;
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -26,8 +26,8 @@ package org.hibernate.ejb.criteria.expression;
import java.io.Serializable; import java.io.Serializable;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.path.AbstractPathImpl; import org.hibernate.ejb.criteria.path.AbstractPathImpl;
/** /**
@ -47,11 +47,11 @@ public class PathTypeExpression<T> extends ExpressionImpl<T> implements Serializ
// nothing to do // nothing to do
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return "type(" + pathImpl.getPathIdentifier() + ")"; return "type(" + pathImpl.getPathIdentifier() + ")";
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -30,9 +30,9 @@ import javax.persistence.criteria.CriteriaBuilder.Case;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Models what ANSI SQL terms a <tt>searched case expression</tt>. This is a <tt>CASE</tt> expression * Models what ANSI SQL terms a <tt>searched case expression</tt>. This is a <tt>CASE</tt> expression
@ -130,7 +130,7 @@ public class SearchedCaseExpression<R>
} }
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
StringBuilder caseStatement = new StringBuilder( "case" ); StringBuilder caseStatement = new StringBuilder( "case" );
for ( WhenClause whenClause : getWhenClauses() ) { for ( WhenClause whenClause : getWhenClauses() ) {
caseStatement.append( " when " ) caseStatement.append( " when " )
@ -144,7 +144,7 @@ public class SearchedCaseExpression<R>
return caseStatement.toString(); return caseStatement.toString();
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -30,9 +30,9 @@ import javax.persistence.criteria.CriteriaBuilder.SimpleCase;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Models what ANSI SQL terms a simple case statement. This is a <tt>CASE</tt> expression in the form<pre> * Models what ANSI SQL terms a simple case statement. This is a <tt>CASE</tt> expression in the form<pre>
@ -138,7 +138,7 @@ public class SimpleCaseExpression<C,R>
Helper.possibleParameter( getOtherwiseResult(), registry ); Helper.possibleParameter( getOtherwiseResult(), registry );
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
StringBuilder caseExpr = new StringBuilder(); StringBuilder caseExpr = new StringBuilder();
caseExpr.append( "case " ) caseExpr.append( "case " )
.append( ( (Renderable) getExpression() ).render( renderingContext ) ) .append( ( (Renderable) getExpression() ).render( renderingContext ) )
@ -154,7 +154,7 @@ public class SimpleCaseExpression<C,R>
return caseExpr.toString(); return caseExpr.toString();
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -27,8 +27,8 @@ import java.io.Serializable;
import java.util.Collection; import java.util.Collection;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.path.PluralAttributePath; import org.hibernate.ejb.criteria.path.PluralAttributePath;
/** /**
@ -57,11 +57,11 @@ public class SizeOfCollectionExpression<C extends Collection>
// nothing to do // nothing to do
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return "size(" + getCollectionPath().render( renderingContext ) + ")"; return "size(" + getCollectionPath().render( renderingContext ) + ")";
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -27,9 +27,9 @@ import java.io.Serializable;
import javax.persistence.criteria.Subquery; import javax.persistence.criteria.Subquery;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Represents a {@link Modifier#ALL}, {@link Modifier#ANY}, {@link Modifier#SOME} modifier appplied to a subquery as * Represents a {@link Modifier#ALL}, {@link Modifier#ANY}, {@link Modifier#SOME} modifier appplied to a subquery as
@ -84,11 +84,11 @@ public class SubqueryComparisonModifierExpression<Y>
// nothing to do (the subquery should be handled directly, and the modified itself is not parameterized) // nothing to do (the subquery should be handled directly, and the modified itself is not parameterized)
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return getModifier().rendered() + ( (Renderable) getSubquery() ).render( renderingContext ); return getModifier().rendered() + ( (Renderable) getSubquery() ).render( renderingContext );
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -27,9 +27,9 @@ import java.io.Serializable;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Models unary arithmetic operation (unary plus and unary minus). * Models unary arithmetic operation (unary plus and unary minus).
@ -75,12 +75,12 @@ public class UnaryArithmeticOperation<T>
Helper.possibleParameter( getOperand(), registry ); Helper.possibleParameter( getOperand(), registry );
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return ( getOperation() == Operation.UNARY_MINUS ? '-' : '+' ) return ( getOperation() == Operation.UNARY_MINUS ? '-' : '+' )
+ ( (Renderable) getOperand() ).render( renderingContext ); + ( (Renderable) getOperand() ).render( renderingContext );
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -41,4 +41,9 @@ public class AbsFunction<N extends Number>
public AbsFunction(CriteriaBuilderImpl criteriaBuilder, Expression expression) { public AbsFunction(CriteriaBuilderImpl criteriaBuilder, Expression expression) {
super( criteriaBuilder, expression.getJavaType(), NAME, expression ); super( criteriaBuilder, expression.getJavaType(), NAME, expression );
} }
@Override
protected boolean isStandardJpaFunction() {
return true;
}
} }

View File

@ -29,7 +29,7 @@ import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Root; import javax.persistence.criteria.Root;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler; import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.LiteralExpression; import org.hibernate.ejb.criteria.expression.LiteralExpression;
/** /**
@ -79,6 +79,11 @@ public class AggregationFunction<T>
return true; return true;
} }
@Override
protected boolean isStandardJpaFunction() {
return true;
}
/** /**
* Implementation of a <tt>COUNT</tt> function providing convenience in construction. * Implementation of a <tt>COUNT</tt> function providing convenience in construction.
* <p/> * <p/>
@ -96,9 +101,10 @@ public class AggregationFunction<T>
} }
@Override @Override
protected void renderArguments( StringBuilder buffer, protected void renderArguments(StringBuilder buffer, RenderingContext renderingContext) {
CriteriaQueryCompiler.RenderingContext renderingContext ) { if ( isDistinct() ) {
if (isDistinct()) buffer.append("distinct "); buffer.append("distinct ");
}
else { else {
// If function specifies a single non-distinct entity with ID, its alias would normally be rendered, which ends up // If function specifies a single non-distinct entity with ID, its alias would normally be rendered, which ends up
// converting to the column(s) associated with the entity's ID in the rendered SQL. However, some DBs don't support // converting to the column(s) associated with the entity's ID in the rendered SQL. However, some DBs don't support

View File

@ -26,8 +26,8 @@ package org.hibernate.ejb.criteria.expression.function;
import java.io.Serializable; import java.io.Serializable;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.ExpressionImpl; import org.hibernate.ejb.criteria.expression.ExpressionImpl;
/** /**
@ -65,11 +65,11 @@ public class BasicFunctionExpression<X>
// nothing to do here... // nothing to do here...
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return getFunctionName() + "()"; return getFunctionName() + "()";
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -26,8 +26,8 @@ package org.hibernate.ejb.criteria.expression.function;
import java.io.Serializable; import java.io.Serializable;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.ExpressionImpl; import org.hibernate.ejb.criteria.expression.ExpressionImpl;
/** /**
@ -63,7 +63,7 @@ public class CastFunction<T,Y>
} }
@Override @Override
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return CAST_NAME + '(' + return CAST_NAME + '(' +
castSource.render( renderingContext ) + castSource.render( renderingContext ) +
" as " + " as " +

View File

@ -38,6 +38,11 @@ public class LengthFunction
implements Serializable { implements Serializable {
public static final String NAME = "length"; public static final String NAME = "length";
@Override
protected boolean isStandardJpaFunction() {
return true;
}
public LengthFunction(CriteriaBuilderImpl criteriaBuilder, Expression<String> value) { public LengthFunction(CriteriaBuilderImpl criteriaBuilder, Expression<String> value) {
super( criteriaBuilder, Integer.class, NAME, value ); super( criteriaBuilder, Integer.class, NAME, value );
} }

View File

@ -27,9 +27,9 @@ import java.io.Serializable;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.LiteralExpression; import org.hibernate.ejb.criteria.expression.LiteralExpression;
/** /**
@ -102,7 +102,7 @@ public class LocateFunction
} }
@Override @Override
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
buffer.append( "locate(" ) buffer.append( "locate(" )
.append( ( (Renderable) getPattern() ).render( renderingContext ) ) .append( ( (Renderable) getPattern() ).render( renderingContext ) )

View File

@ -41,4 +41,9 @@ public class LowerFunction
public LowerFunction(CriteriaBuilderImpl criteriaBuilder, Expression<String> string) { public LowerFunction(CriteriaBuilderImpl criteriaBuilder, Expression<String> string) {
super( criteriaBuilder, String.class, NAME, string ); super( criteriaBuilder, String.class, NAME, string );
} }
@Override
protected boolean isStandardJpaFunction() {
return true;
}
} }

View File

@ -29,10 +29,10 @@ import java.util.List;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterContainer; import org.hibernate.ejb.criteria.ParameterContainer;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.LiteralExpression; import org.hibernate.ejb.criteria.expression.LiteralExpression;
/** /**
@ -44,7 +44,29 @@ public class ParameterizedFunctionExpression<X>
extends BasicFunctionExpression<X> extends BasicFunctionExpression<X>
implements FunctionExpression<X> { implements FunctionExpression<X> {
public static List<String> STANDARD_JPA_FUNCTION_NAMES = Arrays.asList(
// 4.6.17.2.1
"CONCAT",
"SUBSTRING",
"TRIM",
"UPPER",
"LOWER",
"LOCATE",
"LENGTH",
//4.6.17.2.2
"ABS",
"SQRT",
"MOD",
"SIZE",
"INDEX",
// 4.6.17.2.3
"CURRENT_DATE",
"CURRENT_TIME",
"CURRENT_TIMESTAMP"
);
private final List<Expression<?>> argumentExpressions; private final List<Expression<?>> argumentExpressions;
private final boolean isStandardJpaFunction;
public ParameterizedFunctionExpression( public ParameterizedFunctionExpression(
CriteriaBuilderImpl criteriaBuilder, CriteriaBuilderImpl criteriaBuilder,
@ -53,6 +75,7 @@ public class ParameterizedFunctionExpression<X>
List<Expression<?>> argumentExpressions) { List<Expression<?>> argumentExpressions) {
super( criteriaBuilder, javaType, functionName ); super( criteriaBuilder, javaType, functionName );
this.argumentExpressions = argumentExpressions; this.argumentExpressions = argumentExpressions;
this.isStandardJpaFunction = STANDARD_JPA_FUNCTION_NAMES.contains( functionName.toUpperCase() );
} }
public ParameterizedFunctionExpression( public ParameterizedFunctionExpression(
@ -62,14 +85,11 @@ public class ParameterizedFunctionExpression<X>
Expression<?>... argumentExpressions) { Expression<?>... argumentExpressions) {
super( criteriaBuilder, javaType, functionName ); super( criteriaBuilder, javaType, functionName );
this.argumentExpressions = Arrays.asList( argumentExpressions ); this.argumentExpressions = Arrays.asList( argumentExpressions );
this.isStandardJpaFunction = STANDARD_JPA_FUNCTION_NAMES.contains( functionName.toUpperCase() );
} }
protected static List<Expression<?>> wrapAsLiterals(CriteriaBuilderImpl criteriaBuilder, Object... literalArguments) { protected boolean isStandardJpaFunction() {
List<Expression<?>> arguments = new ArrayList<Expression<?>>( properSize( literalArguments.length) ); return isStandardJpaFunction;
for ( Object o : literalArguments ) {
arguments.add( new LiteralExpression( criteriaBuilder, o ) );
}
return arguments;
} }
protected static int properSize(int number) { protected static int properSize(int number) {
@ -90,21 +110,28 @@ public class ParameterizedFunctionExpression<X>
} }
@Override @Override
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
StringBuilder buffer = new StringBuilder() StringBuilder buffer = new StringBuilder();
.append( "function('" ) if ( isStandardJpaFunction() ) {
.append( getFunctionName() ) buffer.append( getFunctionName() )
.append( "', " ); .append( "(" );
}
else {
buffer.append( "function('" )
.append( getFunctionName() )
.append( "', " );
}
renderArguments( buffer, renderingContext ); renderArguments( buffer, renderingContext );
buffer.append( ')' ); buffer.append( ')' );
return buffer.toString(); return buffer.toString();
} }
protected void renderArguments(StringBuilder buffer, CriteriaQueryCompiler.RenderingContext renderingContext) { protected void renderArguments(StringBuilder buffer, RenderingContext renderingContext) {
String sep = ""; String sep = "";
for ( Expression argument : argumentExpressions ) { for ( Expression argument : argumentExpressions ) {
buffer.append( sep ).append( ( (Renderable) argument ).render( renderingContext ) ); buffer.append( sep ).append( ( (Renderable) argument ).render( renderingContext ) );
sep = ", "; sep = ", ";
} }
} }
} }

View File

@ -41,4 +41,9 @@ public class SqrtFunction
public SqrtFunction(CriteriaBuilderImpl criteriaBuilder, Expression<? extends Number> expression) { public SqrtFunction(CriteriaBuilderImpl criteriaBuilder, Expression<? extends Number> expression) {
super( criteriaBuilder, Double.class, NAME, expression ); super( criteriaBuilder, Double.class, NAME, expression );
} }
@Override
protected boolean isStandardJpaFunction() {
return true;
}
} }

View File

@ -27,9 +27,9 @@ import java.io.Serializable;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.LiteralExpression; import org.hibernate.ejb.criteria.expression.LiteralExpression;
/** /**
@ -108,7 +108,7 @@ public class SubstringFunction
Helper.possibleParameter( getValue(), registry ); Helper.possibleParameter( getValue(), registry );
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
buffer.append( "substring(" ) buffer.append( "substring(" )
.append( ( (Renderable) getValue() ).render( renderingContext ) ) .append( ( (Renderable) getValue() ).render( renderingContext ) )

View File

@ -28,9 +28,9 @@ import javax.persistence.criteria.CriteriaBuilder.Trimspec;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.LiteralExpression; import org.hibernate.ejb.criteria.expression.LiteralExpression;
/** /**
@ -117,7 +117,7 @@ public class TrimFunction
} }
@Override @Override
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return new StringBuilder() return new StringBuilder()
.append( "trim(" ) .append( "trim(" )
.append( trimspec.name() ) .append( trimspec.name() )

View File

@ -41,4 +41,9 @@ public class UpperFunction
public UpperFunction(CriteriaBuilderImpl criteriaBuilder, Expression<String> string) { public UpperFunction(CriteriaBuilderImpl criteriaBuilder, Expression<String> string) {
super( criteriaBuilder, String.class, NAME, string ); super( criteriaBuilder, String.class, NAME, string );
} }
@Override
protected boolean isStandardJpaFunction() {
return true;
}
} }

View File

@ -48,7 +48,6 @@ import javax.persistence.metamodel.Type;
import org.hibernate.ejb.criteria.BasicPathUsageException; import org.hibernate.ejb.criteria.BasicPathUsageException;
import org.hibernate.ejb.criteria.CollectionJoinImplementor; import org.hibernate.ejb.criteria.CollectionJoinImplementor;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl;
import org.hibernate.ejb.criteria.FromImplementor; import org.hibernate.ejb.criteria.FromImplementor;
import org.hibernate.ejb.criteria.JoinImplementor; import org.hibernate.ejb.criteria.JoinImplementor;
@ -56,6 +55,7 @@ import org.hibernate.ejb.criteria.ListJoinImplementor;
import org.hibernate.ejb.criteria.MapJoinImplementor; import org.hibernate.ejb.criteria.MapJoinImplementor;
import org.hibernate.ejb.criteria.PathSource; import org.hibernate.ejb.criteria.PathSource;
import org.hibernate.ejb.criteria.SetJoinImplementor; import org.hibernate.ejb.criteria.SetJoinImplementor;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Convenience base class for various {@link javax.persistence.criteria.From} implementations. * Convenience base class for various {@link javax.persistence.criteria.From} implementations.
@ -96,7 +96,7 @@ public abstract class AbstractFromImpl<Z,X>
} }
@Override @Override
public void prepareAlias(CriteriaQueryCompiler.RenderingContext renderingContext) { public void prepareAlias(RenderingContext renderingContext) {
if ( getAlias() == null ) { if ( getAlias() == null ) {
if ( isCorrelated() ) { if ( isCorrelated() ) {
setAlias( getCorrelationParent().getAlias() ); setAlias( getCorrelationParent().getAlias() );
@ -108,13 +108,13 @@ public abstract class AbstractFromImpl<Z,X>
} }
@Override @Override
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
prepareAlias( renderingContext ); prepareAlias( renderingContext );
return getAlias(); return getAlias();
} }
@Override @Override
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return renderProjection( renderingContext ); return renderProjection( renderingContext );
} }
@ -227,7 +227,7 @@ public abstract class AbstractFromImpl<Z,X>
protected abstract boolean canBeJoinSource(); protected abstract boolean canBeJoinSource();
private RuntimeException illegalJoin() { protected RuntimeException illegalJoin() {
return new IllegalArgumentException( return new IllegalArgumentException(
"Collection of values [" + getPathIdentifier() + "] cannot be source of a join" "Collection of values [" + getPathIdentifier() + "] cannot be source of a join"
); );
@ -521,7 +521,7 @@ public abstract class AbstractFromImpl<Z,X>
return canBeJoinSource(); return canBeJoinSource();
} }
private RuntimeException illegalFetch() { protected RuntimeException illegalFetch() {
return new IllegalArgumentException( return new IllegalArgumentException(
"Collection of values [" + getPathIdentifier() + "] cannot be source of a fetch" "Collection of values [" + getPathIdentifier() + "] cannot be source of a fetch"
); );

View File

@ -31,11 +31,11 @@ import javax.persistence.metamodel.Attribute;
import java.io.Serializable; import java.io.Serializable;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl;
import org.hibernate.ejb.criteria.FromImplementor; import org.hibernate.ejb.criteria.FromImplementor;
import org.hibernate.ejb.criteria.JoinImplementor; import org.hibernate.ejb.criteria.JoinImplementor;
import org.hibernate.ejb.criteria.PathSource; import org.hibernate.ejb.criteria.PathSource;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.predicate.AbstractPredicateImpl; import org.hibernate.ejb.criteria.predicate.AbstractPredicateImpl;
/** /**
@ -89,7 +89,7 @@ public abstract class AbstractJoinImpl<Z, X>
} }
@Override @Override
public String renderTableExpression(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderTableExpression(RenderingContext renderingContext) {
prepareAlias( renderingContext ); prepareAlias( renderingContext );
( (FromImplementor) getParent() ).prepareAlias( renderingContext ); ( (FromImplementor) getParent() ).prepareAlias( renderingContext );
StringBuilder tableExpression = new StringBuilder(); StringBuilder tableExpression = new StringBuilder();

View File

@ -35,10 +35,10 @@ import javax.persistence.metamodel.PluralAttribute;
import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.SingularAttribute;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.PathImplementor; import org.hibernate.ejb.criteria.PathImplementor;
import org.hibernate.ejb.criteria.PathSource; import org.hibernate.ejb.criteria.PathSource;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.ExpressionImpl; import org.hibernate.ejb.criteria.expression.ExpressionImpl;
import org.hibernate.ejb.criteria.expression.PathTypeExpression; import org.hibernate.ejb.criteria.expression.PathTypeExpression;
@ -230,7 +230,7 @@ public abstract class AbstractPathImpl<X>
} }
@Override @Override
public void prepareAlias(CriteriaQueryCompiler.RenderingContext renderingContext) { public void prepareAlias(RenderingContext renderingContext) {
// Make sure we delegate up to our source (eventually up to the path root) to // Make sure we delegate up to our source (eventually up to the path root) to
// prepare the path properly. // prepare the path properly.
PathSource<?> source = getPathSource(); PathSource<?> source = getPathSource();
@ -240,7 +240,7 @@ public abstract class AbstractPathImpl<X>
} }
@Override @Override
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
PathSource<?> source = getPathSource(); PathSource<?> source = getPathSource();
if ( source != null ) { if ( source != null ) {
source.prepareAlias( renderingContext ); source.prepareAlias( renderingContext );
@ -252,7 +252,7 @@ public abstract class AbstractPathImpl<X>
} }
@Override @Override
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -32,11 +32,11 @@ import javax.persistence.metamodel.CollectionAttribute;
import org.hibernate.ejb.criteria.CollectionJoinImplementor; import org.hibernate.ejb.criteria.CollectionJoinImplementor;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl;
import org.hibernate.ejb.criteria.FromImplementor; import org.hibernate.ejb.criteria.FromImplementor;
import org.hibernate.ejb.criteria.PathImplementor; import org.hibernate.ejb.criteria.PathImplementor;
import org.hibernate.ejb.criteria.PathSource; import org.hibernate.ejb.criteria.PathSource;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Models a join based on a plural association attribute. * Models a join based on a plural association attribute.
@ -105,7 +105,7 @@ public class CollectionAttributeJoin<O,E>
original.criteriaBuilder(), original.criteriaBuilder(),
treatAsType, treatAsType,
original.getPathSource(), original.getPathSource(),
(CollectionAttribute<? super O,T>) original.getAttribute(), (CollectionAttribute<? super O, T>) original.getAttribute(),
original.getJoinType() original.getJoinType()
); );
this.original = original; this.original = original;
@ -118,12 +118,12 @@ public class CollectionAttributeJoin<O,E>
} }
@Override @Override
public void prepareAlias(CriteriaQueryCompiler.RenderingContext renderingContext) { public void prepareAlias(RenderingContext renderingContext) {
// do nothing... // do nothing...
} }
@Override @Override
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return "treat(" + original.render( renderingContext ) + " as " + treatAsType.getName() + ")"; return "treat(" + original.render( renderingContext ) + " as " + treatAsType.getName() + ")";
} }
} }

View File

@ -31,12 +31,12 @@ import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.ListAttribute;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl;
import org.hibernate.ejb.criteria.FromImplementor; import org.hibernate.ejb.criteria.FromImplementor;
import org.hibernate.ejb.criteria.ListJoinImplementor; import org.hibernate.ejb.criteria.ListJoinImplementor;
import org.hibernate.ejb.criteria.PathImplementor; import org.hibernate.ejb.criteria.PathImplementor;
import org.hibernate.ejb.criteria.PathSource; import org.hibernate.ejb.criteria.PathSource;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.ListIndexExpression; import org.hibernate.ejb.criteria.expression.ListIndexExpression;
/** /**
@ -113,7 +113,7 @@ public class ListAttributeJoin<O,E>
original.criteriaBuilder(), original.criteriaBuilder(),
treatAsType, treatAsType,
original.getPathSource(), original.getPathSource(),
(ListAttribute<? super O,T>) original.getAttribute(), (ListAttribute<? super O, T>) original.getAttribute(),
original.getJoinType() original.getJoinType()
); );
this.original = original; this.original = original;
@ -126,12 +126,12 @@ public class ListAttributeJoin<O,E>
} }
@Override @Override
public void prepareAlias(CriteriaQueryCompiler.RenderingContext renderingContext) { public void prepareAlias(RenderingContext renderingContext) {
// do nothing... // do nothing...
} }
@Override @Override
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return "treat(" + original.render( renderingContext ) + " as " + treatAsType.getName() + ")"; return "treat(" + original.render( renderingContext ) + " as " + treatAsType.getName() + ")";
} }
} }

View File

@ -32,12 +32,12 @@ import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.MapAttribute; import javax.persistence.metamodel.MapAttribute;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl;
import org.hibernate.ejb.criteria.FromImplementor; import org.hibernate.ejb.criteria.FromImplementor;
import org.hibernate.ejb.criteria.MapJoinImplementor; import org.hibernate.ejb.criteria.MapJoinImplementor;
import org.hibernate.ejb.criteria.PathImplementor; import org.hibernate.ejb.criteria.PathImplementor;
import org.hibernate.ejb.criteria.PathSource; import org.hibernate.ejb.criteria.PathSource;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.MapEntryExpression; import org.hibernate.ejb.criteria.expression.MapEntryExpression;
/** /**
@ -134,7 +134,7 @@ public class MapAttributeJoin<O,K,V>
original.criteriaBuilder(), original.criteriaBuilder(),
treatAsType, treatAsType,
original.getPathSource(), original.getPathSource(),
(MapAttribute<? super O,K,T>) original.getAttribute(), (MapAttribute<? super O, K, T>) original.getAttribute(),
original.getJoinType() original.getJoinType()
); );
this.original = original; this.original = original;
@ -147,12 +147,12 @@ public class MapAttributeJoin<O,K,V>
} }
@Override @Override
public void prepareAlias(CriteriaQueryCompiler.RenderingContext renderingContext) { public void prepareAlias(RenderingContext renderingContext) {
// do nothing... // do nothing...
} }
@Override @Override
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return "treat(" + original.render( renderingContext ) + " as " + treatAsType.getName() + ")"; return "treat(" + original.render( renderingContext ) + " as " + treatAsType.getName() + ")";
} }
} }

View File

@ -28,9 +28,9 @@ import javax.persistence.criteria.Root;
import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.EntityType;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl;
import org.hibernate.ejb.criteria.FromImplementor; import org.hibernate.ejb.criteria.FromImplementor;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Hibernate implementation of the JPA {@link Root} contract * Hibernate implementation of the JPA {@link Root} contract
@ -39,12 +39,16 @@ import org.hibernate.ejb.criteria.FromImplementor;
*/ */
public class RootImpl<X> extends AbstractFromImpl<X,X> implements Root<X>, Serializable { public class RootImpl<X> extends AbstractFromImpl<X,X> implements Root<X>, Serializable {
private final EntityType<X> entityType; private final EntityType<X> entityType;
private final boolean allowJoins;
public RootImpl( public RootImpl(CriteriaBuilderImpl criteriaBuilder, EntityType<X> entityType) {
CriteriaBuilderImpl criteriaBuilder, this( criteriaBuilder, entityType, true );
EntityType<X> entityType) { }
public RootImpl(CriteriaBuilderImpl criteriaBuilder, EntityType<X> entityType, boolean allowJoins) {
super( criteriaBuilder, entityType.getJavaType() ); super( criteriaBuilder, entityType.getJavaType() );
this.entityType = entityType; this.entityType = entityType;
this.allowJoins = allowJoins;
} }
public EntityType<X> getEntityType() { public EntityType<X> getEntityType() {
@ -67,10 +71,22 @@ public class RootImpl<X> extends AbstractFromImpl<X,X> implements Root<X>, Seria
@Override @Override
protected boolean canBeJoinSource() { protected boolean canBeJoinSource() {
return true; return allowJoins;
} }
public String renderTableExpression(CriteriaQueryCompiler.RenderingContext renderingContext) { @Override
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
protected RuntimeException illegalJoin() {
return allowJoins ? super.illegalJoin() : new IllegalArgumentException( "UPDATE/DELETE criteria queries cannot define joins" );
}
@Override
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
protected RuntimeException illegalFetch() {
return allowJoins ? super.illegalFetch() : new IllegalArgumentException( "UPDATE/DELETE criteria queries cannot define fetches" );
}
public String renderTableExpression(RenderingContext renderingContext) {
prepareAlias( renderingContext ); prepareAlias( renderingContext );
return getModel().getName() + " as " + getAlias(); return getModel().getName() + " as " + getAlias();
} }
@ -81,13 +97,13 @@ public class RootImpl<X> extends AbstractFromImpl<X,X> implements Root<X>, Seria
} }
@Override @Override
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
prepareAlias( renderingContext ); prepareAlias( renderingContext );
return getAlias(); return getAlias();
} }
@Override @Override
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
@ -115,12 +131,12 @@ public class RootImpl<X> extends AbstractFromImpl<X,X> implements Root<X>, Seria
} }
@Override @Override
public void prepareAlias(CriteriaQueryCompiler.RenderingContext renderingContext) { public void prepareAlias(RenderingContext renderingContext) {
// do nothing... // do nothing...
} }
@Override @Override
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return "treat(" + original.getAlias() + " as " + treatAsType.getName() + ")"; return "treat(" + original.getAlias() + " as " + treatAsType.getName() + ")";
} }
} }

View File

@ -31,12 +31,12 @@ import javax.persistence.criteria.Predicate;
import javax.persistence.metamodel.SetAttribute; import javax.persistence.metamodel.SetAttribute;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl;
import org.hibernate.ejb.criteria.FromImplementor; import org.hibernate.ejb.criteria.FromImplementor;
import org.hibernate.ejb.criteria.PathImplementor; import org.hibernate.ejb.criteria.PathImplementor;
import org.hibernate.ejb.criteria.PathSource; import org.hibernate.ejb.criteria.PathSource;
import org.hibernate.ejb.criteria.SetJoinImplementor; import org.hibernate.ejb.criteria.SetJoinImplementor;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Models a join based on a set-style plural association attribute. * Models a join based on a set-style plural association attribute.
@ -110,7 +110,7 @@ public class SetAttributeJoin<O,E>
original.criteriaBuilder(), original.criteriaBuilder(),
treatAsType, treatAsType,
original.getPathSource(), original.getPathSource(),
(SetAttribute<? super O,T>) original.getAttribute(), (SetAttribute<? super O, T>) original.getAttribute(),
original.getJoinType() original.getJoinType()
); );
this.original = original; this.original = original;
@ -123,12 +123,12 @@ public class SetAttributeJoin<O,E>
} }
@Override @Override
public void prepareAlias(CriteriaQueryCompiler.RenderingContext renderingContext) { public void prepareAlias(RenderingContext renderingContext) {
// do nothing... // do nothing...
} }
@Override @Override
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return "treat(" + original.render( renderingContext ) + " as " + treatAsType.getName() + ")"; return "treat(" + original.render( renderingContext ) + " as " + treatAsType.getName() + ")";
} }
} }

View File

@ -29,10 +29,10 @@ import javax.persistence.metamodel.Bindable;
import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.SingularAttribute;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.CriteriaSubqueryImpl; import org.hibernate.ejb.criteria.CriteriaSubqueryImpl;
import org.hibernate.ejb.criteria.FromImplementor; import org.hibernate.ejb.criteria.FromImplementor;
import org.hibernate.ejb.criteria.PathSource; import org.hibernate.ejb.criteria.PathSource;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Models a join based on a singular attribute * Models a join based on a singular attribute
@ -117,12 +117,12 @@ public class SingularAttributeJoin<O,X> extends AbstractJoinImpl<O,X> {
} }
@Override @Override
public void prepareAlias(CriteriaQueryCompiler.RenderingContext renderingContext) { public void prepareAlias(RenderingContext renderingContext) {
// do nothing... // do nothing...
} }
@Override @Override
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return "treat(" + original.render( renderingContext ) + " as " + treatAsType.getName() + ")"; return "treat(" + original.render( renderingContext ) + " as " + treatAsType.getName() + ")";
} }
} }

View File

@ -32,8 +32,8 @@ import javax.persistence.metamodel.ManagedType;
import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.SingularAttribute;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.PathSource; import org.hibernate.ejb.criteria.PathSource;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Models a path for a {@link SingularAttribute} generally obtained from a * Models a path for a {@link SingularAttribute} generally obtained from a
@ -109,7 +109,7 @@ public class SingularAttributePath<X> extends AbstractPathImpl<X> implements Ser
original.criteriaBuilder(), original.criteriaBuilder(),
treatAsType, treatAsType,
original.getPathSource(), original.getPathSource(),
(SingularAttribute<?,T>) original.getAttribute() (SingularAttribute<?, T>) original.getAttribute()
); );
this.original = original; this.original = original;
this.treatAsType = treatAsType; this.treatAsType = treatAsType;
@ -121,12 +121,12 @@ public class SingularAttributePath<X> extends AbstractPathImpl<X> implements Ser
} }
@Override @Override
public void prepareAlias(CriteriaQueryCompiler.RenderingContext renderingContext) { public void prepareAlias(RenderingContext renderingContext) {
// do nothing... // do nothing...
} }
@Override @Override
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return "treat(" + original.render( renderingContext ) + " as " + treatAsType.getName() + ")"; return "treat(" + original.render( renderingContext ) + " as " + treatAsType.getName() + ")";
} }
} }

View File

@ -27,9 +27,9 @@ import java.io.Serializable;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Models a <tt>BETWEEN</tt> {@link javax.persistence.criteria.Predicate}. * Models a <tt>BETWEEN</tt> {@link javax.persistence.criteria.Predicate}.
@ -85,7 +85,7 @@ public class BetweenPredicate<Y>
Helper.possibleParameter( getUpperBound(), registry ); Helper.possibleParameter( getUpperBound(), registry );
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
final String operator = isNegated() ? " not between " : " between "; final String operator = isNegated() ? " not between " : " between ";
return ( (Renderable) getExpression() ).render( renderingContext ) return ( (Renderable) getExpression() ).render( renderingContext )
+ operator + operator
@ -94,7 +94,7 @@ public class BetweenPredicate<Y>
+ ( (Renderable) getUpperBound() ).render( renderingContext ); + ( (Renderable) getUpperBound() ).render( renderingContext );
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -27,9 +27,9 @@ import java.io.Serializable;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Predicate to assert the explicit value of a boolean expression:<ul> * Predicate to assert the explicit value of a boolean expression:<ul>
@ -74,7 +74,7 @@ public class BooleanAssertionPredicate
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
final String operator = isNegated() ? " <> " : " = "; final String operator = isNegated() ? " <> " : " = ";
final String assertionLiteral = assertedValue ? "true" : "false"; final String assertionLiteral = assertedValue ? "true" : "false";
@ -86,7 +86,7 @@ public class BooleanAssertionPredicate
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }

View File

@ -28,9 +28,9 @@ import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Predicate;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Defines a {@link Predicate} used to wrap an {@link Expression Expression&lt;Boolean&gt;}. * Defines a {@link Predicate} used to wrap an {@link Expression Expression&lt;Boolean&gt;}.
@ -60,11 +60,11 @@ public class BooleanExpressionPredicate
Helper.possibleParameter(expression, registry); Helper.possibleParameter(expression, registry);
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return ( (Renderable) getExpression() ).render( renderingContext ); return ( (Renderable) getExpression() ).render( renderingContext );
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -26,8 +26,8 @@ package org.hibernate.ejb.criteria.predicate;
import java.io.Serializable; import java.io.Serializable;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Predicate used to assert a static boolean condition. * Predicate used to assert a static boolean condition.
@ -60,7 +60,7 @@ public class BooleanStaticAssertionPredicate
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
boolean isTrue = getAssertedValue(); boolean isTrue = getAssertedValue();
if ( isNegated() ) { if ( isNegated() ) {
isTrue = !isTrue; isTrue = !isTrue;
@ -74,7 +74,7 @@ public class BooleanStaticAssertionPredicate
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }

View File

@ -27,10 +27,10 @@ import java.io.Serializable;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.ValueHandlerFactory; import org.hibernate.ejb.criteria.ValueHandlerFactory;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.BinaryOperatorExpression; import org.hibernate.ejb.criteria.expression.BinaryOperatorExpression;
import org.hibernate.ejb.criteria.expression.LiteralExpression; import org.hibernate.ejb.criteria.expression.LiteralExpression;
@ -174,13 +174,13 @@ public class ComparisonPredicate
public abstract String rendered(); public abstract String rendered();
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return ( (Renderable) getLeftHandOperand() ).render( renderingContext ) return ( (Renderable) getLeftHandOperand() ).render( renderingContext )
+ getComparisonOperator().rendered() + getComparisonOperator().rendered()
+ ( (Renderable) getRightHandOperand() ).render( renderingContext ); + ( (Renderable) getRightHandOperand() ).render( renderingContext );
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -31,9 +31,9 @@ import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Predicate;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* A compound {@link Predicate predicate} is a grouping of other {@link Predicate predicates} in order to convert * A compound {@link Predicate predicate} is a grouping of other {@link Predicate predicates} in order to convert
@ -114,7 +114,7 @@ public class CompoundPredicate
} }
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
if ( getExpressions().size() == 0 ) { if ( getExpressions().size() == 0 ) {
boolean implicitTrue = getOperator() == BooleanOperator.AND; boolean implicitTrue = getOperator() == BooleanOperator.AND;
if ( isNegated() ) { if ( isNegated() ) {
@ -145,7 +145,7 @@ public class CompoundPredicate
: " or "; : " or ";
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }

View File

@ -27,9 +27,9 @@ import java.io.Serializable;
import javax.persistence.criteria.Subquery; import javax.persistence.criteria.Subquery;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* Models an <tt>EXISTS(<subquery>)</tt> predicate * Models an <tt>EXISTS(<subquery>)</tt> predicate
@ -54,12 +54,12 @@ public class ExistsPredicate
// nothing to do here // nothing to do here
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return ( isNegated() ? "not " : "" ) + "exists " return ( isNegated() ? "not " : "" ) + "exists "
+ ( (Renderable) getSubquery() ).render( renderingContext ); + ( (Renderable) getSubquery() ).render( renderingContext );
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -27,9 +27,9 @@ import java.io.Serializable;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
/** /**
* ANSI-SQL defines <tt>TRUE</tt>, <tt>FALSE</tt> and <tt>UNKNOWN</tt> as <i>truth values</i>. These * ANSI-SQL defines <tt>TRUE</tt>, <tt>FALSE</tt> and <tt>UNKNOWN</tt> as <i>truth values</i>. These
@ -66,13 +66,13 @@ public class ExplicitTruthValueCheck
Helper.possibleParameter( getBooleanExpression(), registry ); Helper.possibleParameter( getBooleanExpression(), registry );
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return ( (Renderable) getBooleanExpression() ).render( renderingContext ) return ( (Renderable) getBooleanExpression() ).render( renderingContext )
+ " = " + " = "
+ ( getTruthValue() == TruthValue.TRUE ? "true" : "false" ); + ( getTruthValue() == TruthValue.TRUE ? "true" : "false" );
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -32,10 +32,10 @@ import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Subquery; import javax.persistence.criteria.Subquery;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.ValueHandlerFactory; import org.hibernate.ejb.criteria.ValueHandlerFactory;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.LiteralExpression; import org.hibernate.ejb.criteria.expression.LiteralExpression;
/** /**
@ -158,7 +158,7 @@ public class InPredicate<T>
} }
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
buffer.append( ( (Renderable) getExpression() ).render( renderingContext ) ); buffer.append( ( (Renderable) getExpression() ).render( renderingContext ) );
@ -188,7 +188,7 @@ public class InPredicate<T>
return buffer.toString(); return buffer.toString();
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -27,8 +27,8 @@ import java.io.Serializable;
import java.util.Collection; import java.util.Collection;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.UnaryOperatorExpression; import org.hibernate.ejb.criteria.expression.UnaryOperatorExpression;
import org.hibernate.ejb.criteria.path.PluralAttributePath; import org.hibernate.ejb.criteria.path.PluralAttributePath;
@ -58,12 +58,12 @@ public class IsEmptyPredicate<C extends Collection>
// nothing to do // nothing to do
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
final String operator = isNegated() ? " is not empty" : " is empty"; final String operator = isNegated() ? " is not empty" : " is empty";
return getOperand().render( renderingContext ) + operator; return getOperand().render( renderingContext ) + operator;
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -27,9 +27,9 @@ import java.io.Serializable;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.LiteralExpression; import org.hibernate.ejb.criteria.expression.LiteralExpression;
/** /**
@ -124,7 +124,7 @@ public class LikePredicate extends AbstractSimplePredicate implements Serializab
Helper.possibleParameter( getPattern(), registry ); Helper.possibleParameter( getPattern(), registry );
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
final String operator = isNegated() ? " not like " : " like "; final String operator = isNegated() ? " not like " : " like ";
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
buffer.append( ( (Renderable) getMatchExpression() ).render( renderingContext ) ) buffer.append( ( (Renderable) getMatchExpression() ).render( renderingContext ) )
@ -137,7 +137,7 @@ public class LikePredicate extends AbstractSimplePredicate implements Serializab
return buffer.toString(); return buffer.toString();
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -28,9 +28,9 @@ import java.util.Collection;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.LiteralExpression; import org.hibernate.ejb.criteria.expression.LiteralExpression;
import org.hibernate.ejb.criteria.path.PluralAttributePath; import org.hibernate.ejb.criteria.path.PluralAttributePath;
@ -79,13 +79,13 @@ public class MemberOfPredicate<E, C extends Collection<E>>
Helper.possibleParameter( getElementExpression(), registry ); Helper.possibleParameter( getElementExpression(), registry );
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return ( (Renderable) elementExpression ).render( renderingContext ) return ( (Renderable) elementExpression ).render( renderingContext )
+ ( isNegated() ? " not" : "" ) + " member of " + ( isNegated() ? " not" : "" ) + " member of "
+ getCollectionPath().render( renderingContext ); + getCollectionPath().render( renderingContext );
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -27,9 +27,9 @@ import java.io.Serializable;
import javax.persistence.criteria.Expression; import javax.persistence.criteria.Expression;
import org.hibernate.ejb.criteria.CriteriaBuilderImpl; import org.hibernate.ejb.criteria.CriteriaBuilderImpl;
import org.hibernate.ejb.criteria.CriteriaQueryCompiler;
import org.hibernate.ejb.criteria.ParameterRegistry; import org.hibernate.ejb.criteria.ParameterRegistry;
import org.hibernate.ejb.criteria.Renderable; import org.hibernate.ejb.criteria.Renderable;
import org.hibernate.ejb.criteria.compile.RenderingContext;
import org.hibernate.ejb.criteria.expression.UnaryOperatorExpression; import org.hibernate.ejb.criteria.expression.UnaryOperatorExpression;
/** /**
@ -67,7 +67,7 @@ public class NullnessPredicate
Helper.possibleParameter( getOperand(), registry ); Helper.possibleParameter( getOperand(), registry );
} }
public String render(CriteriaQueryCompiler.RenderingContext renderingContext) { public String render(RenderingContext renderingContext) {
return ( (Renderable) operand ).render( renderingContext ) + check(); return ( (Renderable) operand ).render( renderingContext ) + check();
} }
@ -77,7 +77,7 @@ public class NullnessPredicate
: " is null"; : " is null";
} }
public String renderProjection(CriteriaQueryCompiler.RenderingContext renderingContext) { public String renderProjection(RenderingContext renderingContext) {
return render( renderingContext ); return render( renderingContext );
} }
} }

View File

@ -0,0 +1,173 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2012, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ejb.criteria;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaDelete;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.criteria.Root;
import org.hibernate.ejb.metamodel.AbstractMetamodelSpecificTest;
import org.hibernate.ejb.metamodel.Customer;
import org.hibernate.ejb.metamodel.Customer_;
import org.junit.Test;
import static org.junit.Assert.fail;
/**
* @author Steve Ebersole
*/
public class ManipulationCriteriaTest extends AbstractMetamodelSpecificTest {
@Test
public void basicTest() {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
CriteriaBuilder builder = em.getCriteriaBuilder();
{
CriteriaDelete<Customer> deleteCriteria = builder.createCriteriaDelete( Customer.class );
deleteCriteria.from( Customer.class );
em.createQuery( deleteCriteria ).executeUpdate();
}
{
CriteriaDelete<Customer> deleteCriteria = builder.createCriteriaDelete( Customer.class );
Root<Customer> root = deleteCriteria.from( Customer.class );
deleteCriteria.where(
builder.equal(
root.get( Customer_.name ),
"Acme"
)
);
em.createQuery( deleteCriteria ).executeUpdate();
}
{
CriteriaUpdate<Customer> updateCriteria = builder.createCriteriaUpdate( Customer.class );
updateCriteria.from( Customer.class );
updateCriteria.set( Customer_.name, "Acme" );
em.createQuery( updateCriteria ).executeUpdate();
}
{
CriteriaUpdate<Customer> updateCriteria = builder.createCriteriaUpdate( Customer.class );
Root<Customer> root = updateCriteria.from( Customer.class );
updateCriteria.set( Customer_.name, "Acme" );
updateCriteria.where(
builder.equal(
root.get( Customer_.name ),
"Acme"
)
);
em.createQuery( updateCriteria ).executeUpdate();
}
em.getTransaction().commit();
em.close();
}
@Test
public void testNoAssignments() {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
CriteriaBuilder builder = em.getCriteriaBuilder();
try {
CriteriaUpdate<Customer> updateCriteria = builder.createCriteriaUpdate( Customer.class );
updateCriteria.from( Customer.class );
em.createQuery( updateCriteria ).executeUpdate();
fail( "Expecting failure due to no assignments" );
}
catch (IllegalStateException ise) {
// expected
}
em.getTransaction().commit();
em.close();
}
@Test
public void testJoinsAndFetchesDisallowed() {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
CriteriaBuilder builder = em.getCriteriaBuilder();
{
try {
CriteriaDelete<Customer> deleteCriteria = builder.createCriteriaDelete( Customer.class );
Root<Customer> root = deleteCriteria.from( Customer.class );
root.join( Customer_.spouse );
em.createQuery( deleteCriteria ).executeUpdate();
fail( "Expected failure dues to attempt to join" );
}
catch (IllegalArgumentException expected) {
}
}
{
try {
CriteriaDelete<Customer> deleteCriteria = builder.createCriteriaDelete( Customer.class );
Root<Customer> root = deleteCriteria.from( Customer.class );
root.fetch( Customer_.spouse );
em.createQuery( deleteCriteria ).executeUpdate();
fail( "Expected failure dues to attempt to fetch" );
}
catch (IllegalArgumentException expected) {
}
}
{
try {
CriteriaUpdate<Customer> updateCriteria = builder.createCriteriaUpdate( Customer.class );
Root<Customer> root = updateCriteria.from( Customer.class );
root.join( Customer_.spouse );
em.createQuery( updateCriteria ).executeUpdate();
fail( "Expected failure dues to attempt to join" );
}
catch (IllegalArgumentException expected) {
}
}
{
try {
CriteriaUpdate<Customer> updateCriteria = builder.createCriteriaUpdate( Customer.class );
Root<Customer> root = updateCriteria.from( Customer.class );
root.fetch( Customer_.spouse );
em.createQuery( updateCriteria ).executeUpdate();
fail( "Expected failure dues to attempt to fetch" );
}
catch (IllegalArgumentException expected) {
}
}
em.getTransaction().commit();
em.close();
}
}