下面列出了怎么用org.hibernate.hql.QueryTranslator的API类实例代码及写法,或者点击链接到github查看源代码。
protected void runClassicTranslator(String hql) throws Exception {
SessionFactoryImplementor factory = getSessionFactoryImplementor();
Map replacements = new HashMap();
QueryTranslator oldQueryTranslator = null;
try {
QueryTranslatorFactory classic = new ClassicQueryTranslatorFactory();
oldQueryTranslator = classic.createQueryTranslator( hql, hql, Collections.EMPTY_MAP, factory );
oldQueryTranslator.compile( replacements, false );
}
catch ( Exception e ) {
e.printStackTrace();
throw e;
}
String oldsql = oldQueryTranslator.getSQLString();
System.out.println( "HQL : " + hql );
System.out.println( "OLD SQL: " + oldsql );
}
private static String hqlToSql(String hqlQueryText, SessionFactory sessionFactory) {
if (hqlQueryText != null && hqlQueryText.trim().length() > 0
&& sessionFactory != null) {
final QueryTranslatorFactory translatorFactory = new ASTQueryTranslatorFactory();
final SessionFactoryImplementor factory = (SessionFactoryImplementor) sessionFactory;
final QueryTranslator translator = translatorFactory
.createQueryTranslator(hqlQueryText, hqlQueryText,
Collections.EMPTY_MAP, factory);
translator.compile(Collections.EMPTY_MAP, false);
return translator.getSQLString();
}
return null;
}
/**
* HQL to SQL translator
*/
public static String toSql(String hql) {
if (hql != null && hql.trim().length() > 0) {
final QueryTranslatorFactory qtf = new ASTQueryTranslatorFactory();
final SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactory;
final QueryTranslator translator = qtf.createQueryTranslator(hql, hql, Collections.EMPTY_MAP, sfi);
translator.compile(Collections.EMPTY_MAP, false);
return translator.getSQLString();
}
return null;
}
/**
* @see QueryTranslatorFactory#createQueryTranslator
*/
public QueryTranslator createQueryTranslator(
String queryIdentifier,
String queryString,
Map filters,
SessionFactoryImplementor factory) {
return new QueryTranslatorImpl( queryIdentifier, queryString, filters, factory );
}
public void setFetch(boolean fetch) {
this.fetch = fetch;
// Fetch can't be used with scroll() or iterate().
if ( fetch && getWalker().isShallowQuery() ) {
throw new QueryException( QueryTranslator.ERROR_CANNOT_FETCH_WITH_ITERATE );
}
}
private String resolveToLiteralString(Type type) {
try {
LiteralType literalType = ( LiteralType ) type;
Dialect dialect = factory.getDialect();
return literalType.objectToSQLString( constantValue, dialect );
}
catch ( Throwable t ) {
throw new QueryException( QueryTranslator.ERROR_CANNOT_FORMAT_LITERAL + constantExpression, t );
}
}
/**
* 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 );
}
}
/**
* @see QueryTranslatorFactory#createQueryTranslator
*/
public QueryTranslator createQueryTranslator(
String queryIdentifier,
String queryString,
Map filters,
SessionFactoryImplementor factory) {
return new QueryTranslatorImpl( queryIdentifier, queryString, filters, factory );
}
private void checkColumnNames(QueryTranslator oldQueryTranslator, QueryTranslator newQueryTranslator) {
// Check the column names.
String[][] oldColumnNames = oldQueryTranslator.getColumnNames();
String[][] newColumnNames = newQueryTranslator.getColumnNames();
/*assertEquals( "Column name array is not the right length!", oldColumnNames.length, newColumnNames.length );
for ( int i = 0; i < oldColumnNames.length; i++ ) {
assertEquals( "Column name array [" + i + "] is not the right length!", oldColumnNames[i].length, newColumnNames[i].length );
for ( int j = 0; j < oldColumnNames[i].length; j++ ) {
assertEquals( "Column name [" + i + "," + j + "]", oldColumnNames[i][j], newColumnNames[i][j] );
}
}*/
}
private void checkReturnedTypes(QueryTranslator oldQueryTranslator, QueryTranslator newQueryTranslator) {
// Check the returned types for a regression.
Type[] oldReturnTypes = oldQueryTranslator.getReturnTypes();
Type[] returnTypes = newQueryTranslator.getReturnTypes();
assertEquals( "Return types array is not the right length!", oldReturnTypes.length, returnTypes.length );
for ( int i = 0; i < returnTypes.length; i++ ) {
assertNotNull( returnTypes[i] );
assertNotNull( oldReturnTypes[i] );
assertEquals( "Returned types did not match!", oldReturnTypes[i].getReturnedClass(), returnTypes[i].getReturnedClass() );
System.out.println("returnedType[" + i + "] = " + returnTypes[i] + " oldReturnTypes[" + i + "] = " + oldReturnTypes[i]);
}
}
private void checkQuerySpaces(QueryTranslator oldQueryTranslator, QueryTranslator newQueryTranslator) {
// Check the query spaces for a regression.
Set oldQuerySpaces = oldQueryTranslator.getQuerySpaces();
Set querySpaces = newQueryTranslator.getQuerySpaces();
assertEquals( "Query spaces is not the right size!", oldQuerySpaces.size(), querySpaces.size() );
for ( Iterator iterator = oldQuerySpaces.iterator(); iterator.hasNext(); ) {
Object o = iterator.next();
assertTrue( "New query space does not contain " + o + "!", querySpaces.contains( o ) );
}
}
private void checkSql(QueryTranslator oldQueryTranslator, QueryTranslator newQueryTranslator, String hql, boolean scalar, String sql) {
String oldsql = oldQueryTranslator.getSQLString();
String newsql = newQueryTranslator.getSQLString();
System.out.println( "HQL : " + ASTPrinter.escapeMultibyteChars(hql) );
System.out.println( "OLD SQL: " + ASTPrinter.escapeMultibyteChars(oldsql) );
System.out.println( "NEW SQL: " + ASTPrinter.escapeMultibyteChars(newsql) );
if ( sql == null ) {
// Check the generated SQL. ASTPrinter.escapeMultibyteChars(
assertSQLEquals( "SQL is not the same as the old SQL (scalar=" + scalar + ")", oldsql, newsql );
}
else {
assertSQLEquals( "SQL is not the same as the expected SQL (scalar=" + scalar + ")", sql, newsql );
}
}
private void assertEjbqlEqualsHql(String ejbql, String hql) {
QueryTranslatorFactory ast = new ASTQueryTranslatorFactory();
QueryTranslator queryTranslator = ast.createQueryTranslator( hql, hql, Collections.EMPTY_MAP, sfi() );
queryTranslator.compile( Collections.EMPTY_MAP, true );
String hqlSql = queryTranslator.getSQLString();
queryTranslator = ast.createQueryTranslator( ejbql, ejbql, Collections.EMPTY_MAP, sfi() );
queryTranslator.compile( Collections.EMPTY_MAP, true );
String ejbqlSql = queryTranslator.getSQLString();
assertEquals( hqlSql, ejbqlSql );
}
private QueryTranslatorImpl compile(String input) {
QueryTranslatorFactory ast = new ASTQueryTranslatorFactory();
QueryTranslator queryTranslator = ast.createQueryTranslator( input, input, Collections.EMPTY_MAP, sfi() );
queryTranslator.compile( Collections.EMPTY_MAP, true );
return ( QueryTranslatorImpl ) queryTranslator;
}
private void compileWithAstQueryTranslator(String hql, boolean scalar) {
Map replacements = new HashMap();
QueryTranslatorFactory ast = new ASTQueryTranslatorFactory();
SessionFactoryImplementor factory = getSessionFactoryImplementor();
QueryTranslator newQueryTranslator = ast.createQueryTranslator( hql, hql, Collections.EMPTY_MAP, factory );
newQueryTranslator.compile( replacements, scalar );
}
protected HQLQueryPlan(String hql, String collectionRole, boolean shallow, Map enabledFilters, SessionFactoryImplementor factory) {
this.sourceQuery = hql;
this.shallow = shallow;
Set copy = new HashSet();
copy.addAll( enabledFilters.keySet() );
this.enabledFilterNames = java.util.Collections.unmodifiableSet( copy );
Set combinedQuerySpaces = new HashSet();
String[] concreteQueryStrings = QuerySplitter.concreteQueries( hql, factory );
final int length = concreteQueryStrings.length;
translators = new QueryTranslator[length];
List sqlStringList = new ArrayList();
for ( int i=0; i<length; i++ ) {
if ( collectionRole == null ) {
translators[i] = factory.getSettings()
.getQueryTranslatorFactory()
.createQueryTranslator( hql, concreteQueryStrings[i], enabledFilters, factory );
translators[i].compile( factory.getSettings().getQuerySubstitutions(), shallow );
}
else {
translators[i] = factory.getSettings()
.getQueryTranslatorFactory()
.createFilterTranslator( hql, concreteQueryStrings[i], enabledFilters, factory );
( ( FilterTranslator ) translators[i] ).compile( collectionRole, factory.getSettings().getQuerySubstitutions(), shallow );
}
combinedQuerySpaces.addAll( translators[i].getQuerySpaces() );
sqlStringList.addAll( translators[i].collectSqlStrings() );
}
this.sqlStrings = ArrayHelper.toStringArray( sqlStringList );
this.querySpaces = combinedQuerySpaces;
if ( length == 0 ) {
parameterMetadata = new ParameterMetadata( null, null );
returnMetadata = null;
}
else {
this.parameterMetadata = buildParameterMetadata( translators[0].getParameterTranslations(), hql );
if ( translators[0].isManipulationStatement() ) {
returnMetadata = null;
}
else {
if ( length > 1 ) {
final int returns = translators[0].getReturnTypes().length;
returnMetadata = new ReturnMetadata( translators[0].getReturnAliases(), new Type[returns] );
}
else {
returnMetadata = new ReturnMetadata( translators[0].getReturnAliases(), translators[0].getReturnTypes() );
}
}
}
}
public QueryTranslator[] getTranslators() {
QueryTranslator[] copy = new QueryTranslator[translators.length];
System.arraycopy(translators, 0, copy, 0, copy.length);
return copy;
}
private void setConstantValue(DotNode node, String text, Object value) {
if ( log.isDebugEnabled() ) {
log.debug( "setConstantValue() " + text + " -> " + value + " " + value.getClass().getName() );
}
node.setFirstChild( null ); // Chop off the rest of the tree.
if ( value instanceof String ) {
node.setType( SqlTokenTypes.QUOTED_STRING );
}
else if ( value instanceof Character ) {
node.setType( SqlTokenTypes.QUOTED_STRING );
}
else if ( value instanceof Byte ) {
node.setType( SqlTokenTypes.NUM_INT );
}
else if ( value instanceof Short ) {
node.setType( SqlTokenTypes.NUM_INT );
}
else if ( value instanceof Integer ) {
node.setType( SqlTokenTypes.NUM_INT );
}
else if ( value instanceof Long ) {
node.setType( SqlTokenTypes.NUM_LONG );
}
else if ( value instanceof Double ) {
node.setType( SqlTokenTypes.NUM_DOUBLE );
}
else if ( value instanceof Float ) {
node.setType( SqlTokenTypes.NUM_FLOAT );
}
else {
node.setType( SqlTokenTypes.CONSTANT );
}
Type type;
try {
type = TypeFactory.heuristicType( value.getClass().getName() );
}
catch ( MappingException me ) {
throw new QueryException( me );
}
if ( type == null ) {
throw new QueryException( QueryTranslator.ERROR_CANNOT_DETERMINE_TYPE + node.getText() );
}
try {
LiteralType literalType = ( LiteralType ) type;
Dialect dialect = walker.getSessionFactoryHelper().getFactory().getDialect();
node.setText( literalType.objectToSQLString( value, dialect ) );
}
catch ( Exception e ) {
throw new QueryException( QueryTranslator.ERROR_CANNOT_FORMAT_LITERAL + node.getText(), e );
}
node.setDataType( type );
node.setResolvedConstant( text );
}
private void doToken(String token, QueryTranslatorImpl q) throws QueryException {
if ( q.isName( StringHelper.root( token ) ) ) { //path expression
doPathExpression( q.unalias( token ), q );
}
else if ( token.startsWith( ParserHelper.HQL_VARIABLE_PREFIX ) ) { //named query parameter
q.addNamedParameter( token.substring( 1 ) );
appendToken( q, "?" );
}
else {
Queryable persister = q.getEntityPersisterUsingImports( token );
if ( persister != null ) { // the name of a class
final String discrim = persister.getDiscriminatorSQLValue();
if ( InFragment.NULL.equals(discrim) || InFragment.NOT_NULL.equals(discrim) ) {
throw new QueryException( "subclass test not allowed for null or not null discriminator" );
}
else {
appendToken( q, discrim );
}
}
else {
Object constant;
if (
token.indexOf( '.' ) > -1 &&
( constant = ReflectHelper.getConstantValue( token ) ) != null
) {
Type type;
try {
type = TypeFactory.heuristicType( constant.getClass().getName() );
}
catch ( MappingException me ) {
throw new QueryException( me );
}
if ( type == null ) throw new QueryException( QueryTranslator.ERROR_CANNOT_DETERMINE_TYPE + token );
try {
appendToken( q, ( ( LiteralType ) type ).objectToSQLString( constant, q.getFactory().getDialect() ) );
}
catch ( Exception e ) {
throw new QueryException( QueryTranslator.ERROR_CANNOT_FORMAT_LITERAL + token, e );
}
}
else { //anything else
String negatedToken = negated ? ( String ) NEGATIONS.get( token.toLowerCase() ) : null;
if ( negatedToken != null && ( !betweenSpecialCase || !"or".equals( negatedToken ) ) ) {
appendToken( q, negatedToken );
}
else {
appendToken( q, token );
}
}
}
}
}
private String toSql(String hql) {
QueryTranslatorFactory ast = new ASTQueryTranslatorFactory();
QueryTranslator queryTranslator = ast.createQueryTranslator( hql, hql, Collections.EMPTY_MAP, sfi() );
queryTranslator.compile( Collections.EMPTY_MAP, true );
return queryTranslator.getSQLString();
}
public void testHQLAggregationReturnType() {
// EJB3: COUNT returns Long
QueryTranslatorImpl translator = createNewQueryTranslator( "select count(*) from Human h" );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.LONG, translator.getReturnTypes()[0] );
translator = createNewQueryTranslator( "select count(h.height) from Human h" );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.LONG, translator.getReturnTypes()[0] );
// MAX, MIN return the type of the state-field to which they are applied.
translator = createNewQueryTranslator( "select max(h.height) from Human h" );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.DOUBLE, translator.getReturnTypes()[0] );
translator = createNewQueryTranslator( "select max(h.id) from Human h" );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.LONG, translator.getReturnTypes()[0] );
// AVG returns Double.
translator = createNewQueryTranslator( "select avg(h.height) from Human h" );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.DOUBLE, translator.getReturnTypes()[0] );
translator = createNewQueryTranslator( "select avg(h.id) from Human h" );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.DOUBLE, translator.getReturnTypes()[0] );
translator = createNewQueryTranslator( "select avg(h.bigIntegerValue) from Human h" );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.DOUBLE, translator.getReturnTypes()[0] );
// SUM returns Long when applied to state-fields of integral types (other than BigInteger);
translator = createNewQueryTranslator( "select sum(h.id) from Human h" );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.LONG, translator.getReturnTypes()[0] );
translator = createNewQueryTranslator( "select sum(h.intValue) from Human h" );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.LONG, translator.getReturnTypes()[0] );
// SUM returns Double when applied to state-fields of floating point types;
translator = createNewQueryTranslator( "select sum(h.height) from Human h" );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.DOUBLE, translator.getReturnTypes()[0] );
translator = createNewQueryTranslator( "select sum(h.floatValue) from Human h" );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.DOUBLE, translator.getReturnTypes()[0] );
// SUM returns BigInteger when applied to state-fields of type BigInteger
translator = createNewQueryTranslator( "select sum(h.bigIntegerValue) from Human h" );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.BIG_INTEGER, translator.getReturnTypes()[0] );
// SUM and BigDecimal when applied to state-fields of type BigDecimal.
translator = createNewQueryTranslator( "select sum(h.bigDecimalValue) from Human h" );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.BIG_DECIMAL, translator.getReturnTypes()[0] );
// special case to test classicquery special case handling of count(*)
QueryTranslator oldQueryTranslator = null;
String hql = "select count(*) from Human h";
QueryTranslatorFactory classic = new ClassicQueryTranslatorFactory();
oldQueryTranslator = classic.createQueryTranslator( hql, hql, Collections.EMPTY_MAP, getSessionFactoryImplementor() );
oldQueryTranslator.compile( Collections.EMPTY_MAP, true);
assertEquals( "incorrect return type count", 1, oldQueryTranslator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.LONG, oldQueryTranslator.getReturnTypes()[0] );
}
public void testClassicHQLAggregationReturnTypes() {
// EJB3: COUNT returns Long
QueryTranslatorImpl translator = createNewQueryTranslator( "select count(*) from Human h", sfi() );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.INTEGER, translator.getReturnTypes()[0] );
translator = createNewQueryTranslator( "select count(h.height) from Human h", sfi() );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.INTEGER, translator.getReturnTypes()[0] );
// MAX, MIN return the type of the state-field to which they are applied.
translator = createNewQueryTranslator( "select max(h.height) from Human h", sfi() );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.DOUBLE, translator.getReturnTypes()[0] );
translator = createNewQueryTranslator( "select max(h.id) from Human h", sfi() );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.LONG, translator.getReturnTypes()[0] );
// AVG returns Float integrals, and otherwise the field type.
translator = createNewQueryTranslator( "select avg(h.height) from Human h", sfi() );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.DOUBLE, translator.getReturnTypes()[0] );
translator = createNewQueryTranslator( "select avg(h.id) from Human h", sfi() );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.FLOAT, translator.getReturnTypes()[0] );
translator = createNewQueryTranslator( "select avg(h.bigIntegerValue) from Human h", sfi() );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.BIG_INTEGER, translator.getReturnTypes()[0] );
// SUM returns underlying type sum
translator = createNewQueryTranslator( "select sum(h.id) from Human h", sfi() );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.LONG, translator.getReturnTypes()[0] );
translator = createNewQueryTranslator( "select sum(h.intValue) from Human h", sfi() );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.INTEGER, translator.getReturnTypes()[0] );
translator = createNewQueryTranslator( "select sum(h.height) from Human h", sfi() );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.DOUBLE, translator.getReturnTypes()[0] );
translator = createNewQueryTranslator( "select sum(h.floatValue) from Human h", sfi() );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.FLOAT, translator.getReturnTypes()[0] );
translator = createNewQueryTranslator( "select sum(h.bigIntegerValue) from Human h", sfi() );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.BIG_INTEGER, translator.getReturnTypes()[0] );
translator = createNewQueryTranslator( "select sum(h.bigDecimalValue) from Human h", sfi() );
assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.BIG_DECIMAL, translator.getReturnTypes()[0] );
// special case to test classicquery special case handling of count(*)
QueryTranslator oldQueryTranslator = null;
String hql = "select count(*) from Human h";
QueryTranslatorFactory classic = new ClassicQueryTranslatorFactory();
oldQueryTranslator = classic.createQueryTranslator( hql, hql, Collections.EMPTY_MAP, sfi() );
oldQueryTranslator.compile( Collections.EMPTY_MAP, true);
assertEquals( "incorrect return type count", 1, oldQueryTranslator.getReturnTypes().length );
assertEquals( "incorrect return type", Hibernate.INTEGER, oldQueryTranslator.getReturnTypes()[0] );
}