下面列出了怎么用org.hibernate.QueryException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Compile a filter. This method may be called multiple
* times. Subsequent invocations are no-ops.
*/
public synchronized void compile(
String collectionRole,
Map replacements,
boolean scalar) throws QueryException, MappingException {
if ( !isCompiled() ) {
addFromAssociation( "this", collectionRole );
paramValueBinders.add(
new CollectionFilterKeyParameterSpecification(
collectionRole,
getFactory().getMetamodel().collectionPersister( collectionRole ).getKeyType()
)
);
compile( replacements, scalar );
}
}
@Override
public String[] toColumns(String alias, String propertyName) throws QueryException {
validate( propertyName );
final String joinTableAlias = joinSequence.getFirstJoin().getAlias();
if ( CollectionPropertyNames.COLLECTION_INDEX.equals( propertyName ) ) {
return queryableCollection.toColumns( joinTableAlias, propertyName );
}
final String[] cols = queryableCollection.getIndexColumnNames( joinTableAlias );
if ( CollectionPropertyNames.COLLECTION_MIN_INDEX.equals( propertyName ) ) {
if ( cols.length != 1 ) {
throw new QueryException( "composite collection index in minIndex()" );
}
return new String[] {"min(" + cols[0] + ')'};
}
else {
if ( cols.length != 1 ) {
throw new QueryException( "composite collection index in maxIndex()" );
}
return new String[] {"max(" + cols[0] + ')'};
}
}
public String[] toColumns(String alias, String propertyName) throws QueryException {
if ( ENTITY_CLASS.equals(propertyName) ) {
// This doesn't actually seem to work but it *might*
// work on some dbs. Also it doesn't work if there
// are multiple columns of results because it
// is not accounting for the suffix:
// return new String[] { getDiscriminatorColumnName() };
return new String[] { discriminatorFragment(alias).toFragmentString() };
}
else {
return super.toColumns(alias, propertyName);
}
}
private void createAssociationPathCriteriaMap() {
final Iterator<CriteriaImpl.Subcriteria> iter = rootCriteria.iterateSubcriteria();
while ( iter.hasNext() ) {
CriteriaImpl.Subcriteria crit = iter.next();
String wholeAssociationPath = getWholeAssociationPath( crit );
Object old = associationPathCriteriaMap.put( wholeAssociationPath, crit );
if ( old != null ) {
throw new QueryException( "duplicate association path: " + wholeAssociationPath );
}
JoinType joinType = crit.getJoinType();
old = associationPathJoinTypesMap.put( wholeAssociationPath, joinType );
if ( old != null ) {
// TODO : not so sure this is needed...
throw new QueryException( "duplicate association path: " + wholeAssociationPath );
}
if ( crit.getWithClause() != null ) {
this.withClauseMap.put( wholeAssociationPath, crit.getWithClause() );
}
}
}
@SuppressWarnings("unchecked")
@Override
protected List getResultList(List results, ResultTransformer resultTransformer) throws QueryException {
// meant to handle dynamic instantiation queries...
HolderInstantiator holderInstantiator = buildHolderInstantiator( resultTransformer );
if ( holderInstantiator.isRequired() ) {
for ( int i = 0; i < results.size(); i++ ) {
Object[] row = (Object[]) results.get( i );
Object result = holderInstantiator.instantiate( row );
results.set( i, result );
}
if ( !hasSelectNew() && resultTransformer != null ) {
return resultTransformer.transformList( results );
}
else {
return results;
}
}
else {
return results;
}
}
public void validateTypes(SelectClause selectClause) throws QueryException {
Type[] selectTypes = selectClause.getQueryReturnTypes();
if ( selectTypes.length != types.length ) {
throw new QueryException( "number of select types did not match those for insert" );
}
for ( int i = 0; i < types.length; i++ ) {
if ( !areCompatible( types[i], selectTypes[i] ) ) {
throw new QueryException(
"insertion type [" + types[i] + "] and selection type [" +
selectTypes[i] + "] at position " + i + " are not compatible"
);
}
}
// otherwise, everything ok.
}
protected List getResultList(List results, ResultTransformer resultTransformer) throws QueryException {
// meant to handle dynamic instantiation queries...
HolderInstantiator holderInstantiator = HolderInstantiator.getHolderInstantiator(selectNewTransformer, resultTransformer, queryReturnAliases);
if ( holderInstantiator.isRequired() ) {
for ( int i = 0; i < results.size(); i++ ) {
Object[] row = ( Object[] ) results.get( i );
Object result = holderInstantiator.instantiate(row);
results.set( i, result );
}
if(!hasSelectNew() && resultTransformer!=null) {
return resultTransformer.transformList(results);
} else {
return results;
}
} else {
return results;
}
}
private void generate(AST sqlAst) throws QueryException, RecognitionException {
if ( sql == null ) {
final SqlGenerator gen = new SqlGenerator( factory );
gen.statement( sqlAst );
sql = gen.getSQL();
if ( LOG.isDebugEnabled() ) {
LOG.debugf( "HQL: %s", hql );
LOG.debugf( "SQL: %s", sql );
}
gen.getParseErrorHandler().throwQueryException();
if ( collectedParameterSpecifications == null ) {
collectedParameterSpecifications = gen.getCollectedParameters();
}
else {
collectedParameterSpecifications.addAll( gen.getCollectedParameters() );
}
}
}
protected List getResultList(List results, ResultTransformer resultTransformer) throws QueryException {
// meant to handle dynamic instantiation queries...(Copy from QueryLoader)
HolderInstantiator holderInstantiator = HolderInstantiator.getHolderInstantiator(
null,
resultTransformer,
getReturnAliasesForTransformer()
);
if ( holderInstantiator.isRequired() ) {
for ( int i = 0; i < results.size(); i++ ) {
Object[] row = ( Object[] ) results.get( i );
Object result = holderInstantiator.instantiate(row);
results.set( i, result );
}
return resultTransformer.transformList(results);
}
else {
return results;
}
}
private String getElementName(PathExpressionParser.CollectionElement element, QueryTranslatorImpl q) throws QueryException {
String name;
if ( element.isOneToMany ) {
name = element.alias;
}
else {
Type type = element.elementType;
if ( type.isEntityType() ) { //ie. a many-to-many
String entityName = ( ( EntityType ) type ).getAssociatedEntityName();
name = pathExpressionParser.continueFromManyToMany( entityName, element.elementColumns, q );
}
else {
throw new QueryException( "illegally dereferenced collection element" );
}
}
return name;
}
@Override
public String[] toColumns(String propertyName) throws QueryException {
if ( "index".equals( propertyName ) ) {
if ( indexFragments == null ) {
String[] tmp = new String[indexColumnNames.length];
for ( int i = 0; i < indexColumnNames.length; i++ ) {
tmp[i] = indexColumnNames[i] == null
? indexFormulas[i]
: indexColumnNames[i];
indexFragments = tmp;
}
}
return indexFragments;
}
return elementPropertyMapping.toColumns( propertyName );
}
/**
* Coordinates the efforts to perform a scroll across all the included query translators.
*
* @param queryParameters The query parameters
* @param session The session
*
* @return The query result iterator
*
* @throws HibernateException Indicates a problem performing the query
*/
public ScrollableResultsImplementor performScroll(
QueryParameters queryParameters,
SharedSessionContractImplementor session) throws HibernateException {
if ( traceEnabled ) {
LOG.tracev( "Iterate: {0}", getSourceQuery() );
queryParameters.traceParameters( session.getFactory() );
}
if ( translators.length != 1 ) {
throw new QueryException( "implicit polymorphism not supported for scroll() queries" );
}
if ( queryParameters.getRowSelection().definesLimits() && translators[0].containsCollectionFetches() ) {
throw new QueryException( "firstResult/maxResults not supported in conjunction with scroll() of a query containing collection fetches" );
}
return translators[0].scroll( queryParameters, session );
}
public String[] toColumns(String alias, String propertyName) throws QueryException {
//TODO: *two* hashmap lookups here is one too many...
String[] columns = (String[]) columnsByPropertyPath.get(propertyName);
if ( columns == null ) {
throw propertyException( propertyName );
}
String[] templates = (String[]) formulaTemplatesByPropertyPath.get(propertyName);
String[] result = new String[columns.length];
for ( int i=0; i<columns.length; i++ ) {
if ( columns[i]==null ) {
result[i] = StringHelper.replace( templates[i], Template.TEMPLATE, alias );
}
else {
result[i] = StringHelper.qualify( alias, columns[i] );
}
}
return result;
}
protected boolean isNonQualifiedPropertyRef(AST ident) {
final String identText = ident.getText();
if ( currentFromClause.isFromElementAlias( identText ) ) {
return false;
}
List fromElements = currentFromClause.getExplicitFromElements();
if ( fromElements.size() == 1 ) {
final FromElement fromElement = ( FromElement ) fromElements.get( 0 );
try {
log.trace( "attempting to resolve property [" + identText + "] as a non-qualified ref" );
return fromElement.getPropertyMapping( identText ).toType( identText ) != null;
}
catch( QueryException e ) {
// Should mean that no such property was found
}
}
return false;
}
@Override
public String render(Type columnType, List args, SessionFactoryImplementor factory) throws QueryException {
final boolean threeArgs = args.size() > 2;
final Object pattern = args.get( 0 );
final Object string = args.get( 1 );
final Object start = threeArgs ? args.get( 2 ) : null;
final StringBuilder buf = new StringBuilder();
buf.append( "charindex(" ).append( pattern ).append( ", " );
if (threeArgs) {
buf.append( "right(" );
}
buf.append( string );
if (threeArgs) {
buf.append( ", char_length(" ).append( string ).append( ")-(" ).append( start ).append( "-1))" );
}
buf.append( ')' );
return buf.toString();
}
void addFromClass(String name, Queryable classPersister)
throws QueryException {
JoinSequence joinSequence = new JoinSequence( getFactory() )
.setRoot( classPersister, name );
//crossJoins.add(name);
addFrom( name, classPersister.getEntityName(), joinSequence );
}
public void end(QueryTranslatorImpl q) throws QueryException {
if ( lastToken != null ) {
parser.token( lastToken, q );
}
parser.end( q );
lastToken = null;
currentCollectionProp = null;
}
@Override
public String render(Type type, List args, SessionFactoryImplementor factory) throws QueryException {
if (args == null || args.size() != 3) {
throw new IllegalArgumentException("The function must be passed 2 arguments");
}
String language = (String) args.get(0);
String field = (String) args.get(1);
String searchString = (String) args.get(2);
return field + " @@ to_tsquery('" + language + "', " + searchString + ")";
}
public Type toType(String propertyName) throws QueryException {
if ( propertyName.equals(CollectionPropertyNames.COLLECTION_ELEMENTS) ) {
return memberPersister.getElementType();
}
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_INDICES) ) {
if ( !memberPersister.hasIndex() ) throw new QueryException("unindexed collection before indices()");
return memberPersister.getIndexType();
}
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_SIZE) ) {
return Hibernate.INTEGER;
}
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MAX_INDEX) ) {
return memberPersister.getIndexType();
}
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MIN_INDEX) ) {
return memberPersister.getIndexType();
}
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MAX_ELEMENT) ) {
return memberPersister.getElementType();
}
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MIN_ELEMENT) ) {
return memberPersister.getElementType();
}
else {
//return memberPersister.getPropertyType(propertyName);
throw new QueryException("illegal syntax near collection: " + propertyName);
}
}
public String[] toColumns(String alias, String propertyName)
throws QueryException {
if ( "index".equals( propertyName ) ) {
if ( isManyToMany() ) {
throw new QueryException( "index() function not supported for many-to-many association" );
}
return StringHelper.qualify( alias, indexColumnNames );
}
return elementPropertyMapping.toColumns( alias, propertyName );
}
private void prepareForIndex(QueryTranslatorImpl q) throws QueryException {
QueryableCollection collPersister = q.getCollectionPersister( collectionRole );
if ( !collPersister.hasIndex() ) {
throw new QueryException( "unindexed collection before []: " + path );
}
String[] indexCols = collPersister.getIndexColumnNames();
if ( indexCols.length != 1 ) {
throw new QueryException( "composite-index appears in []: " + path );
}
//String[] keyCols = collPersister.getKeyColumnNames();
JoinSequence fromJoins = new JoinSequence( q.getFactory() )
.setUseThetaStyle( useThetaStyleJoin )
.setRoot( collPersister, collectionName )
.setNext( joinSequence.copy() );
if ( !continuation ) {
addJoin( collectionName, collPersister.getCollectionType() );
}
joinSequence.addCondition( collectionName + '.' + indexCols[0] + " = " ); //TODO: get SQL rendering out of here
CollectionElement elem = new CollectionElement();
elem.elementColumns = collPersister.getElementColumnNames(collectionName);
elem.elementType = collPersister.getElementType();
elem.isOneToMany = collPersister.isOneToMany();
elem.alias = collectionName;
elem.joinSequence = joinSequence;
collectionElements.addLast( elem );
setExpectingCollectionIndex();
q.addCollection( collectionName, collectionRole );
q.addFromJoinOnly( collectionName, fromJoins );
}
/**
* Returns the locations of all occurrences of the named parameter.
*/
public int[] getNamedParameterLocations(String name) throws QueryException {
Object o = namedParameters.get( name );
if ( o == null ) {
QueryException qe = new QueryException( QueryTranslator.ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name );
qe.setQueryString( queryTranslatorImpl.getQueryString() );
throw qe;
}
if ( o instanceof Integer ) {
return new int[]{( ( Integer ) o ).intValue()};
}
else {
return ArrayHelper.toIntArray( ( ArrayList ) o );
}
}
/**
* Determine the name of the property for the entity encapsulated by the
* given type which represents the id or unique-key.
*
* @param entityType The type representing the entity.
* @return The corresponding property name
* @throws QueryException Indicates such a property could not be found.
*/
public String getIdentifierOrUniqueKeyPropertyName(EntityType entityType) {
try {
return entityType.getIdentifierOrUniqueKeyPropertyName( sfi );
}
catch ( MappingException me ) {
throw new QueryException( me );
}
}
private void endChild(QueryTranslatorImpl q) throws QueryException {
if ( child == null ) {
//null child could occur for no from clause in a filter
cacheSelectTokens = false;
}
else {
child.end( q );
}
}
public void testInsertIntoSuperclassPropertiesFails() {
TestData data = new TestData();
data.prepare();
Session s = openSession();
Transaction t = s.beginTransaction();
try {
s.createQuery( "insert into Human (id, bodyWeight) select id, bodyWeight from Lizard" ).executeUpdate();
fail( "superclass prop insertion did not error" );
}
catch( QueryException e ) {
// expected result
}
t.commit();
t = s.beginTransaction();
s.createQuery( "delete Animal where mother is not null" ).executeUpdate();
s.createQuery( "delete Animal where father is not null" ).executeUpdate();
s.createQuery( "delete Animal" ).executeUpdate();
t.commit();
s.close();
data.cleanup();
}
public String getRenderText(SessionFactoryImplementor sessionFactory) {
try {
return getTypeInternal().objectToSQLString( getValue(), sessionFactory.getDialect() );
}
catch( Throwable t ) {
throw new QueryException( "Unable to render boolean literal value", t );
}
}
public void testFetchInSubqueryFails() {
Session s = openSession();
try {
s.createQuery( "from Animal a where a.mother in (select m from Animal a1 inner join a1.mother as m join fetch m.mother)" ).list();
fail( "fetch join allowed in subquery" );
}
catch( QueryException expected ) {
// expected behavior
}
s.close();
}
public void end(QueryTranslatorImpl q) throws QueryException {
if ( expectingPathContinuation ) {
expectingPathContinuation = false;
PathExpressionParser.CollectionElement element = pathExpressionParser.lastCollectionElement();
if ( element.elementColumns.length != 1 ) {
throw new QueryException( "path expression ended in composite collection element" );
}
appendToken( q, element.elementColumns[0] );
addToCurrentJoin( element );
}
token( ")", q );
}
protected void prepareTest() throws Exception {
super.prepareTest();
SelectClause.VERSION2_SQL = true;
DotNode.REGRESSION_STYLE_JOIN_SUPPRESSION = true;
DotNode.ILLEGAL_COLL_DEREF_EXCP_BUILDER = new DotNode.IllegalCollectionDereferenceExceptionBuilder() {
public QueryException buildIllegalCollectionDereferenceException(String propertyName, FromReferenceNode lhs) {
throw new QueryException( "illegal syntax near collection: " + propertyName );
}
};
}
@Override
public String render(Type firstArgumentType, List args, SessionFactoryImplementor factory) throws QueryException {
if ( args.size() != 2 && args.size() != 3 ) {
throw new QueryException( "convert() requires two or three arguments" );
}
final String type = (String) args.get( 1 );
if ( args.size() == 2 ) {
return "{fn convert(" + args.get( 0 ) + " , " + type + ")}";
}
else {
return "convert(" + args.get( 0 ) + " , " + type + "," + args.get( 2 ) + ")";
}
}