HHH-4862 - quoted column/alias names not properly handled in org.hibernate.loader.EntityAliases

git-svn-id: https://svn.jboss.org/repos/hibernate/core/trunk@18665 1b8cb986-b30d-0410-93ca-fae66ebed9b2
This commit is contained in:
Steve Ebersole 2010-01-28 22:04:20 +00:00
parent 4ac6062cf1
commit b52cdc9523
10 changed files with 444 additions and 66 deletions

View File

@ -24,6 +24,8 @@
package org.hibernate.test.annotations.quote.resultsetmappings;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.test.annotations.TestCase;
/**
@ -32,29 +34,58 @@ import org.hibernate.test.annotations.TestCase;
* @author Steve Ebersole
*/
public class ExplicitSqlResultSetMappingTest extends TestCase {
private String queryString = "select t.\"NAME\" as \"QuotEd_nAMe\" from \"MY_ENTITY_TABLE_NAME\" t";
private String queryString = "select t.\"NAME\" as \"QuotEd_nAMe\" from \"MY_ENTITY_TABLE\" t";
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] { MyEntity.class };
}
public void testCompleteAutoDiscovery() {
Session s = openSession();
@Override
protected void configure(Configuration cfg) {
cfg.setProperty( Environment.GLOBALLY_QUOTED_IDENTIFIERS, "true" );
}
private void prepareTestData() {
Session s = sfi().openSession();
s.beginTransaction();
s.createSQLQuery( queryString )
.list();
s.save( new MyEntity( "mine" ) );
s.getTransaction().commit();
s.close();
}
public void testPartialAutoDiscovery() {
Session s = openSession();
private void cleanupTestData() {
Session s = sfi().openSession();
s.beginTransaction();
s.createSQLQuery( queryString )
.setResultSetMapping( "explicitResultSetMapping" )
.list();
s.createQuery( "delete MyEntity" ).executeUpdate();
s.getTransaction().commit();
s.close();
}
public void testCompleteScalarAutoDiscovery() {
prepareTestData();
Session s = openSession();
s.beginTransaction();
s.createSQLQuery( queryString )
.list();
s.getTransaction().commit();
s.close();
cleanupTestData();
}
public void testPartialScalarAutoDiscovery() {
prepareTestData();
Session s = openSession();
s.beginTransaction();
s.createSQLQuery( queryString )
.setResultSetMapping( "explicitScalarResultSetMapping" )
.list();
s.getTransaction().commit();
s.close();
cleanupTestData();
}
}

View File

@ -26,9 +26,12 @@ package org.hibernate.test.annotations.quote.resultsetmappings;
import javax.persistence.Column;
import javax.persistence.ColumnResult;
import javax.persistence.Entity;
import javax.persistence.EntityResult;
import javax.persistence.FieldResult;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SqlResultSetMapping;
import javax.persistence.SqlResultSetMappings;
import javax.persistence.Table;
/**
@ -36,16 +39,41 @@ import javax.persistence.Table;
*
* @author Steve Ebersole
*/
@SqlResultSetMapping(
name="explicitResultSetMapping",
columns={ @ColumnResult(name="`QuotEd_nAMe`") }
)
@SqlResultSetMappings({
@SqlResultSetMapping(
name="explicitScalarResultSetMapping",
columns={ @ColumnResult(name="QuotEd_nAMe") }
)
,
@SqlResultSetMapping(
name="basicEntityResultSetMapping",
entities = @EntityResult( entityClass = MyEntity.class )
)
,
@SqlResultSetMapping(
name="expandedEntityResultSetMapping",
entities = @EntityResult(
entityClass = MyEntity.class,
fields = {
@FieldResult( name = "id", column = "eId" ),
@FieldResult( name = "name", column = "eName" )
}
)
)
})
@Entity
@Table( name = "MY_ENTITY_TABLE_NAME" )
@Table( name = "MY_ENTITY_TABLE" )
public class MyEntity {
private Long id;
private String name;
public MyEntity() {
}
public MyEntity(String name) {
this.name = name;
}
@Id
@GeneratedValue
public Long getId() {

View File

@ -96,9 +96,12 @@ public class SQLQueryImpl extends AbstractQueryImpl implements SQLQuery {
}
this.queryReturns = Arrays.asList( definition.getQueryReturns() );
}
else {
else if ( queryDef.getQueryReturns() != null && queryDef.getQueryReturns().length > 0 ) {
this.queryReturns = Arrays.asList( queryDef.getQueryReturns() );
}
else {
this.queryReturns = new ArrayList();
}
this.querySpaces = queryDef.getQuerySpaces();
this.callable = queryDef.isCallable();

View File

@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* Copyright (c) 2010, 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 Middleware LLC.
* 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
@ -20,24 +20,29 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.loader;
import java.util.Map;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.persister.entity.Loadable;
/**
* EntityAliases that chooses the column names over the alias names.
* EntityAliases that chooses the column names over the alias names. This strategy is used
* when the result-set mapping did not give specific aliases to use in extracting from the
* result set. We use the column names from the underlying persister.
*
* @author max
*
* @author Steve Ebersole
*/
public class ColumnEntityAliases extends DefaultEntityAliases {
public ColumnEntityAliases(Map returnProperties, Loadable persister, String suffix) {
super(returnProperties, persister, suffix);
public ColumnEntityAliases(
Map returnProperties,
Loadable persister,
String suffix) {
super( returnProperties, persister, suffix );
}
protected String[] getIdentifierAliases(Loadable persister, String suffix) {
@ -51,6 +56,4 @@ public class ColumnEntityAliases extends DefaultEntityAliases {
protected String[] getPropertyAliases(Loadable persister, int j) {
return persister.getPropertyColumnNames(j);
}
}

View File

@ -28,6 +28,7 @@ import java.util.Map;
import org.hibernate.persister.entity.Loadable;
import org.hibernate.util.CollectionHelper;
import org.hibernate.util.StringHelper;
/**
* EntityAliases which handles the logic of selecting user provided aliases (via return-property),
@ -46,47 +47,63 @@ public class DefaultEntityAliases implements EntityAliases {
private final String rowIdAlias;
private final Map userProvidedAliases;
public DefaultEntityAliases(Loadable persister, String suffix) {
this(CollectionHelper.EMPTY_MAP, persister, suffix);
}
/**
* Calculate and cache select-clause suffixes.
* @param map
* Calculate and cache select-clause aliases
*
* @param userProvidedAliases The explicit aliases provided in a result-set mapping.
* @param persister The persister for which we are generating select aliases
* @param suffix The calculated suffix.
*/
public DefaultEntityAliases(Map userProvidedAliases, Loadable persister, String suffix) {
public DefaultEntityAliases(
Map userProvidedAliases,
Loadable persister,
String suffix) {
this.suffix = suffix;
this.userProvidedAliases = userProvidedAliases;
String[] keyColumnsCandidates = getUserProvidedAliases(
persister.getIdentifierPropertyName(),
(String[]) null
);
if (keyColumnsCandidates==null) {
suffixedKeyColumns = getUserProvidedAliases(
"id",
getIdentifierAliases(persister, suffix)
);
}
else {
suffixedKeyColumns = keyColumnsCandidates;
}
intern(suffixedKeyColumns);
suffixedPropertyColumns = getSuffixedPropertyAliases(persister);
suffixedDiscriminatorColumn = getUserProvidedAlias(
"class",
getDiscriminatorAlias(persister, suffix)
);
if ( persister.isVersioned() ) {
suffixedVersionColumn = suffixedPropertyColumns[ persister.getVersionProperty() ];
}
else {
suffixedVersionColumn = null;
}
suffixedKeyColumns = determineKeyAlias( persister, suffix );
suffixedPropertyColumns = determinePropertyAliases( persister );
suffixedDiscriminatorColumn = determineDiscriminatorAlias( persister, suffix );
suffixedVersionColumn = determineVersionAlias( persister );
rowIdAlias = Loadable.ROWID_ALIAS + suffix; // TODO: not visible to the user!
}
public DefaultEntityAliases(Loadable persister, String suffix) {
this( CollectionHelper.EMPTY_MAP, persister, suffix );
}
private String[] determineKeyAlias(Loadable persister, String suffix) {
final String[] aliases;
final String[] keyColumnsCandidates = getUserProvidedAliases( persister.getIdentifierPropertyName(), null );
if ( keyColumnsCandidates == null ) {
aliases = getUserProvidedAliases(
"id",
getIdentifierAliases(persister, suffix)
);
}
else {
aliases = keyColumnsCandidates;
}
final String[] rtn = StringHelper.unquote( aliases, persister.getFactory().getDialect() );
intern( rtn );
return rtn;
}
private String[][] determinePropertyAliases(Loadable persister) {
return getSuffixedPropertyAliases( persister );
}
private String determineDiscriminatorAlias(Loadable persister, String suffix) {
String alias = getUserProvidedAlias( "class", getDiscriminatorAlias( persister, suffix ) );
return StringHelper.unquote( alias, persister.getFactory().getDialect() );
}
private String[] determineVersionAlias(Loadable persister) {
return persister.isVersioned()
? suffixedPropertyColumns[ persister.getVersionProperty() ]
: null;
}
protected String getDiscriminatorAlias(Loadable persister, String suffix) {
return persister.getDiscriminatorAlias(suffix);
}
@ -118,36 +135,55 @@ public class DefaultEntityAliases implements EntityAliases {
return columns[0];
}
}
/**
* {@inheritDoc}
*/
public String[][] getSuffixedPropertyAliases(Loadable persister) {
int size = persister.getPropertyNames().length;
String[][] suffixedPropertyAliases = new String[size][];
final int size = persister.getPropertyNames().length;
final String[][] suffixedPropertyAliases = new String[size][];
for ( int j = 0; j < size; j++ ) {
suffixedPropertyAliases[j] = getUserProvidedAliases(
persister.getPropertyNames()[j],
getPropertyAliases(persister, j)
);
getPropertyAliases( persister, j )
);
suffixedPropertyAliases[j] = StringHelper.unquote( suffixedPropertyAliases[j], persister.getFactory().getDialect() );
intern( suffixedPropertyAliases[j] );
}
return suffixedPropertyAliases;
}
/**
* {@inheritDoc}
*/
public String[] getSuffixedVersionAliases() {
return suffixedVersionColumn;
}
/**
* {@inheritDoc}
*/
public String[][] getSuffixedPropertyAliases() {
return suffixedPropertyColumns;
}
/**
* {@inheritDoc}
*/
public String getSuffixedDiscriminatorAlias() {
return suffixedDiscriminatorColumn;
}
/**
* {@inheritDoc}
*/
public String[] getSuffixedKeyAliases() {
return suffixedKeyColumns;
}
/**
* {@inheritDoc}
*/
public String getRowIdAlias() {
return rowIdAlias;
}
@ -157,5 +193,4 @@ public class DefaultEntityAliases implements EntityAliases {
strings[i] = strings[i].intern();
}
}
}

View File

@ -58,6 +58,7 @@ import org.hibernate.type.CollectionType;
import org.hibernate.util.ArrayHelper;
import org.hibernate.util.StringHelper;
/**
* Extension point for loaders which use a SQL result set with "unexpected" column aliases.
*
@ -126,7 +127,7 @@ public class CustomLoader extends Loader {
specifiedAliases.add( scalarRtn.getColumnAlias() );
resultColumnProcessors.add(
new ScalarResultColumnProcessor(
StringHelper.unquote( scalarRtn.getColumnAlias() ),
StringHelper.unquote( scalarRtn.getColumnAlias(), factory.getDialect() ),
scalarRtn.getType()
)
);

View File

@ -29,6 +29,8 @@ import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.Arrays;
import org.hibernate.dialect.Dialect;
public final class StringHelper {
private static final int ALIAS_TRUNCATE_LENGTH = 10;
@ -541,4 +543,59 @@ public final class StringHelper {
return name;
}
}
/**
* Determine if the given name is quoted. It is considered quoted if either:
* <ol>
* <li>starts AND ends with backticks (`)</li>
* <li>starts with dialect-specified {@link org.hibernate.dialect.Dialect#openQuote() open-quote}
* AND ends with dialect-specified {@link org.hibernate.dialect.Dialect#closeQuote() close-quote}</li>
* </ol>
*
* @param name The name to check
* @param dialect The dialect (to determine the "real" quoting chars).
*
* @return True if quoted, false otherwise
*/
public static boolean isQuoted(String name, Dialect dialect) {
return name != null && name.length() != 0
&& ( name.charAt( 0 ) == '`' && name.charAt( name.length() - 1 ) == '`'
|| name.charAt( 0 ) == dialect.openQuote() && name.charAt( name.length() - 1 ) == dialect.closeQuote() );
}
/**
* Return the unquoted version of name stripping the start and end quote characters.
*
* @param name The name to be unquoted.
* @param dialect The dialect (to determine the "real" quoting chars).
*
* @return The unquoted version.
*/
public static String unquote(String name, Dialect dialect) {
if ( isQuoted( name, dialect ) ) {
return name.substring( 1, name.length() - 1 );
}
else {
return name;
}
}
/**
* Return the unquoted version of name stripping the start and end quote characters.
*
* @param names The names to be unquoted.
* @param dialect The dialect (to determine the "real" quoting chars).
*
* @return The unquoted versions.
*/
public static String[] unquote(String[] names, Dialect dialect) {
if ( names == null ) {
return null;
}
String[] unquoted = new String[ names.length ];
for ( int i = 0; i < names.length; i++ ) {
unquoted[i] = unquote( names[i], dialect );
}
return unquoted;
}
}

View File

@ -0,0 +1,58 @@
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ Copyright (c) 2010, 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
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.test.sql.hand.quotedidentifiers">
<class name="Person" table="`Person`">
<id name="id" unsaved-value="0" column="`pId`">
<generator class="increment"/>
</id>
<property name="name" column="`pName`" not-null="true"/>
</class>
<resultset name="person-scalar">
<return-scalar column="`pId`"/>
<return-scalar column="`pName`"/>
</resultset>
<resultset name="person-entity-basic">
<return alias="p" class="Person"/>
</resultset>
<resultset name="person-entity-expanded">
<return alias="p" class="Person">
<return-property name="id" column="`pId`"/>
<return-property name="name" column="`pName`"/>
</return>
</resultset>
<sql-query name="query-person">
select p."pId", p."pName" from "Person" p
</sql-query>
</hibernate-mapping>

View File

@ -0,0 +1,105 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, 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.test.sql.hand.quotedidentifiers;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.dialect.Dialect;
import org.hibernate.junit.functional.DatabaseSpecificFunctionalTestCase;
/**
* Test of various situations with native-sql queries and quoted identifiers
*
* @author Steve Ebersole
*/
public class NativeSqlAndQuotedIdentifiersTest extends DatabaseSpecificFunctionalTestCase {
public NativeSqlAndQuotedIdentifiersTest(String string) {
super( string );
}
public String[] getMappings() {
return new String[] { "sql/hand/quotedidentifiers/Mappings.hbm.xml" };
}
@Override
public boolean appliesTo(Dialect dialect) {
return '\"' == dialect.openQuote();
}
@Override
protected void prepareTest() throws Exception {
Session session = sfi().openSession();
session.beginTransaction();
session.save( new Person( "me" ) );
session.getTransaction().commit();
session.close();
}
@Override
protected void cleanupTest() throws Exception {
Session session = sfi().openSession();
session.beginTransaction();
session.createQuery( "delete Person" ).executeUpdate();
session.getTransaction().commit();
session.close();
}
public void testCompleteScalarDiscovery() {
Session session = openSession();
session.beginTransaction();
session.getNamedQuery( "query-person" ).list();
session.getTransaction().commit();
session.close();
}
public void testPartialScalarDiscovery() {
Session session = openSession();
session.beginTransaction();
SQLQuery query = (SQLQuery) session.getNamedQuery( "query-person" );
query.setResultSetMapping( "person-scalar" );
query.list();
session.getTransaction().commit();
session.close();
}
public void testBasicEntityMapping() {
Session session = openSession();
session.beginTransaction();
SQLQuery query = (SQLQuery) session.getNamedQuery( "query-person" );
query.setResultSetMapping( "person-entity-basic" );
query.list();
session.getTransaction().commit();
session.close();
}
public void testExpandedEntityMapping() {
Session session = openSession();
session.beginTransaction();
SQLQuery query = (SQLQuery) session.getNamedQuery( "query-person" );
query.setResultSetMapping( "person-entity-expanded" );
query.list();
session.getTransaction().commit();
session.close();
}
}

View File

@ -0,0 +1,57 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, 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.test.sql.hand.quotedidentifiers;
/**
* TODO : javadoc
*
* @author Steve Ebersole
*/
public class Person {
private Long id;
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}