6.0 Final tasks - general test_legacy dir clean-up

At this point, everything left in test_legacy is something I think we want to account for in the test suite (move it, etc)
This commit is contained in:
Steve Ebersole 2021-12-18 12:37:28 -06:00
parent 8f9d200936
commit f9fa2e6e53
81 changed files with 0 additions and 9369 deletions

View File

@ -1,28 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.dialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
/**
* @author Andrea Boriero
*/
public class DerbyDialectDefaultMultiTableBulkIdStrategyTest extends BaseUnitTestCase {
@Test
@TestForIssue(jiraKey = "HHH-10238")
public void testDefaultMultiTableBulkIdStrategyIsLocal() {
MultiTableBulkIdStrategy actual = new DerbyDialectTestCase.LocalDerbyDialect().getFallbackSqmMutationStrategy(
runtimeRootEntityDescriptor );
assertThat(actual, is(instanceOf(LocalTemporaryTableBulkIdStrategy.class)));
}
}

View File

@ -1,39 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.dialect;
import org.junit.Test;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static org.junit.Assert.assertEquals;
public class Oracle8iDialectTestCase extends BaseUnitTestCase {
@Test
@TestForIssue(jiraKey = "HHH-9290")
public void testTemporaryTableNameTruncation() throws Exception {
final AbstractMultiTableBulkIdStrategyImpl strategy = (AbstractMultiTableBulkIdStrategyImpl) new Oracle8iDialect().getFallbackSqmMutationStrategy(
runtimeRootEntityDescriptor );
String temporaryTableName = strategy.getIdTableSupport().generateIdTableName(
"TABLE_NAME_THAT_EXCEEDS_30_CHARACTERS"
);
assertEquals(
"Temporary table names should be truncated to 30 characters",
30,
temporaryTableName.length()
);
assertEquals(
"Temporary table names should start with HT_",
"HT_TABLE_NAME_THAT_EXCEEDS_30_",
temporaryTableName
);
}
}

View File

@ -1,23 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.id.hhh14407;
import jakarta.persistence.Basic;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
/**
* @author Sönke Reimer
*/
@Entity(name="ChildEntity")
class ChildEntity extends ParentEntity {
@Basic
@Column(name="CHILD")
private String ivChild;
}

View File

@ -1,34 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.id.hhh14407;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Inheritance;
import jakarta.persistence.InheritanceType;
import jakarta.persistence.Version;
/**
* @author Sönke Reimer
*/
@Entity(name="ParentEntity")
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
class ParentEntity {
@Id
@Column(name = "ID", length = 32)
private String Id;
@Version
@Column(name = "LOCK_VERSION")
private int Lock_Version;
public String getId() {
return Id;
}
}

View File

@ -1,58 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.id.hhh14407;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.persistent.PersistentTableBulkIdStrategy;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
/**
* @author Nathan Xu
* @author Sönke Reimer
*/
@RequiresDialect( value = H2Dialect.class )
@TestForIssue( jiraKey = "HHH14407" )
public class PersistentTableBulkIdStrategyNPETest extends BaseCoreFunctionalTestCase {
@Override
protected void configure(Configuration configuration) {
configuration.setProperty(
Environment.DIALECT,
PersistentTableBulkIdH2Dialect.class.getName()
);
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
ParentEntity.class,
ChildEntity.class
};
}
@Test
public void hhh14407Test() {
// without fix of HHH14407, the test case will trigger exception due to NPE in PersistentTableBulkIdStrategy
}
public static class PersistentTableBulkIdH2Dialect extends H2Dialect {
@Override
public MultiTableBulkIdStrategy getDefaultMultiTableBulkIdStrategy() {
return new PersistentTableBulkIdStrategy();
}
}
}

View File

@ -1,253 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.sql;
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.hibernate.QueryException;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.HSQLDialect;
import org.hibernate.dialect.function.SQLFunctionRegistry;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.persister.entity.PropertyMapping;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.ServiceRegistryBuilder;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.type.Type;
import static org.junit.Assert.assertEquals;
/**
* @author Steve Ebersole
*/
public class TemplateTest extends BaseUnitTestCase {
private static final PropertyMapping PROPERTY_MAPPING = new PropertyMapping() {
public String[] toColumns(String propertyName) throws QueryException, UnsupportedOperationException {
if ( "sql".equals( propertyName ) ) {
return new String[] { "sql" };
}
else if ( "component".equals( propertyName ) ) {
return new String[] { "comp_1", "comp_2" };
}
else if ( "component.prop1".equals( propertyName ) ) {
return new String[] { "comp_1" };
}
else if ( "component.prop2".equals( propertyName ) ) {
return new String[] { "comp_2" };
}
else if ( "property".equals( propertyName ) ) {
return new String[] { "prop" };
}
throw new QueryException( "could not resolve property: " + propertyName );
}
public Type toType(String propertyName) throws QueryException {
return null;
}
public String[] toColumns(String alias, String propertyName) throws QueryException {
return new String[0];
}
public Type getType() {
return null;
}
};
private static final ColumnMapper MAPPER = new ColumnMapper() {
public SqlValueReference[] map(String reference) {
final String[] columnNames = PROPERTY_MAPPING.toColumns( reference );
final SqlValueReference[] result = new SqlValueReference[ columnNames.length ];
int i = 0;
for ( final String columnName : columnNames ) {
result[i] = new ColumnReference() {
@Override
public String getColumnName() {
return columnName;
}
};
i++;
}
return result;
}
};
private static final Dialect DIALECT = new HSQLDialect();
private static final SQLFunctionRegistry FUNCTION_REGISTRY = new SQLFunctionRegistry( DIALECT, Collections.EMPTY_MAP );
private static SessionFactoryImplementor SESSION_FACTORY = null; // Required for ORDER BY rendering.
@BeforeClass
public static void buildSessionFactory() {
Configuration cfg = new Configuration();
cfg.setProperty( AvailableSettings.DIALECT, DIALECT.getClass().getName() );
ServiceRegistry serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( cfg.getProperties() );
SESSION_FACTORY = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry );
}
@AfterClass
public static void closeSessionFactory() {
if ( SESSION_FACTORY != null ) {
SESSION_FACTORY.close();
SESSION_FACTORY = null;
}
}
@Test
public void testSqlExtractFunction() {
String fragment = "extract( year from col )";
String template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY );
assertEquals( "extract(year from " + Template.TEMPLATE + ".col)", template );
}
@Test
public void testSqlTrimFunction() {
String fragment = "trim( col )";
String template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY );
assertEquals( "trim(" + Template.TEMPLATE + ".col)", template );
fragment = "trim( from col )";
template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY );
assertEquals( "trim(from " + Template.TEMPLATE + ".col)", template );
fragment = "trim( both from col )";
template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY );
assertEquals( "trim(both from " + Template.TEMPLATE + ".col)", template );
fragment = "trim( leading from col )";
template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY );
assertEquals( "trim(leading from " + Template.TEMPLATE + ".col)", template );
fragment = "trim( TRAILING from col )";
template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY );
assertEquals( "trim(TRAILING from " + Template.TEMPLATE + ".col)", template );
fragment = "trim( 'b' from col )";
template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY );
assertEquals( "trim('b' from " + Template.TEMPLATE + ".col)", template );
fragment = "trim( both 'b' from col )";
template = Template.renderWhereStringTemplate( fragment, Template.TEMPLATE, DIALECT, FUNCTION_REGISTRY );
assertEquals( "trim(both 'b' from " + Template.TEMPLATE + ".col)", template );
}
@Test
public void testSQLReferences() {
String fragment = "sql asc, sql desc";
String template = doStandardRendering( fragment );
assertEquals( Template.TEMPLATE + ".sql asc, " + Template.TEMPLATE + ".sql desc", template );
}
@Test
public void testQuotedSQLReferences() {
String fragment = "`sql` asc, `sql` desc";
String template = doStandardRendering( fragment );
assertEquals( Template.TEMPLATE + ".\"sql\" asc, " + Template.TEMPLATE + ".\"sql\" desc", template );
}
@Test
public void testPropertyReference() {
String fragment = "property asc, property desc";
String template = doStandardRendering( fragment );
assertEquals( Template.TEMPLATE + ".prop asc, " + Template.TEMPLATE + ".prop desc", template );
}
@Test
public void testFunctionReference() {
String fragment = "upper(sql) asc, lower(sql) desc";
String template = doStandardRendering( fragment );
assertEquals( "upper(" + Template.TEMPLATE + ".sql) asc, lower(" + Template.TEMPLATE + ".sql) desc", template );
}
@Test
public void testQualifiedFunctionReference() {
String fragment = "qual.upper(property) asc, qual.lower(property) desc";
String template = doStandardRendering( fragment );
assertEquals( "qual.upper(" + Template.TEMPLATE + ".prop) asc, qual.lower(" + Template.TEMPLATE + ".prop) desc", template );
}
@Test
public void testDoubleQualifiedFunctionReference() {
String fragment = "qual1.qual2.upper(property) asc, qual1.qual2.lower(property) desc";
String template = doStandardRendering( fragment );
assertEquals( "qual1.qual2.upper(" + Template.TEMPLATE + ".prop) asc, qual1.qual2.lower(" + Template.TEMPLATE + ".prop) desc", template );
}
@Test
public void testFunctionWithPropertyReferenceAsParam() {
String fragment = "upper(property) asc, lower(property) desc";
String template = doStandardRendering( fragment );
assertEquals( "upper(" + Template.TEMPLATE + ".prop) asc, lower(" + Template.TEMPLATE + ".prop) desc", template );
}
@Test
public void testNestedFunctionReferences() {
String fragment = "upper(lower(sql)) asc, lower(upper(sql)) desc";
String template = doStandardRendering( fragment );
assertEquals( "upper(lower(" + Template.TEMPLATE + ".sql)) asc, lower(upper(" + Template.TEMPLATE + ".sql)) desc", template );
}
@Test
public void testComplexNestedFunctionReferences() {
String fragment = "mod(mod(sql,2),3) asc";
String template = doStandardRendering( fragment );
assertEquals( "mod(mod(" + Template.TEMPLATE + ".sql, 2), 3) asc", template );
}
@Test
public void testCollation() {
String fragment = "`sql` COLLATE my_collation, `sql` COLLATE your_collation";
String template = doStandardRendering( fragment );
assertEquals( Template.TEMPLATE + ".\"sql\" collate my_collation, " + Template.TEMPLATE + ".\"sql\" collate your_collation", template );
}
@Test
public void testCollationAndOrdering() {
String fragment = "sql COLLATE my_collation, upper(prop) COLLATE your_collation asc, `sql` desc";
String template = doStandardRendering( fragment );
assertEquals( Template.TEMPLATE + ".sql collate my_collation, upper(" + Template.TEMPLATE + ".prop) collate your_collation asc, " + Template.TEMPLATE + ".\"sql\" desc", template );
}
@Test
public void testComponentReferences() {
String fragment = "component asc";
String template = doStandardRendering( fragment );
assertEquals( Template.TEMPLATE + ".comp_1 asc, " + Template.TEMPLATE + ".comp_2 asc", template );
}
@Test
public void testComponentDerefReferences() {
String fragment = "component.prop1 asc";
String template = doStandardRendering( fragment );
assertEquals( Template.TEMPLATE + ".comp_1 asc", template );
}
public String doStandardRendering(String fragment) {
return Template.renderOrderByStringTemplate( fragment, MAPPER, SESSION_FACTORY, DIALECT, FUNCTION_REGISTRY );
}
}

View File

@ -1,111 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.ast;
import java.io.PrintWriter;
import antlr.ASTFactory;
import antlr.collections.AST;
import org.junit.Test;
import org.hibernate.hql.internal.antlr.HqlTokenTypes;
import org.hibernate.hql.internal.ast.HqlParser;
import org.hibernate.hql.internal.ast.util.ASTIterator;
import org.hibernate.hql.internal.ast.util.ASTParentsFirstIterator;
import org.hibernate.hql.internal.ast.util.ASTPrinter;
import org.hibernate.hql.internal.ast.util.ASTUtil;
import org.hibernate.hql.internal.ast.util.TokenPrinters;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Test ASTIterator.
*/
public class ASTIteratorTest extends BaseUnitTestCase {
private ASTFactory factory = new ASTFactory();
@Test
public void testSimpleTree() throws Exception {
String input = "select foo from foo in class org.hibernate.test.Foo, fee in class org.hibernate.test.Fee where foo.dependent = fee order by foo.string desc, foo.component.count asc, fee.id";
HqlParser parser = HqlParser.getInstance( input );
parser.statement();
AST ast = parser.getAST();
ASTPrinter printer = TokenPrinters.HQL_TOKEN_PRINTER;
printer.showAst( ast, new PrintWriter( System.out ) );
ASTIterator iterator = new ASTIterator( ast );
int count = 0;
while ( iterator.hasNext() ) {
assertTrue( iterator.next() instanceof AST );
count++;
}
assertEquals( 43, count );
UnsupportedOperationException uoe = null;
try {
iterator.remove();
}
catch ( UnsupportedOperationException e ) {
uoe = e;
}
assertNotNull( uoe );
}
@Test
public void testParentsFirstIterator() throws Exception {
AST[] tree = new AST[4];
AST grandparent = tree[0] = ASTUtil.create( factory, 1, "grandparent" );
AST parent = tree[1] = ASTUtil.create( factory, 2, "parent" );
AST child = tree[2] = ASTUtil.create( factory, 3, "child" );
AST baby = tree[3] = ASTUtil.create( factory, 4, "baby" );
AST t = ASTUtil.createTree( factory, tree );
AST brother = ASTUtil.create( factory, 10, "brother" );
child.setNextSibling( brother );
AST sister = ASTUtil.create( factory, 11, "sister" );
brother.setNextSibling( sister );
AST uncle = factory.make( new AST[]{
factory.create( 20, "uncle" ),
factory.create( 21, "cousin1" ),
factory.create( 22, "cousin2" ),
factory.create( 23, "cousin3" )} );
parent.setNextSibling( uncle );
System.out.println( t.toStringTree() );
System.out.println( "--- ASTParentsFirstIterator ---" );
ASTParentsFirstIterator iter = new ASTParentsFirstIterator( t );
int count = 0;
while ( iter.hasNext() ) {
AST n = iter.nextNode();
count++;
System.out.println( n );
}
assertEquals( 10, count );
System.out.println( "--- ASTIterator ---" );
ASTIterator iter2 = new ASTIterator( t );
int count2 = 0;
while ( iter2.hasNext() ) {
AST n = iter2.nextNode();
count2++;
System.out.println( n );
}
assertEquals( 10, count2 );
System.out.println( "--- ASTParentsFirstIterator (parent) ---" );
ASTParentsFirstIterator iter3 = new ASTParentsFirstIterator( parent );
int count3 = 0;
while ( iter3.hasNext() ) {
AST n = iter3.nextNode();
count3++;
System.out.println( n );
}
assertEquals( 5, count3 );
}
}

View File

@ -1,68 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.ast;
import antlr.ASTFactory;
import antlr.collections.AST;
import org.junit.Test;
import org.hibernate.hql.internal.ast.util.ASTUtil;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
/**
* Unit test for ASTUtil.
*/
public class ASTUtilTest extends BaseUnitTestCase {
private ASTFactory factory = new ASTFactory();
@Test
public void testCreate() throws Exception {
AST n = ASTUtil.create( factory, 1, "one");
assertNull( n.getFirstChild() );
assertEquals( "one", n.getText() );
assertEquals( 1, n.getType() );
}
@Test
public void testCreateTree() throws Exception {
AST[] tree = new AST[4];
AST grandparent = tree[0] = ASTUtil.create(factory, 1, "grandparent");
AST parent = tree[1] = ASTUtil.create(factory,2,"parent");
AST child = tree[2] = ASTUtil.create(factory,3,"child");
AST baby = tree[3] = ASTUtil.create(factory,4,"baby");
AST t = ASTUtil.createTree( factory, tree);
assertSame(t,grandparent);
assertSame(parent,t.getFirstChild());
assertSame(child,t.getFirstChild().getFirstChild());
assertSame( baby, t.getFirstChild().getFirstChild().getFirstChild() );
}
@Test
public void testFindPreviousSibling() throws Exception {
AST child1 = ASTUtil.create(factory,2, "child1");
AST child2 = ASTUtil.create(factory,3, "child2");
AST n = factory.make( new AST[] {
ASTUtil.create(factory, 1, "parent"),
child1,
child2,
});
assertSame(child1,ASTUtil.findPreviousSibling( n,child2));
Exception e = null;
try {
ASTUtil.findPreviousSibling(child1,null);
}
catch (Exception x) {
e = x;
}
assertNotNull(e);
}
}

View File

@ -1,120 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.test.cid;
import java.util.Calendar;
import java.util.Collections;
import jakarta.persistence.PersistenceException;
import org.hibernate.Session;
import org.hibernate.dialect.Oracle8iDialect;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.exception.SQLGrammarException;
import org.hibernate.testing.SkipForDialect;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Andrea Boriero
*/
public class CompositeIdCountEntityTest extends BaseCoreFunctionalTestCase {
@Override
public String[] getMappings() {
return new String[] { "cid/Customer.hbm.xml", "cid/Order.hbm.xml", "cid/LineItem.hbm.xml", "cid/Product.hbm.xml" };
}
@Test
public void testNonDistinctCountOfEntityWithCompositeId() {
// the check here is all based on whether we had commas in the expressions inside the count
final HQLQueryPlan plan = sessionFactory().getQueryInterpretationCache().getHQLQueryPlan(
"select count(o) from Order o",
false,
Collections.EMPTY_MAP
);
assertEquals( 1, plan.getTranslators().length );
final QueryTranslator translator = plan.getTranslators()[0];
final String generatedSql = translator.getSQLString();
final int countExpressionListStart = generatedSql.indexOf( "count(" );
final int countExpressionListEnd = generatedSql.indexOf( ")", countExpressionListStart );
final String countExpressionFragment = generatedSql.substring( countExpressionListStart+6, countExpressionListEnd+1 );
final boolean hadCommas = countExpressionFragment.contains( "," );
// set up the expectation based on Dialect...
final boolean expectCommas = sessionFactory().getDialect().supportsTupleCounts();
assertEquals( expectCommas, hadCommas );
}
@Test
@SkipForDialect(value = Oracle8iDialect.class, comment = "Cannot count distinct over multiple columns in Oracle")
@SkipForDialect(value = SQLServerDialect.class, comment = "Cannot count distinct over multiple columns in SQL Server")
public void testDistinctCountOfEntityWithCompositeId() {
// today we do not account for Dialects supportsTupleDistinctCounts() is false. though really the only
// "option" there is to throw an error.
final HQLQueryPlan plan = sessionFactory().getQueryInterpretationCache().getHQLQueryPlan(
"select count(distinct o) from Order o",
false,
Collections.EMPTY_MAP
);
assertEquals( 1, plan.getTranslators().length );
final QueryTranslator translator = plan.getTranslators()[0];
final String generatedSql = translator.getSQLString();
System.out.println( "Generated SQL : " + generatedSql );
final int countExpressionListStart = generatedSql.indexOf( "count(" );
final int countExpressionListEnd = generatedSql.indexOf( ")", countExpressionListStart );
final String countExpressionFragment = generatedSql.substring( countExpressionListStart+6, countExpressionListEnd+1 );
assertTrue( countExpressionFragment.startsWith( "distinct" ) );
assertTrue( countExpressionFragment.contains( "," ) );
Session s = openSession();
s.beginTransaction();
Customer c = new Customer();
c.setCustomerId( "1" );
c.setAddress("123 somewhere");
c.setName("Brett");
Order o1 = new Order( c );
o1.setOrderDate( Calendar.getInstance() );
Order o2 = new Order( c );
o2.setOrderDate( Calendar.getInstance() );
s.persist( c );
s.persist( o1 );
s.persist( o2 );
s.getTransaction().commit();
s.clear();
s.beginTransaction();
try {
long count = ( Long ) s.createQuery( "select count(distinct o) FROM Order o" ).uniqueResult();
if ( ! getDialect().supportsTupleDistinctCounts() ) {
fail( "expected PersistenceException caused by SQLGrammarException" );
}
assertEquals( 2l, count );
}
catch ( PersistenceException e ) {
if ( ! (e.getCause() instanceof SQLGrammarException ) || getDialect().supportsTupleDistinctCounts() ) {
throw e;
}
}
s.getTransaction().commit();
s.close();
s = openSession();
s.beginTransaction();
s.createQuery("delete from Order").executeUpdate();
s.createQuery("delete from Customer").executeUpdate();
s.getTransaction().commit();
s.close();
}
}

View File

@ -1,99 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.test.connections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.hibernate.ConnectionReleaseMode;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.jta.TestingJtaBootstrap;
import org.hibernate.testing.jta.TestingJtaPlatformImpl;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Andrea Boriero
*/
@RequiresDialect(H2Dialect.class)
public class AggressiveReleaseQueryIterationTest extends ConnectionManagementTestCase {
@Override
@SuppressWarnings("unchecked")
protected void addSettings(Map settings) {
super.addSettings( settings );
TestingJtaBootstrap.prepare( settings );
// settings.put( Environment.TRANSACTION_STRATEGY, CMTTransactionFactory.class.getName() );
settings.put( AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, JtaTransactionCoordinatorBuilderImpl.class.getName() );
settings.put( Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.AFTER_STATEMENT.toString() );
settings.put( Environment.GENERATE_STATISTICS, "true" );
settings.put( Environment.STATEMENT_BATCH_SIZE, "0" );
}
@Override
protected Session getSessionUnderTest() throws Throwable {
return openSession();
}
@Override
protected void reconnect(Session session) {
}
@Override
protected void prepare() throws Throwable {
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
}
@Override
protected void done() throws Throwable {
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
}
@Test
public void testQueryIteration() throws Throwable {
prepare();
Session s = getSessionUnderTest();
Silly silly = new Silly( "silly" );
s.save( silly );
s.flush();
List itr = s.createQuery( "from Silly" ).iterate();
assertTrue( itr.hasNext() );
Silly silly2 = ( Silly ) itr.next();
assertEquals( silly, silly2 );
Hibernate.close( itr );
itr = s.createQuery( "from Silly" ).iterate();
Iterator itr2 = s.createQuery( "from Silly where name = 'silly'" ).iterate();
assertTrue( itr.hasNext() );
assertEquals( silly, itr.next() );
assertTrue( itr2.hasNext() );
assertEquals( silly, itr2.next() );
Hibernate.close( itr );
Hibernate.close( itr2 );
s.delete( silly );
s.flush();
release( s );
done();
}
}

View File

@ -1,22 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
public abstract class AbstractFoo {
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}

View File

@ -1,28 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
/**
* @author Gail Badner
*/
public class Address {
private int addressId;
public int getAddressId() {
return addressId;
}
private String addressText;
public String getAddressText() {
return addressText;
}
public void setAddressText(String addressText) {
this.addressText = addressText;
}
}

View File

@ -1,23 +0,0 @@
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping SYSTEM "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
<hibernate-mapping
package="org.hibernate.test.hql">
<class name="StateProvince">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<property name="isoCode"/>
</class>
</hibernate-mapping>

View File

@ -1,30 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
public class Bar {
private Integer id;
AbstractFoo myFoo;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public AbstractFoo getMyFoo() {
return myFoo;
}
public void setMyFoo(AbstractFoo myFoo) {
this.myFoo = myFoo;
}
}

View File

@ -1,25 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import java.io.Serializable;
/**
* @author tknowlton at iamhisfriend dot org
*/
@Entity
public class Bid implements Serializable {
@Id
float amount;
@Id
@ManyToOne
Item item;
}

View File

@ -1,41 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
/**
* @author Gail Badner
*/
public class CityState {
private String city;
private String state;
public CityState() {}
public CityState(String city, String state) {
this.city = city;
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}

View File

@ -1,14 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
/**
* @author <a href="mailto:stliu@hibernate.org">Strong Liu</a>
*/
public enum Code {
ADM, CEN, RPA, RPP, PRJ, HUB, RQS, OAD, ORP, ORQ
}

View File

@ -1,38 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
/**
* @author David Mansfield
*/
public class Country {
String code;
String name;
public Country() {}
public Country(String code, String name) {
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -1,46 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id: Course.java 5686 2005-02-12 07:27:32Z steveebersole $
package org.hibernate.test.criteria;
import java.util.HashSet;
import java.util.Set;
/**
* @author Gavin King
*/
public class Course {
private String courseCode;
private String description;
private Set courseMeetings = new HashSet();
private Set crossListedAs;
public String getCourseCode() {
return courseCode;
}
public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set getCourseMeetings() {
return courseMeetings;
}
public void setCourseMeetings(Set courseMeetings) {
this.courseMeetings = courseMeetings;
}
public Set getCrossListedAs() {
return crossListedAs;
}
public void setCrossListedAs(Set crossListedAs) {
this.crossListedAs = crossListedAs;
}
}

View File

@ -1,36 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
/**
* @author Gail Badner
*/
public class CourseMeeting {
private CourseMeetingId id;
private Course course;
public CourseMeeting() {}
public CourseMeeting(Course course, String day, int period, String location) {
this.id = new CourseMeetingId( course, day, period, location );
this.course = course;
}
public CourseMeetingId getId() {
return id;
}
public void setId(CourseMeetingId id) {
this.id = id;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
}

View File

@ -1,52 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
import java.io.Serializable;
/**
* @author Gail Badner
*/
public class CourseMeetingId implements Serializable {
private String courseCode;
private String day;
private int period;
private String location;
public CourseMeetingId() {}
public CourseMeetingId(Course course, String day, int period, String location) {
this.courseCode = course.getCourseCode();
this.day = day;
this.period = period;
this.location = location;
}
public String getCourseCode() {
return courseCode;
}
public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}

View File

@ -1,99 +0,0 @@
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.test.criteria">
<class name="Course">
<id name="courseCode">
<generator class="assigned"/>
</id>
<property name="description"/>
<set name="courseMeetings" inverse="true" cascade="all-delete-orphan">
<key column="courseCode"/>
<one-to-many class="CourseMeeting"/>
</set>
<set name="crossListedAs">
<key />
<element type="string" />
</set>
</class>
<class name="CourseMeeting">
<composite-id name="id" class="CourseMeetingId">
<key-property name="courseCode"/>
<key-property name="day"/>
<key-property name="period"/>
<key-property name="location"/>
</composite-id>
<many-to-one name="course" insert="false" update="false">
<column name="courseCode"/>
</many-to-one>
</class>
<class name="Student">
<id name="studentNumber">
<column name="studentId"/>
<generator class="assigned"/>
</id>
<property name="name" not-null="true"/>
<component name="cityState">
<property name="city" column="address_city"/>
<property name="state" column="address_state"/>
</component>
<set name="enrolments" inverse="true" cascade="delete">
<key column="studentId"/>
<one-to-many class="Enrolment"/>
</set>
<many-to-one name="preferredCourse" column="preferredCourseCode"/>
<map name="addresses" table="studentAddresses">
<key column="studentId" />
<map-key type="string" column="addressType" />
<composite-element class="org.hibernate.test.criteria.StudentAddress" >
<property name="line1" />
<property name="line2" />
<property name="city" />
<property name="state" />
<property name="zip" />
</composite-element>
</map>
<list name="studyAbroads">
<key column="studentId" />
<list-index column="ind" />
<composite-element class="org.hibernate.test.criteria.StudyAbroad">
<property name="date" column="strt_dt"/>
<many-to-one name="country" />
</composite-element>
</list>
</class>
<class name="Country">
<id name="code" />
<property name="name" />
</class>
<class name="Enrolment">
<composite-id>
<key-property name="studentNumber">
<column name="studentId"/>
</key-property>
<key-property name="courseCode"/>
</composite-id>
<many-to-one name="student" insert="false" update="false">
<column name="studentId"/>
</many-to-one>
<many-to-one name="course" insert="false" update="false">
<column name="courseCode"/>
</many-to-one>
<property name="semester" not-null="true"/>
<property name="year" column="`year`" not-null="true"/>
</class>
</hibernate-mapping>

View File

@ -1,69 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id: Enrolment.java 6970 2005-05-31 20:24:41Z oneovthafew $
package org.hibernate.test.criteria;
import java.io.Serializable;
/**
* @author Gavin King
*/
public class Enrolment implements Serializable {
private Student student;
private Course course;
private long studentNumber;
private String courseCode;
private short year;
private short semester;
public String getCourseCode() {
return courseCode;
}
public void setCourseCode(String courseId) {
this.courseCode = courseId;
}
public long getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(long studentId) {
this.studentNumber = studentId;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public short getSemester() {
return semester;
}
public void setSemester(short semester) {
this.semester = semester;
}
public short getYear() {
return year;
}
public void setYear(short year) {
this.year = year;
}
public boolean equals(Object other) {
if ( !(other instanceof Enrolment) ) return false;
Enrolment that = (Enrolment) other;
return studentNumber==that.studentNumber &&
courseCode.equals(that.courseCode);
}
public int hashCode() {
return courseCode.hashCode();
}
}

View File

@ -1,28 +0,0 @@
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.test.criteria">
<class name="AbstractFoo">
<id name="id">
</id>
<discriminator type="string" column="subtype" />
<subclass name="GreatFoo" discriminator-value="KAPUT">
</subclass>
</class>
<class name="Bar">
<id name="id">
</id>
<one-to-one name="myFoo" cascade="all" />
</class>
</hibernate-mapping>

View File

@ -1,12 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
public class GreatFoo extends AbstractFoo {
}

View File

@ -1,25 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
import jakarta.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* @author tknowlton at iamhisfriend dot org
*/
@Entity
public class Item implements Serializable {
@Id
String name;
@OneToMany(mappedBy = "item", fetch = FetchType.EAGER)
@OrderBy("amount desc")
Set<Bid> bids = new HashSet<Bid>();
}

View File

@ -1,40 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.Id;
import jakarta.persistence.IdClass;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
/**
* @author <a href="mailto:stliu@hibernate.org">Strong Liu</a>
*/
@Entity
@IdClass(ListActionRole.class)
public class ListActionRole extends VersionedRecord {
@Id
@Enumerated(EnumType.STRING)
Code roleCode;
@ManyToOne(targetEntity = Role.class)
@JoinColumn(nullable = false)
Role role;
@Override
public String toString() {
return "ListActionRole.Id(roleCode=" + roleCode + ")";
}
@Override
public int hashCode() {
return toString().hashCode();
}
}

View File

@ -1,13 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
/**
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
public class Man extends Person {
}

View File

@ -1,59 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!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.criteria">
<class name="Order" table="t_order">
<id name="orderId" column="order_id" type="int" unsaved-value="0" access="field" >
<generator class="increment" />
</id>
<many-to-one name="orderAddress" cascade="all"/>
<set name="orderLines" cascade="all-delete-orphan" access="field" inverse="true" fetch="select">
<key column="order_id" />
<one-to-many class="OrderLine" />
</set>
<set name="orderContacts" cascade="all-delete-orphan" access="field" fetch="select">
<key column="order_id" />
<many-to-many class="OrderContact" />
</set>
</class>
<class name="OrderLine" table="order_line">
<id name="lineId" column="order_line_id" type="int" unsaved-value="0" access="field" >
<generator class="increment" />
</id>
<many-to-one name="order" column="order_id" class="Order" />
<property name="articleId" column="article_id" type="string" />
</class>
<class name="OrderContact" table="order_contact">
<id name="contactId" column="order_contact_id" type="int" unsaved-value="0" access="field" >
<generator class="increment" />
</id>
<property name="contact" column="contact" type="string" />
<set name="orders" access="field" inverse="true" fetch="select">
<key column="contact_id" />
<many-to-many class="Order" />
</set>
</class>
<class name="OrderAddress">
<id name="orderAddressId" type="int" unsaved-value="0" access="field" >
<generator class="increment" />
</id>
<many-to-one name="deliveryAddress" class="Address" cascade="all" />
<set name="notifiedAddresses" cascade="all" inverse="false" fetch="select" >
<key column="orderAddressId"/>
<one-to-many class="Address"/>
</set>
</class>
<class name="Address">
<id name="addressId" column="address_id" type="int" unsaved-value="0" access="field" >
<generator class="increment" />
</id>
<property name="addressText"/>
</class>
</hibernate-mapping>

View File

@ -1,56 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class Order {
private int orderId;
public int getOrderId() {
return orderId;
}
private Set<OrderLine> orderLines = new HashSet<OrderLine>();
public Set<OrderLine> getLines() {
return Collections.unmodifiableSet(orderLines);
}
public void addLine(OrderLine orderLine){
orderLine.setOrder(this);
this.orderLines.add(orderLine);
}
private Set<OrderContact> orderContacts = new HashSet<OrderContact>();
public Set<OrderContact> getContacts() {
return Collections.unmodifiableSet(orderContacts);
}
public void addContact(OrderContact orderContact){
orderContact.getOrders().add( this );
this.orderContacts.add(orderContact);
}
public OrderAddress orderAddress;
public OrderAddress getOrderAddress() {
return orderAddress;
}
public void setOrderAddress(OrderAddress orderAddress) {
this.orderAddress = orderAddress;
}
public String toString() {
return "" + getOrderId() + " - " + getLines();
}
}

View File

@ -1,43 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
import java.util.HashSet;
import java.util.Set;
public class OrderAddress {
private int orderAddressId;
public int getOrderAddressId() {
return orderAddressId;
}
private Address deliveryAddress;
public Address getDeliveryAddress() {
return deliveryAddress;
}
public void setDeliveryAddress(Address deliveryAddress) {
this.deliveryAddress = deliveryAddress;
}
private Set<Address> notifiedAddresses = new HashSet<Address>();
public Set<Address> getNotifiedAddresses() {
return notifiedAddresses;
}
public void setNotifiedAddresses(Set<Address> notifiedAddresses) {
this.notifiedAddresses = notifiedAddresses;
}
public String toString() {
return "" + orderAddressId + " - " + getDeliveryAddress() + " - " + getNotifiedAddresses();
}
}

View File

@ -1,39 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
import java.util.HashSet;
import java.util.Set;
public class OrderContact {
private int contactId = 0;
private Set<Order> orders = new HashSet<Order>();
private String contact;
public int getContactId() {
return contactId;
}
public Set<Order> getOrders() {
return orders;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String toString() {
return "[" + getContactId() + ":" + getContact() + "]";
}
}

View File

@ -1,41 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
public class OrderLine {
private int lineId = 0;
private Order order;
private String articleId;
public int getLineId() {
return lineId;
}
public Order getOrder() {
return order;
}
public String getArticleId() {
return articleId;
}
public void setOrder(Order order) {
this.order = order;
}
public void setArticleId(String articleId) {
this.articleId = articleId;
}
public String toString() {
return "[" + getLineId() + ":" + getArticleId() + "]";
}
}

View File

@ -1,26 +0,0 @@
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.test.criteria">
<class name="Person">
<id name="id" type="long">
<generator class="org.hibernate.id.enhanced.SequenceStyleGenerator"/>
</id>
<property name="name" type="string"/>
<property name="weight" type="integer"/>
<property name="height" type="integer"/>
<union-subclass name="Man"/>
<union-subclass name="Woman"/>
</class>
</hibernate-mapping>

View File

@ -1,76 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
/**
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
public abstract class Person {
private Long id;
private String name;
private Integer weight;
private Integer height;
@Override
public boolean equals(Object o) {
if ( this == o ) return true;
if ( !( o instanceof Person ) ) return false;
Person person = (Person) o;
if ( height != null ? !height.equals( person.height ) : person.height != null ) return false;
if ( id != null ? !id.equals( person.id ) : person.id != null ) return false;
if ( name != null ? !name.equals( person.name ) : person.name != null ) return false;
if ( weight != null ? !weight.equals( person.weight ) : person.weight != null ) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + ( name != null ? name.hashCode() : 0 );
result = 31 * result + ( weight != null ? weight.hashCode() : 0 );
result = 31 * result + ( height != null ? height.hashCode() : 0 );
return result;
}
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;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
}

View File

@ -1,24 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
/**
* @author <a href="mailto:stliu@hibernate.org">Strong Liu</a>
*/
@Entity
@Table(name = "roles")
public class Role extends VersionedRecord {
@Id
@Enumerated(EnumType.STRING)
Code code;
}

View File

@ -1,23 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.LikeExpression;
public class StringExpression extends LikeExpression {
private final static Character ESCAPE_CODE = new Character( '\\' );
protected StringExpression( String property, String value,
boolean ignoreCase ) {
super( property, value, ESCAPE_CODE, ignoreCase );
}
public static Criterion stringExpression( String propertyName,
String value, boolean ignoreCase ) {
return new StringExpression( propertyName, value, ignoreCase );
}
}

View File

@ -1,82 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author Gavin King
*/
public class Student {
private long studentNumber;
private String name;
private CityState cityState;
private Course preferredCourse;
private Set enrolments = new HashSet();
private Map addresses;
private List studyAbroads;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(long studentNumber) {
this.studentNumber = studentNumber;
}
public CityState getCityState() {
return cityState;
}
public void setCityState(CityState cityState) {
this.cityState = cityState;
}
public Course getPreferredCourse() {
return preferredCourse;
}
public void setPreferredCourse(Course preferredCourse) {
this.preferredCourse = preferredCourse;
}
public Set getEnrolments() {
return enrolments;
}
public void setEnrolments(Set employments) {
this.enrolments = employments;
}
public Map getAddresses() {
return addresses;
}
public void setAddresses(Map addresses) {
this.addresses = addresses;
}
public List getStudyAbroads() {
return studyAbroads;
}
public void setStudyAbroads(List studyAbroads) {
this.studyAbroads = studyAbroads;
}
}

View File

@ -1,96 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
/**
* @author David Mansfield
*/
public class StudentAddress {
private String line1;
private String line2;
private String city;
private String state;
private String zip;
public String getLine1() {
return line1;
}
public void setLine1(String line1) {
this.line1 = line1;
}
public String getLine2() {
return line2;
}
public void setLine2(String line2) {
this.line2 = line2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
// @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((city == null) ? 0 : city.hashCode());
result = prime * result + ((line1 == null) ? 0 : line1.hashCode());
result = prime * result + ((line2 == null) ? 0 : line2.hashCode());
result = prime * result + ((state == null) ? 0 : state.hashCode());
result = prime * result + ((zip == null) ? 0 : zip.hashCode());
return result;
}
// @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StudentAddress other = (StudentAddress) obj;
if (city == null) {
if (other.city != null)
return false;
} else if (!city.equals(other.city))
return false;
if (line1 == null) {
if (other.line1 != null)
return false;
} else if (!line1.equals(other.line1))
return false;
if (line2 == null) {
if (other.line2 != null)
return false;
} else if (!line2.equals(other.line2))
return false;
if (state == null) {
if (other.state != null)
return false;
} else if (!state.equals(other.state))
return false;
if (zip == null) {
if (other.zip != null)
return false;
} else if (!zip.equals(other.zip))
return false;
return true;
}
}

View File

@ -1,34 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
/*
* Created on 28-Jan-2005
*
*/
package org.hibernate.test.criteria;
/**
* @author max
*
*/
public class StudentDTO {
private String studentName;
private String courseDescription;
public StudentDTO() { }
public String getName() {
return studentName;
}
public String getDescription() {
return courseDescription;
}
}

View File

@ -1,37 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
import java.util.Date;
public class StudyAbroad {
private Country country;
private Date date;
public StudyAbroad() {}
public StudyAbroad(Country country, Date date) {
this.country = country;
this.date = date;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}

View File

@ -1,19 +0,0 @@
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.test.criteria">
<class name="TestObject" table="`test`">
<id name="id">
<column name="ID" />
<generator class="native" />
</id>
<property name="text" />
</class>
</hibernate-mapping>

View File

@ -1,29 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
public class TestObject {
private Integer id;
private String text;
public Integer getId() {
return id;
}
public void setId( Integer id ) {
this.id = id;
}
public String getText() {
return text;
}
public void setText( String text ) {
this.text = text;
}
}

View File

@ -1,18 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
import jakarta.persistence.MappedSuperclass;
/**
* @author <a href="mailto:stliu@hibernate.org">Strong Liu</a>
*/
@MappedSuperclass
abstract class VersionedRecord implements java.io.Serializable {
Long recordVersion;
Boolean isDeleted;
}

View File

@ -1,13 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.criteria;
/**
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
public class Woman extends Person {
}

View File

@ -1,65 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.hql;
import org.junit.Test;
import org.hibernate.Session;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
/**
* Some simple test queries using the classic translator explicitly
* to ensure that code is not broken in changes for the new translator.
* <p/>
* Only really checking translation and syntax, not results.
*
* @author Steve Ebersole
*/
@RequiresDialectFeature(DialectChecks.SupportsNoColumnInsert.class)
public class ClassicTranslatorTest extends QueryTranslatorTestCase {
@Override
public void configure(Configuration cfg) {
super.configure( cfg );
cfg.setProperty( Environment.QUERY_TRANSLATOR, ClassicQueryTranslatorFactory.class.getName() );
cfg.setProperty( AvailableSettings.JDBC_TYLE_PARAMS_ZERO_BASE, "true" );
}
@Override
public boolean createSchema() {
return true;
}
@Override
public boolean rebuildSessionFactoryOnError() {
return true;
}
@Test
public void testQueries() {
Session session = openSession();
session.beginTransaction();
session.createQuery( "from Animal" ).list();
session.createQuery( "select a from Animal as a" ).list();
session.createQuery( "select a.mother from Animal as a" ).list();
session.createQuery( "select m from Animal as a inner join a.mother as m" ).list();
session.createQuery( "select a from Animal as a inner join fetch a.mother" ).list();
session.createQuery( "from Animal as a where a.description = ?" ).setString( 0, "jj" ).list();
session.createQuery( "from Animal as a where a.description = :desc" ).setString( "desc", "jr" ).list();
session.getTransaction().commit();
session.close();
}
}

View File

@ -1,201 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.test.hql;
import java.util.Collections;
import org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory;
import org.hibernate.hql.internal.ast.QueryTranslatorImpl;
import org.hibernate.hql.spi.QueryTranslatorFactory;
import org.hibernate.internal.log.DeprecationLogger;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.logger.LoggerInspectionRule;
import org.hibernate.testing.logger.Triggerable;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Tests that the forms of referencing parts of and info about collections as a property
* gets logged as a deprecation warning. E.g. {@code `h.family.elements`} is
* deprecated in preference for {@code `elements(h.family)`}
*
* @author Steve Ebersole
*/
public class CollectionPropertyDeprecationsTest extends BaseCoreFunctionalTestCase {
@Rule
public LoggerInspectionRule logInspection = new LoggerInspectionRule(
DeprecationLogger.DEPRECATION_LOGGER
);
@Override
public String[] getMappings() {
return new String[] {"hql/Animal.hbm.xml"};
}
@Override
public boolean createSchema() {
return false;
}
@Override
public boolean rebuildSessionFactoryOnError() {
return false;
}
@Test
@TestForIssue( jiraKey = "HHH-11400" )
public void testReferencingBagElements() {
Triggerable triggerable = logInspection.watchForLogMessages( "HHH90000016" );
// first the accepted ways
compileQuery( "select elements(h.friends) from Human h" );
assertFalse( triggerable.wasTriggered() );
triggerable.reset();
compileQuery( "select h from Human h where h in elements(h.friends)" );
assertFalse( triggerable.wasTriggered() );
triggerable.reset();
// then the deprecated way
compileQuery( "select h.friends.elements from Human h" );
assertTrue( triggerable.wasTriggered() );
}
@Test
@TestForIssue( jiraKey = "HHH-11400" )
public void testReferencingSetElements() {
Triggerable triggerable = logInspection.watchForLogMessages( "HHH90000016" );
// first the accepted ways
compileQuery( "select elements(h.nickNames) from Human h" );
assertFalse( triggerable.wasTriggered() );
triggerable.reset();
compileQuery( "select h from Human h where h.name.first in elements(h.nickNames)" );
assertFalse( triggerable.wasTriggered() );
triggerable.reset();
// then the deprecated way
compileQuery( "select h.nickNames.elements from Human h" );
assertTrue( triggerable.wasTriggered() );
}
@Test
@TestForIssue( jiraKey = "HHH-11400" )
public void testReferencingListElements() {
Triggerable triggerable = logInspection.watchForLogMessages( "HHH90000016" );
// first the accepted ways
compileQuery( "select elements(u.permissions) from User u" );
assertFalse( triggerable.wasTriggered() );
triggerable.reset();
compileQuery( "select u from User u where u.userName in elements(u.permissions)" );
assertFalse( triggerable.wasTriggered() );
triggerable.reset();
// then the deprecated way
compileQuery( "select u.permissions.elements from User u" );
assertTrue( triggerable.wasTriggered() );
}
@Test
@TestForIssue( jiraKey = "HHH-11400" )
public void testReferencingListIndices() {
Triggerable triggerable = logInspection.watchForLogMessages( "HHH90000016" );
// first the accepted ways
compileQuery( "select indices(u.permissions) from User u" );
assertFalse( triggerable.wasTriggered() );
triggerable.reset();
compileQuery( "select u from User u where u.userName in indices(u.permissions)" );
assertFalse( triggerable.wasTriggered() );
triggerable.reset();
// then the deprecated way
compileQuery( "select u.permissions.indices from User u" );
assertTrue( triggerable.wasTriggered() );
}
@Test
@TestForIssue( jiraKey = "HHH-11400" )
public void testReferencingMapElements() {
// NOTE : JPA's VALUE ought to work fine as we never supported
// that in the legacy form...
Triggerable triggerable = logInspection.watchForLogMessages( "HHH90000016" );
// first the accepted ways
compileQuery( "select elements(h.family) from Human h" );
assertFalse( triggerable.wasTriggered() );
triggerable.reset();
compileQuery( "select h from Human h where h.name.first in elements(h.family)" );
assertFalse( triggerable.wasTriggered() );
triggerable.reset();
// then the deprecated way
compileQuery( "select h.family.elements from Human h" );
assertTrue( triggerable.wasTriggered() );
}
@Test
@TestForIssue( jiraKey = "HHH-11400" )
public void testReferencingMapIndices() {
// NOTE : JPA's KEY ought to work fine as we never supported
// that in the legacy form...
Triggerable triggerable = logInspection.watchForLogMessages( "HHH90000016" );
// first the accepted ways
compileQuery( "select indices(h.family) from Human h" );
assertFalse( triggerable.wasTriggered() );
triggerable.reset();
compileQuery( "select h from Human h where h.name.first in indices(h.family)" );
assertFalse( triggerable.wasTriggered() );
triggerable.reset();
// then the deprecated way
compileQuery( "select h.family.indices from Human h" );
assertTrue( triggerable.wasTriggered() );
}
@Test
@TestForIssue( jiraKey = "HHH-11400" )
public void testReferencingSize() {
Triggerable triggerable = logInspection.watchForLogMessages( "HHH90000016" );
// first the accepted ways
compileQuery( "select size(h.family) from Human h" );
assertFalse( triggerable.wasTriggered() );
triggerable.reset();
compileQuery( "select h from Human h where size(h.family) = 1" );
assertFalse( triggerable.wasTriggered() );
triggerable.reset();
// then the deprecated way
compileQuery( "select h.family.size from Human h" );
assertTrue( triggerable.wasTriggered() );
}
private QueryTranslatorImpl compileQuery(String hql) {
QueryTranslatorFactory ast = new ASTQueryTranslatorFactory();
QueryTranslatorImpl newQueryTranslator = (QueryTranslatorImpl) ast.createQueryTranslator(
hql,
hql,
Collections.EMPTY_MAP,
sessionFactory(),
null
);
newQueryTranslator.compile( Collections.emptyMap(), false );
return newQueryTranslator;
}
}

View File

@ -1,297 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.hql;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Collections;
import java.util.List;
import antlr.RecognitionException;
import antlr.TokenStreamException;
import antlr.collections.AST;
import org.junit.Test;
import org.hibernate.hql.internal.antlr.HqlSqlTokenTypes;
import org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory;
import org.hibernate.hql.internal.ast.HqlParser;
import org.hibernate.hql.internal.ast.QueryTranslatorImpl;
import org.hibernate.hql.internal.ast.util.ASTUtil;
import org.hibernate.hql.spi.QueryTranslator;
import org.hibernate.hql.spi.QueryTranslatorFactory;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
/**
* @author <a href="mailto:alex@jboss.org">Alexey Loubyansky</a>
*/
@RequiresDialectFeature(DialectChecks.SupportsNoColumnInsert.class)
public class EJBQLTest extends BaseCoreFunctionalTestCase {
@Override
public String[] getMappings() {
return new String[]{
"hql/Animal.hbm.xml",
"/org/hibernate/orm/test/batchfetch/ProductLine.hbm.xml",
"cid/Customer.hbm.xml",
"cid/Order.hbm.xml",
"cid/LineItem.hbm.xml",
"cid/Product.hbm.xml",
"legacy/Glarch.hbm.xml",
"legacy/Fee.hbm.xml",
"legacy/Qux.hbm.xml",
"legacy/Fum.hbm.xml",
"legacy/Holder.hbm.xml",
"legacy/One.hbm.xml",
"legacy/FooBar.hbm.xml",
"legacy/Many.hbm.xml",
"legacy/Baz.hbm.xml",
"legacy/Simple.hbm.xml",
"legacy/Middle.hbm.xml",
"legacy/Category.hbm.xml",
"legacy/Multi.hbm.xml",
"legacy/Commento.hbm.xml",
"legacy/Marelo.hbm.xml",
"compositeelement/Parent.hbm.xml",
"legacy/Container.hbm.xml",
};
}
@Override
public boolean createSchema() {
return false;
}
@Test
public void testEjb3PositionalParameters() throws Exception {
QueryTranslatorImpl qt = compile( "from Animal a where a.bodyWeight = ?1" );
AST ast = ( AST ) qt.getSqlAST();
// make certain that the ejb3-positional param got recognized as a positional param
List namedParams = ASTUtil.collectChildren(
ast,
new ASTUtil.FilterPredicate() {
public boolean exclude(AST n) {
return n.getType() != HqlSqlTokenTypes.PARAM;
}
}
);
assertTrue( "ejb3 positional param not recognized as a named param", namedParams.size() > 0 );
}
@Test
public void testSelectObjectClause() throws Exception {
//parse("select object(m) from Model m");
assertEjbqlEqualsHql( "select object(m) from Model m", "from Model m" );
}
@Test
public void testCollectionMemberDeclaration() throws Exception {
String hql = "select o from Animal a inner join a.offspring o";
String ejbql = "select object(o) from Animal a, in(a.offspring) o";
//parse(hql);
//parse(ejbql);
assertEjbqlEqualsHql( ejbql, hql );
}
@Test
public void testIsEmpty() throws Exception {
//String hql = "from Animal a where not exists (from a.offspring)";
String hql = "from Animal a where not exists elements(a.offspring)";
String ejbql = "select object(a) from Animal a where a.offspring is empty";
//parse(hql);
//parse(ejbql);
assertEjbqlEqualsHql(ejbql, hql);
hql = "from Animal a where exists (from a.mother.father.offspring)";
ejbql = "select object(a) from Animal a where a.mother.father.offspring is not empty";
assertEjbqlEqualsHql( ejbql, hql );
}
@Test
public void testMemberOf() throws Exception {
String hql = "from Animal a where a.mother in (from a.offspring)";
//String hql = "from Animal a where a.mother in elements(a.offspring)";
String ejbql = "select object(a) from Animal a where a.mother member of a.offspring";
//parse(hql);
//parse(ejbql);
assertEjbqlEqualsHql( ejbql, hql );
hql = "from Animal a where a.mother not in (from a.offspring)";
//hql = "from Animal a where a.mother not in elements(a.offspring)";
ejbql = "select object(a) from Animal a where a.mother not member of a.offspring";
//parse(hql);
//parse(ejbql);
assertEjbqlEqualsHql( ejbql, hql );
}
@Test
public void testEJBQLFunctions() throws Exception {
String hql = "select object(a) from Animal a where a.description = concat('1', concat('2','3'), '4'||'5')||0";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "from Animal a where substring(a.description, 1, 3) = :p1";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select substring(a.description, 1, 3) from Animal a";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "from Animal a where lower(a.description) = :p1";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select lower(a.description) from Animal a";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "from Animal a where upper(a.description) = :p1";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select upper(a.description) from Animal a";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "from Animal a where length(a.description) = :p1";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select length(a.description) from Animal a";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "from Animal a where locate(a.description, 'abc', 2) = :p1";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select locate(a.description, :p1, 2) from Animal a";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select object(a) from Animal a where trim(trailing '_' from a.description) = :p1";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select trim(trailing '_' from a.description) from Animal a";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select object(a) from Animal a where trim(leading '_' from a.description) = :p1";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select object(a) from Animal a where trim(both a.description) = :p1";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select object(a) from Animal a where trim(a.description) = :p1";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select object(a) from Animal a where abs(a.bodyWeight) = sqrt(a.bodyWeight)";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select object(a) from Animal a where mod(a.bodyWeight, a.mother.bodyWeight) = :p1";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select object(a) from Animal a where BIT_LENGTH(a.bodyWeight) = :p1";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select BIT_LENGTH(a.bodyWeight) from Animal a";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select object(a) from Animal a where CURRENT_DATE = :p1 or CURRENT_TIME = :p2 or CURRENT_TIMESTAMP = :p3";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
// todo the following is not supported
//hql = "select CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP from Animal a";
//parse(hql, true);
//System.out.println("sql: " + toSql(hql));
hql = "select object(a) from Animal a where a.bodyWeight like '%a%'";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select object(a) from Animal a where a.bodyWeight not like '%a%'";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
hql = "select object(a) from Animal a where a.bodyWeight like '%a%' escape '%'";
parse( hql, false );
System.out.println( "sql: " + toSql( hql ) );
}
@Test
public void testTrueFalse() throws Exception {
assertEjbqlEqualsHql( "from Human h where h.pregnant is true", "from Human h where h.pregnant = true" );
assertEjbqlEqualsHql( "from Human h where h.pregnant is false", "from Human h where h.pregnant = false" );
assertEjbqlEqualsHql( "from Human h where not(h.pregnant is true)", "from Human h where not( h.pregnant=true )" );
}
private void assertEjbqlEqualsHql(String ejbql, String hql) {
QueryTranslatorFactory ast = new ASTQueryTranslatorFactory();
QueryTranslator queryTranslator = ast.createQueryTranslator( hql, hql, Collections.EMPTY_MAP, sessionFactory(), null );
queryTranslator.compile( Collections.EMPTY_MAP, true );
String hqlSql = queryTranslator.getSQLString();
queryTranslator = ast.createQueryTranslator( ejbql, ejbql, Collections.EMPTY_MAP, sessionFactory(), null );
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, sessionFactory(), null );
queryTranslator.compile( Collections.EMPTY_MAP, true );
return ( QueryTranslatorImpl ) queryTranslator;
}
private AST parse(String input, boolean logging) throws RecognitionException, TokenStreamException {
if ( logging ) {
System.out.println( "input: ->" + input + "<-" );
}
HqlParser parser = HqlParser.getInstance( input );
parser.setFilter( false );
parser.statement();
AST ast = parser.getAST();
if ( logging ) {
System.out.println( "AST : " + ast.toStringTree() + "" );
ByteArrayOutputStream baos = new ByteArrayOutputStream();
parser.showAst( ast, new PrintStream( baos ) );
System.out.println( baos.toString() );
}
assertEquals( "At least one error occurred during parsing!", 0, parser.getParseErrorHandler().getErrorCount() );
return ast;
}
private String toSql(String hql) {
QueryTranslatorFactory ast = new ASTQueryTranslatorFactory();
QueryTranslator queryTranslator = ast.createQueryTranslator( hql, hql, Collections.EMPTY_MAP, sessionFactory(), null );
queryTranslator.compile( Collections.EMPTY_MAP, true );
return queryTranslator.getSQLString();
}
}

View File

@ -1,143 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.hql;
import java.util.List;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import org.hibernate.query.Query;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.junit.Test;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* @author Gail Badner
*/
@TestForIssue( jiraKey = "HHH-12729")
public class HibernateFirstResultMaxResultsTest extends BaseNonConfigCoreFunctionalTestCase {
protected Class[] getAnnotatedClasses() {
return new Class[] { Employee.class };
}
@Test
public void testFirstResult() {
doInHibernate(
this::sessionFactory,
session -> {
Query query = session.createQuery( "from Employee" );
// not initialized yet
assertNull( query.getHibernateFirstResult() );
// the following is special case; when initialized to -1, getHibernateFirstResult returns 0
assertEquals( 0 , query.setFirstResult( -1 ).getFirstResult() );
assertEquals( Integer.valueOf( 0 ), query.setFirstResult( 0 ).getHibernateFirstResult() );
assertEquals( Integer.valueOf( 1 ), query.setFirstResult( 1 ).getHibernateFirstResult() );
assertEquals( Integer.valueOf( 10 ), query.setFirstResult( 10 ).getHibernateFirstResult() );
}
);
}
@Test
public void testMaxResults() {
doInHibernate(
this::sessionFactory,
session -> {
Query query = session.createQuery( "from Employee" );
// not initialized yet
assertNull( query.getHibernateMaxResults() );
// values <= 0 are considered uninitialized;
assertNull( query.setHibernateMaxResults( -1 ).getHibernateMaxResults() );
assertNull( query.setHibernateMaxResults( 0 ).getHibernateMaxResults() );
assertEquals( Integer.valueOf( 1 ), query.setHibernateMaxResults( 1 ).getHibernateMaxResults() );
assertEquals( Integer.valueOf( 0 ), query.setMaxResults( 0 ).getHibernateMaxResults() );
assertEquals( Integer.valueOf( 2 ), query.setMaxResults( 2 ).getHibernateMaxResults() );
}
);
}
@Test
public void testPagination() {
doInHibernate(
this::sessionFactory,
session -> {
for ( int i = 0; i < 5; i++ ) {
session.persist( new Employee( i ) );
}
}
);
final String query = "from Employee order by id";
checkResults( executeQuery( query, null, null ), 0, 4 );
checkResults( executeQuery( query, 0, null ), 0, 4 );
checkResults( executeQuery( query, -1, null ), 0, 4 );
checkResults( executeQuery( query, null, 0 ), 0, 4 );
checkResults( executeQuery( query, null, -1 ), 0, 4 );
checkResults( executeQuery( query, null, 2 ), 0, 1 );
checkResults( executeQuery( query, -1, 0 ), 0, 4 );
checkResults( executeQuery( query, -1, 3 ), 0, 2 );
checkResults( executeQuery( query, 1, null ), 1, 4 );
checkResults( executeQuery( query, 1, 0 ), 1, 4 );
checkResults( executeQuery( query, 1, -1 ), 1, 4 );
checkResults( executeQuery( query, 1, 1 ), 1, 1 );
}
public List executeQuery(String queryString, Integer firstResult, Integer maxResults) {
return doInHibernate(
this::sessionFactory,
session -> {
Query query = session.createQuery( queryString );
if ( firstResult != null ) {
query.setHibernateFirstResult( firstResult );
}
if ( maxResults != null ) {
query.setHibernateMaxResults( maxResults );
}
return query.list();
}
);
}
private void checkResults( List results, int firstIdExpected, int lastIdExpected ) {
int resultIndex = 0;
for( int i = firstIdExpected ; i <= lastIdExpected ; i++, resultIndex++ ) {
assertEquals( i, ( (Employee) results.get( resultIndex ) ).id );
}
}
@Entity(name = "Employee")
public static class Employee {
@Id
private long id;
private String name;
public Employee() {
}
public Employee(long id) {
this.id = id;
}
}
}

View File

@ -1,127 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.hql;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import org.hibernate.query.hql.internal.QuerySplitter;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.stream.IntStream;
import org.hibernate.metamodel.internal.MetamodelImpl;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author Steve Ebersole
*/
public class QuerySplitterTest extends BaseNonConfigCoreFunctionalTestCase {
@Test
public void testQueryWithEntityNameAsStringLiteral() {
final String qry = "select e from Employee a where e.name = ', Employee Number 1'";
String[] results = QuerySplitter.concreteQueries( qry, sessionFactory() );
assertEquals( 1, results.length );
assertEquals(
"select e from org.hibernate.test.hql.QuerySplitterTest$Employee a where e.name = ', Employee Number 1'",
results[0]
);
}
@Test
@TestForIssue(jiraKey = "HHH-7973" )
public void testQueryWithEntityNameAsStringLiteral2() {
final String qry = "from Employee where name = 'He is the, Employee Number 1'";
String[] results = QuerySplitter.concreteQueries( qry, sessionFactory() );
assertEquals( 1, results.length );
assertEquals(
"from org.hibernate.test.hql.QuerySplitterTest$Employee where name = 'He is the, Employee Number 1'",
results[0]
);
}
@Test
@TestForIssue(jiraKey = "HHH-14948")
public void testMemoryConsumptionOfFailedImportsCache() throws NoSuchFieldException, IllegalAccessException {
IntStream.range( 0, 1001 )
.forEach( i -> QuerySplitter.concreteQueries(
"from Employee e join e.company" + i,
sessionFactory()
) );
MetamodelImpl metamodel = (MetamodelImpl) sessionFactory().getMetamodel();
Field field = MetamodelImpl.class.getDeclaredField( "imports" );
field.setAccessible( true );
//noinspection unchecked
Map<String, String> imports = (Map<String, String>) field.get( metamodel );
// VERY hard-coded, but considering the possibility of a regression of a memory-related issue,
// it should be worth it
assertEquals( 1000, imports.size() );
}
@Test
@TestForIssue(jiraKey = "HHH-7973" )
public void testQueryWithEntityNameAsStringLiteralAndEscapeQuoteChar() {
final String qry = "from Employee where name = '''He is '' the, Employee Number 1'''";
String[] results = QuerySplitter.concreteQueries( qry, sessionFactory() );
assertEquals( 1, results.length );
assertEquals(
"from org.hibernate.test.hql.QuerySplitterTest$Employee where name = '''He is '' the, Employee Number 1'''",
results[0]
);
}
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] { Employee.class };
}
@Entity( name = "Employee" )
@Table( name= "tabEmployees" )
public class Employee {
@Id
private long id;
private String name;
public Employee() {
}
public Employee(long id, String strName) {
this();
this.name = strName;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String strName) {
this.name = strName;
}
}
}

View File

@ -1,289 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.hql;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import junit.framework.ComparisonFailure;
import org.hibernate.MappingException;
import org.hibernate.QueryException;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory;
import org.hibernate.hql.internal.ast.QueryTranslatorImpl;
import org.hibernate.hql.internal.ast.util.ASTPrinter;
import org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory;
import org.hibernate.hql.spi.QueryTranslator;
import org.hibernate.hql.spi.QueryTranslatorFactory;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.type.Type;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public abstract class QueryTranslatorTestCase extends BaseCoreFunctionalTestCase {
public String[] getMappings() {
return new String[] {
"hql/Animal.hbm.xml",
"hql/EntityWithCrazyCompositeKey.hbm.xml",
"hql/CrazyIdFieldNames.hbm.xml",
"hql/SimpleEntityWithAssociation.hbm.xml",
"hql/ComponentContainer.hbm.xml",
"/org/hibernate/orm/test/batchfetch/ProductLine.hbm.xml",
"cid/Customer.hbm.xml",
"cid/Order.hbm.xml",
"cid/LineItem.hbm.xml",
"cid/Product.hbm.xml",
"legacy/Baz.hbm.xml",
"legacy/Category.hbm.xml",
"legacy/Commento.hbm.xml",
"legacy/Container.hbm.xml",
"legacy/Custom.hbm.xml",
"legacy/Eye.hbm.xml",
"legacy/Fee.hbm.xml",
"legacy/FooBar.hbm.xml",
"legacy/Fum.hbm.xml",
"legacy/Glarch.hbm.xml",
"legacy/Holder.hbm.xml",
"legacy/Many.hbm.xml",
"legacy/Marelo.hbm.xml",
"legacy/RootDetail.hbm.xml",
"legacy/Middle.hbm.xml",
"legacy/Multi.hbm.xml",
"legacy/Nameable.hbm.xml",
"legacy/One.hbm.xml",
"legacy/Qux.hbm.xml",
"legacy/Simple.hbm.xml",
"legacy/SingleSeveral.hbm.xml",
"legacy/WZ.hbm.xml",
"legacy/UpDown.hbm.xml",
"compositeelement/Parent.hbm.xml",
"onetoone/joined/Person.hbm.xml",
"any/Properties.hbm.xml"
};
}
@Override
public boolean createSchema() {
return false;
}
@Override
public boolean rebuildSessionFactoryOnError() {
return false;
}
public void assertTranslation(String hql) throws QueryException, MappingException {
assertTranslation( hql, null );
}
protected void assertTranslation(String hql, Map replacements) {
ComparisonFailure cf = null;
try {
assertTranslation( hql, replacements, false, null );
}
catch ( ComparisonFailure e ) {
e.printStackTrace();
cf = e;
}
if ( "false".equals( System.getProperty( "org.hibernate.test.hql.SkipScalarQuery", "false" ) ) ) {
// Run the scalar translation anyway, even if there was a comparison failure.
assertTranslation( hql, replacements, true, null );
}
if ( cf != null ) {
throw cf;
}
}
protected void assertTranslation(String hql, Map replacements, boolean scalar, String sql) {
SessionFactoryImplementor factory = sessionFactory();
// Create an empty replacements map if we don't have one.
if ( replacements == null ) {
replacements = new HashMap();
}
// steve -> note that the empty maps here represent the currently enabled filters...
QueryTranslator oldQueryTranslator = null;
Exception oldException = null;
try {
System.out.println("Compiling with classic QueryTranslator...");
QueryTranslatorFactory classic = new ClassicQueryTranslatorFactory();
oldQueryTranslator = classic.createQueryTranslator( hql, hql, Collections.EMPTY_MAP, factory, null );
oldQueryTranslator.compile( replacements, scalar );
}
catch ( QueryException e ) {
oldException = e;
}
catch ( MappingException e ) {
oldException = e;
}
QueryTranslator newQueryTranslator = null;
Exception newException = null;
try {
System.out.println("Compiling with AST QueryTranslator...");
newQueryTranslator = createNewQueryTranslator( hql, replacements, scalar );
}
catch ( QueryException e ) {
newException = e;
}
catch ( MappingException e ) {
newException = e;
}
// If the old QT threw an exception, the new one should too.
if ( oldException != null ) {
assertNotNull( "New query translator did *NOT* throw an exception, the old one did : " + oldException, newException );
assertEquals( oldException.getMessage(), newException.getMessage() );
return; // Don't bother with the rest of the assertions.
}
else if ( newException != null ) {
newException.printStackTrace();
assertNull( "Old query translator did not throw an exception, the new one did", newException );
}
// -- check all of the outputs --
checkSql( oldQueryTranslator, newQueryTranslator, hql, scalar, sql );
checkQuerySpaces( oldQueryTranslator, newQueryTranslator );
checkReturnedTypes( oldQueryTranslator, newQueryTranslator );
}
protected QueryTranslatorImpl createNewQueryTranslator(String hql, Map replacements, boolean scalar) {
SessionFactoryImplementor factory = sessionFactory();
return createNewQueryTranslator( hql, replacements, scalar, factory );
}
private QueryTranslatorImpl createNewQueryTranslator(String hql, Map replacements, boolean scalar, SessionFactoryImplementor factory) {
QueryTranslatorFactory ast = new ASTQueryTranslatorFactory();
QueryTranslatorImpl newQueryTranslator = ( QueryTranslatorImpl ) ast.createQueryTranslator( hql, hql, Collections.EMPTY_MAP, factory, null );
newQueryTranslator.compile( replacements, scalar );
return newQueryTranslator;
}
protected QueryTranslatorImpl createNewQueryTranslator(String hql) {
return createNewQueryTranslator( hql, new HashMap(), false );
}
protected QueryTranslatorImpl createNewQueryTranslator(String hql, SessionFactoryImplementor sfimpl) {
return createNewQueryTranslator( hql, new HashMap(), false, sfimpl );
}
protected HQLQueryPlan createQueryPlan(String hql, boolean scalar) {
return new HQLQueryPlan( hql, scalar, Collections.EMPTY_MAP, sessionFactory() );
}
protected HQLQueryPlan createQueryPlan(String hql) {
return createQueryPlan( hql, false );
}
@Deprecated
protected SessionFactoryImplementor getSessionFactoryImplementor() {
return sessionFactory();
}
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<Serializable> oldQuerySpaces = oldQueryTranslator.getQuerySpaces();
Set<Serializable> querySpaces = newQueryTranslator.getQuerySpaces();
assertEquals( "Query spaces is not the right size!", oldQuerySpaces.size(), querySpaces.size() );
for ( Object o : oldQuerySpaces ) {
assertTrue( "New query space does not contain " + o + "!", querySpaces.contains( o ) );
}
}
protected Exception compileBadHql(String hql, boolean scalar) {
QueryTranslator newQueryTranslator;
Map replacements = null;
Exception newException = null;
SessionFactoryImplementor factory = sessionFactory();
try {
QueryTranslatorFactory ast = new ASTQueryTranslatorFactory();
newQueryTranslator = ast.createQueryTranslator( hql, hql, Collections.EMPTY_MAP, factory, null );
newQueryTranslator.compile( replacements, scalar );
}
catch ( QueryException e ) {
newException = e;
}
catch ( MappingException e ) {
newException = e;
}
assertNotNull( "Expected exception from compilation of '" + hql + "'!", newException );
return newException;
}
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 assertSQLEquals(String message, String oldsql, String newsql) {
Map oldMap = getTokens(oldsql);
Map newMap = getTokens(newsql);
if ( !oldMap.equals(newMap) ) {
assertEquals(message, oldsql, newsql);
}
}
private Map getTokens(String sql) {
Map<String,Integer> result = new TreeMap<String,Integer>();
if ( sql == null ) {
return result;
}
result.put( "=", Integer.valueOf( StringHelper.countUnquoted( sql, '=' ) ) );
StringTokenizer tokenizer = new StringTokenizer( sql, "(),= " );
while ( tokenizer.hasMoreTokens() ) {
String fragment = tokenizer.nextToken();
/*if ( "on".equals(fragment) ) fragment = "and";
if ( "join".equals(fragment) || "inner".equals(fragment) ) continue;*/
Integer count = result.get(fragment);
if ( count == null ) {
count = Integer.valueOf(1);
}
else {
count = Integer.valueOf( count.intValue() + 1 );
}
result.put(fragment, count);
}
return result;
}
}

View File

@ -1,76 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.iterate;
import java.util.Iterator;
import org.junit.Test;
import org.hibernate.Hibernate;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Gavin King
*/
public class IterateTest extends BaseCoreFunctionalTestCase {
public String[] getMappings() {
return new String[] { "iterate/Item.hbm.xml" };
}
public void configure(Configuration cfg) {
super.configure( cfg );
cfg.setProperty( Environment.USE_QUERY_CACHE, "true" );
cfg.setProperty( Environment.CACHE_REGION_PREFIX, "foo" );
cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, "true" );
cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
}
@Test
public void testIterate() throws Exception {
sessionFactory().getStatistics().clear();
Session s = openSession();
Transaction t = s.beginTransaction();
Item i1 = new Item("foo");
Item i2 = new Item("bar");
s.persist("Item", i1);
s.persist("Item", i2);
t.commit();
s.close();
s = openSession();
t = s.beginTransaction();
Iterator iter = s.getNamedQuery("Item.nameDesc").iterate();
i1 = (Item) iter.next();
i2 = (Item) iter.next();
assertFalse( Hibernate.isInitialized(i1) );
assertFalse( Hibernate.isInitialized(i2) );
i1.getName();
i2.getName();
assertFalse( Hibernate.isInitialized(i1) );
assertFalse( Hibernate.isInitialized(i2) );
assertEquals( i1.getName(), "foo" );
assertEquals( i2.getName(), "bar" );
Hibernate.initialize(i1);
assertFalse( iter.hasNext() );
s.delete(i1);
s.delete(i2);
t.commit();
s.close();
assertEquals( sessionFactory().getStatistics().getEntityFetchCount(), 2 );
}
}

View File

@ -1,113 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.test.jpa.compliance.tck2_2;
import java.util.List;
import jakarta.persistence.Column;
import jakarta.persistence.ElementCollection;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
import org.hibernate.boot.MetadataSources;
import org.hibernate.cfg.annotations.CollectionBinder;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.function.SQLFunctionRegistry;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.junit.Test;
import org.hamcrest.CoreMatchers;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* @author Steve Ebersole
*/
public class OrderByAnnotationTests extends BaseNonConfigCoreFunctionalTestCase {
private static final String ELEMENT_TOKEN = "$element$";
private static final String TABLE_ALIAS = "a";
private static final String COLUMN_NAME = "name";
@Test
public void testOrderByEmpty() {
assertThat( translate( "" ), CoreMatchers.is( TABLE_ALIAS + '.' + COLUMN_NAME + " asc" ) );
}
@Test
public void testOrderByJustDesc() {
assertThat( translate( "desc" ), CoreMatchers.is( TABLE_ALIAS + '.' + COLUMN_NAME + " desc" ) );
assertThat( translate( "DESC"), CoreMatchers.is( TABLE_ALIAS + '.' + COLUMN_NAME + " desc" ) );
}
@Test
public void testOrderByJustAsc() {
assertThat( translate( "asc"), CoreMatchers.is( TABLE_ALIAS + '.' + COLUMN_NAME + " asc" ) );
assertThat( translate( "ASC"), CoreMatchers.is( TABLE_ALIAS + '.' + COLUMN_NAME + " asc" ) );
}
private String translate(String fragment) {
fragment = CollectionBinder.adjustUserSuppliedValueCollectionOrderingFragment( fragment );
final TranslationContext translationContext = translationContext();
final OrderByTranslation translation = OrderByFragmentTranslator.translate( translationContext, fragment );
return translation.injectAliases( columnReference -> TABLE_ALIAS );
}
private TranslationContext translationContext() {
final ColumnMapper columnMapper = reference -> {
assert ELEMENT_TOKEN.equals( reference );
return new SqlValueReference[] {
(ColumnReference) () -> COLUMN_NAME
};
};
return new TranslationContext() {
@Override
public SessionFactoryImplementor getSessionFactory() {
return sessionFactory();
}
@Override
public Dialect getDialect() {
return getSessionFactory().getJdbcServices().getJdbcEnvironment().getDialect();
}
@Override
public SQLFunctionRegistry getSqlFunctionRegistry() {
return getSessionFactory().getSqlFunctionRegistry();
}
@Override
public ColumnMapper getColumnMapper() {
return columnMapper;
}
};
}
// @Override
// protected void applyMetadataSources(MetadataSources metadataSources) {
// super.applyMetadataSources( metadataSources );
// metadataSources.addAnnotatedClass( A.class );
// }
//
// @Entity( name = "A" )
// @Table( name = "T_A" )
// public static class A {
// @Id
// public Integer id;
// @ElementCollection
// @Column( name = "name" )
// @OrderBy
// public List<String> names;
// }
}

View File

@ -1,347 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.process;
import jakarta.persistence.CollectionTable;
import jakarta.persistence.Column;
import jakarta.persistence.ElementCollection;
import jakarta.persistence.Embeddable;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.engine.spi.LoadQueryInfluencers;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.jdbc.Work;
import org.hibernate.loader.JoinWalker;
import org.hibernate.loader.entity.EntityJoinWalker;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.persister.entity.OuterJoinLoadable;
import org.junit.Test;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.junit4.ExtraAssertions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
/**
* @author Gail Badner
*/
public class EncapsulatedCompositeAttributeResultSetProcessorTest extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { Person.class, Customer.class };
}
@Test
public void testSimpleNestedCompositeAttributeProcessing() throws Exception {
// create some test data
Session session = openSession();
session.beginTransaction();
Person person = new Person();
person.id = 1;
person.name = "Joe Blow";
person.address = new Address();
person.address.address1 = "1313 Mockingbird Lane";
person.address.city = "Pleasantville";
person.address.country = "USA";
AddressType addressType = new AddressType();
addressType.typeName = "snail mail";
person.address.type = addressType;
session.save( person );
session.getTransaction().commit();
session.close();
// session = openSession();
// session.beginTransaction();
// Person personGotten = (Person) session.get( Person.class, person.id );
// assertEquals( person.id, personGotten.id );
// assertEquals( person.address.address1, personGotten.address.address1 );
// assertEquals( person.address.city, personGotten.address.city );
// assertEquals( person.address.country, personGotten.address.country );
// assertEquals( person.address.type.typeName, personGotten.address.type.typeName );
// session.getTransaction().commit();
// session.close();
List results = getResults( sessionFactory().getEntityPersister( Person.class.getName() ) );
assertEquals( 1, results.size() );
Object result = results.get( 0 );
assertNotNull( result );
Person personWork = ExtraAssertions.assertTyping( Person.class, result );
assertEquals( person.id, personWork.id );
assertEquals( person.address.address1, personWork.address.address1 );
assertEquals( person.address.city, personWork.address.city );
assertEquals( person.address.country, personWork.address.country );
assertEquals( person.address.type.typeName, person.address.type.typeName );
// clean up test data
session = openSession();
session.beginTransaction();
session.createQuery( "delete Person" ).executeUpdate();
session.getTransaction().commit();
session.close();
}
@Test
public void testNestedCompositeElementCollectionQueryBuilding() {
doCompare(
sessionFactory(),
(OuterJoinLoadable) sessionFactory().getClassMetadata( Customer.class )
);
}
private void doCompare(SessionFactoryImplementor sf, OuterJoinLoadable persister) {
final LoadQueryInfluencers influencers = LoadQueryInfluencers.NONE;
final LockMode lockMode = LockMode.NONE;
final int batchSize = 1;
final EntityJoinWalker walker = new EntityJoinWalker(
persister,
persister.getKeyColumnNames(),
batchSize,
lockMode,
sf,
influencers
);
final LoadQueryDetails details = Helper.INSTANCE.buildLoadQueryDetails( persister, sf );
compare( walker, details );
}
private void compare(JoinWalker walker, LoadQueryDetails details) {
System.out.println( "WALKER : " + walker.getSQLString() );
System.out.println( "LOAD-PLAN : " + details.getSqlStatement() );
System.out.println();
}
@Test
public void testNestedCompositeElementCollectionProcessing() throws Exception {
// create some test data
Session session = openSession();
session.beginTransaction();
Person person = new Person();
person.id = 1;
person.name = "Joe Blow";
session.save( person );
Customer customer = new Customer();
customer.id = 1L;
Investment investment1 = new Investment();
investment1.description = "stock";
investment1.date = new Date();
investment1.monetaryAmount = new MonetaryAmount();
investment1.monetaryAmount.currency = MonetaryAmount.CurrencyCode.USD;
investment1.monetaryAmount.amount = BigDecimal.valueOf( 1234, 2 );
investment1.performedBy = person;
Investment investment2 = new Investment();
investment2.description = "bond";
investment2.date = new Date();
investment2.monetaryAmount = new MonetaryAmount();
investment2.monetaryAmount.currency = MonetaryAmount.CurrencyCode.EUR;
investment2.monetaryAmount.amount = BigDecimal.valueOf( 98176, 1 );
customer.investments.add( investment1 );
customer.investments.add( investment2 );
session.save( customer );
session.getTransaction().commit();
session.close();
// session = openSession();
// session.beginTransaction();
// Customer customerGotten = (Customer) session.get( Customer.class, customer.id );
// assertEquals( customer.id, customerGotten.id );
// session.getTransaction().commit();
// session.close();
List results = getResults( sessionFactory().getEntityPersister( Customer.class.getName() ) );
assertEquals( 2, results.size() );
assertSame( results.get( 0 ), results.get( 1 ) );
Object result = results.get( 0 );
assertNotNull( result );
Customer customerWork = ExtraAssertions.assertTyping( Customer.class, result );
// clean up test data
session = openSession();
session.beginTransaction();
session.delete( customerWork.investments.get( 0 ).performedBy );
session.delete( customerWork );
session.getTransaction().commit();
session.close();
}
private List<?> getResults(EntityPersister entityPersister ) {
final LoadPlan plan = Helper.INSTANCE.buildLoadPlan( sessionFactory(), entityPersister );
final LoadQueryDetails queryDetails = Helper.INSTANCE.buildLoadQueryDetails( plan, sessionFactory() );
final String sql = queryDetails.getSqlStatement();
final ResultSetProcessor resultSetProcessor = queryDetails.getResultSetProcessor();
final List results = new ArrayList();
final Session workSession = openSession();
workSession.beginTransaction();
workSession.doWork(
new Work() {
@Override
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement( sql );
ps.setInt( 1, 1 );
ResultSet resultSet = ps.executeQuery();
results.addAll(
resultSetProcessor.extractResults(
resultSet,
(SessionImplementor) workSession,
new QueryParameters(),
Helper.parameterContext(),
true,
false,
null,
null
)
);
resultSet.close();
ps.close();
}
}
);
workSession.getTransaction().commit();
workSession.close();
return results;
}
@Entity( name = "Person" )
public static class Person implements Serializable {
@Id
Integer id;
String name;
@Embedded
Address address;
}
@Embeddable
public static class Address implements Serializable {
String address1;
String city;
String country;
AddressType type;
}
@Embeddable
public static class AddressType {
String typeName;
}
@Entity( name = "Customer" )
public static class Customer {
private Long id;
private List<Investment> investments = new ArrayList<Investment>();
@Id
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable( name = "investments", joinColumns = @JoinColumn( name = "customer_id" ) )
public List<Investment> getInvestments() {
return investments;
}
public void setInvestments(List<Investment> investments) {
this.investments = investments;
}
}
@Embeddable
public static class Investment {
private MonetaryAmount monetaryAmount;
private String description;
private Date date;
private Person performedBy;
@Embedded
public MonetaryAmount getMonetaryAmount() {
return monetaryAmount;
}
public void setMonetaryAmount(MonetaryAmount monetaryAmount) {
this.monetaryAmount = monetaryAmount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name="`date`")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@ManyToOne
public Person getPerformedBy() {
return performedBy;
}
public void setPerformedBy(Person performedBy) {
this.performedBy = performedBy;
}
}
@Embeddable
public static class MonetaryAmount {
public static enum CurrencyCode {
USD,
EUR
}
private BigDecimal amount;
@Column(length = 3)
@Enumerated(EnumType.STRING)
private CurrencyCode currency;
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public CurrencyCode getCurrency() {
return currency;
}
public void setCurrency(CurrencyCode currency) {
this.currency = currency;
}
}
}

View File

@ -1,407 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.process;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import jakarta.persistence.Embeddable;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import org.hibernate.LockOptions;
import org.hibernate.Session;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.jdbc.Work;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.type.Type;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.junit4.ExtraAssertions;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author Gail Badner
*/
public class EncapsulatedCompositeIdResultSetProcessorTest extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { Parent.class, CardField.class, Card.class };
}
@Test
public void testSimpleCompositeId() throws Exception {
// create some test data
Session session = openSession();
session.beginTransaction();
Parent parent = new Parent();
parent.id = new ParentPK();
parent.id.firstName = "Joe";
parent.id.lastName = "Blow";
session.save( parent );
session.getTransaction().commit();
session.close();
session = openSession();
session.beginTransaction();
Parent parentGotten = (Parent) session.get( Parent.class, parent.id );
assertEquals( parent, parentGotten );
session.getTransaction().commit();
session.close();
final List results = getResults(
sessionFactory().getEntityPersister( Parent.class.getName() ),
new Callback() {
@Override
public void bind(PreparedStatement ps) throws SQLException {
ps.setString( 1, "Joe" );
ps.setString( 2, "Blow" );
}
@Override
public QueryParameters getQueryParameters() {
return new QueryParameters();
}
}
);
assertEquals( 1, results.size() );
Object result = results.get( 0 );
assertNotNull( result );
Parent parentWork = ExtraAssertions.assertTyping( Parent.class, result );
assertEquals( parent, parentWork );
// clean up test data
session = openSession();
session.beginTransaction();
session.createQuery( "delete Parent" ).executeUpdate();
session.getTransaction().commit();
session.close();
}
@Test
public void testCompositeIdWithKeyManyToOne() throws Exception {
final String cardId = "ace-of-spades";
// create some test data
Session session = openSession();
session.beginTransaction();
Card card = new Card( cardId );
final CardField cardField = new CardField( card, 1 );
session.persist( card );
session.persist( cardField );
session.getTransaction().commit();
session.close();
session = openSession();
session.beginTransaction();
Card cardProxy = (Card) session.load( Card.class, cardId );
final CardFieldPK cardFieldPK = new CardFieldPK( cardProxy, 1 );
CardField cardFieldGotten = (CardField) session.get( CardField.class, cardFieldPK );
//assertEquals( card, cardGotten );
session.getTransaction().commit();
session.close();
final EntityPersister entityPersister = sessionFactory().getEntityPersister( CardField.class.getName() );
final List results = getResults(
entityPersister,
new Callback() {
@Override
public void bind(PreparedStatement ps) throws SQLException {
ps.setString( 1, cardField.primaryKey.card.id );
ps.setInt( 2, cardField.primaryKey.fieldNumber );
}
@Override
public QueryParameters getQueryParameters() {
QueryParameters qp = new QueryParameters();
qp.setPositionalParameterTypes( new Type[] { entityPersister.getIdentifierType() } );
qp.setPositionalParameterValues( new Object[] { cardFieldPK } );
qp.setOptionalObject( null );
qp.setOptionalEntityName( entityPersister.getEntityName() );
qp.setOptionalId( cardFieldPK );
qp.setLockOptions( LockOptions.NONE );
return qp;
}
}
);
assertEquals( 1, results.size() );
Object result = results.get( 0 );
assertNotNull( result );
CardField cardFieldWork = ExtraAssertions.assertTyping( CardField.class, result );
assertEquals( cardFieldGotten, cardFieldWork );
// clean up test data
session = openSession();
session.beginTransaction();
session.createQuery( "delete CardField" ).executeUpdate();
session.createQuery( "delete Card" ).executeUpdate();
session.getTransaction().commit();
session.close();
}
private List getResults(final EntityPersister entityPersister, final Callback callback) {
final LoadPlan plan = Helper.INSTANCE.buildLoadPlan( sessionFactory(), entityPersister );
final LoadQueryDetails queryDetails = Helper.INSTANCE.buildLoadQueryDetails( plan, sessionFactory() );
final String sql = queryDetails.getSqlStatement();
final ResultSetProcessor resultSetProcessor = queryDetails.getResultSetProcessor();
final List results = new ArrayList();
final Session workSession = openSession();
workSession.beginTransaction();
workSession.doWork(
new Work() {
@Override
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement( sql );
callback.bind( ps );
ResultSet resultSet = ps.executeQuery();
//callback.beforeExtractResults( workSession );
results.addAll(
resultSetProcessor.extractResults(
resultSet,
(SessionImplementor) workSession,
callback.getQueryParameters(),
Helper.parameterContext(),
true,
false,
null,
null
)
);
resultSet.close();
ps.close();
}
}
);
workSession.getTransaction().commit();
workSession.close();
return results;
}
private interface Callback {
void bind(PreparedStatement ps) throws SQLException;
QueryParameters getQueryParameters ();
}
@Entity ( name = "Parent" )
public static class Parent {
@EmbeddedId
public ParentPK id;
public boolean equals(Object o) {
if ( this == o ) return true;
if ( !( o instanceof Parent ) ) return false;
final Parent parent = (Parent) o;
if ( !id.equals( parent.id ) ) return false;
return true;
}
public int hashCode() {
return id.hashCode();
}
}
@Embeddable
public static class ParentPK implements Serializable {
private String firstName;
private String lastName;
public boolean equals(Object o) {
if ( this == o ) return true;
if ( !( o instanceof ParentPK ) ) return false;
final ParentPK parentPk = (ParentPK) o;
if ( !firstName.equals( parentPk.firstName ) ) return false;
if ( !lastName.equals( parentPk.lastName ) ) return false;
return true;
}
public int hashCode() {
int result;
result = firstName.hashCode();
result = 29 * result + lastName.hashCode();
return result;
}
}
@Entity ( name = "CardField" )
public static class CardField implements Serializable {
@EmbeddedId
private CardFieldPK primaryKey;
CardField(Card card, int fieldNumber) {
this.primaryKey = new CardFieldPK(card, fieldNumber);
}
CardField() {
}
public CardFieldPK getPrimaryKey() {
return primaryKey;
}
public void setPrimaryKey(CardFieldPK primaryKey) {
this.primaryKey = primaryKey;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
CardField cardField = (CardField) o;
if ( primaryKey != null ? !primaryKey.equals( cardField.primaryKey ) : cardField.primaryKey != null ) {
return false;
}
return true;
}
@Override
public int hashCode() {
return primaryKey != null ? primaryKey.hashCode() : 0;
}
}
@Embeddable
public static class CardFieldPK implements Serializable {
@ManyToOne(optional = false)
private Card card;
private int fieldNumber;
public CardFieldPK(Card card, int fieldNumber) {
this.card = card;
this.fieldNumber = fieldNumber;
}
CardFieldPK() {
}
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
public int getFieldNumber() {
return fieldNumber;
}
public void setFieldNumber(int fieldNumber) {
this.fieldNumber = fieldNumber;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
CardFieldPK that = (CardFieldPK) o;
if ( fieldNumber != that.fieldNumber ) {
return false;
}
if ( card != null ? !card.equals( that.card ) : that.card != null ) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = card != null ? card.hashCode() : 0;
result = 31 * result + fieldNumber;
return result;
}
}
@Entity ( name = "Card" )
public static class Card implements Serializable {
@Id
private String id;
public Card(String id) {
this();
this.id = id;
}
Card() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
Card card = (Card) o;
if ( !id.equals( card.id ) ) {
return false;
}
return true;
}
@Override
public int hashCode() {
return id.hashCode();
}
}
}

View File

@ -1,261 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.process;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.jdbc.Work;
import org.hibernate.persister.entity.EntityPersister;
import org.junit.Test;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.junit4.ExtraAssertions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Gail Badner
*/
public class EntityAssociationResultSetProcessorTest extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { Message.class, Poster.class, ReportedMessage.class };
}
@Test
public void testManyToOneEntityProcessing() throws Exception {
final EntityPersister entityPersister = sessionFactory().getEntityPersister( Message.class.getName() );
// create some test data
Session session = openSession();
session.beginTransaction();
Message message = new Message( 1, "the message" );
Poster poster = new Poster( 2, "the poster" );
session.save( message );
session.save( poster );
message.poster = poster;
poster.messages.add( message );
session.getTransaction().commit();
session.close();
{
final LoadPlan plan = Helper.INSTANCE.buildLoadPlan( sessionFactory(), entityPersister );
final LoadQueryDetails queryDetails = Helper.INSTANCE.buildLoadQueryDetails( plan, sessionFactory() );
final String sql = queryDetails.getSqlStatement();
final ResultSetProcessor resultSetProcessor = queryDetails.getResultSetProcessor();
final List results = new ArrayList();
final Session workSession = openSession();
workSession.beginTransaction();
workSession.doWork(
new Work() {
@Override
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement( sql );
ps.setInt( 1, 1 );
ResultSet resultSet = ps.executeQuery();
results.addAll(
resultSetProcessor.extractResults(
resultSet,
(SessionImplementor) workSession,
new QueryParameters(),
Helper.parameterContext(),
true,
false,
null,
null
)
);
resultSet.close();
ps.close();
}
}
);
assertEquals( 1, results.size() );
Object result = results.get( 0 );
assertNotNull( result );
Message workMessage = ExtraAssertions.assertTyping( Message.class, result );
assertEquals( 1, workMessage.mid.intValue() );
assertEquals( "the message", workMessage.msgTxt );
assertTrue( Hibernate.isInitialized( workMessage.poster ) );
Poster workPoster = workMessage.poster;
assertEquals( 2, workPoster.pid.intValue() );
assertEquals( "the poster", workPoster.name );
assertFalse( Hibernate.isInitialized( workPoster.messages ) );
workSession.getTransaction().commit();
workSession.close();
}
// clean up test data
session = openSession();
session.beginTransaction();
session.createQuery( "delete Message" ).executeUpdate();
session.createQuery( "delete Poster" ).executeUpdate();
session.getTransaction().commit();
session.close();
}
@Test
public void testNestedManyToOneEntityProcessing() throws Exception {
final EntityPersister entityPersister = sessionFactory().getEntityPersister( ReportedMessage.class.getName() );
// create some test data
Session session = openSession();
session.beginTransaction();
Message message = new Message( 1, "the message" );
Poster poster = new Poster( 2, "the poster" );
session.save( message );
session.save( poster );
message.poster = poster;
poster.messages.add( message );
ReportedMessage reportedMessage = new ReportedMessage( 0, "inappropriate", message );
session.save( reportedMessage );
session.getTransaction().commit();
session.close();
{
final LoadPlan plan = Helper.INSTANCE.buildLoadPlan( sessionFactory(), entityPersister );
final LoadQueryDetails queryDetails = Helper.INSTANCE.buildLoadQueryDetails( plan, sessionFactory() );
final String sql = queryDetails.getSqlStatement();
final ResultSetProcessor resultSetProcessor = queryDetails.getResultSetProcessor();
final List results = new ArrayList();
final Session workSession = openSession();
workSession.beginTransaction();
workSession.doWork(
new Work() {
@Override
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement( sql );
ps.setInt( 1, 0 );
ResultSet resultSet = ps.executeQuery();
results.addAll(
resultSetProcessor.extractResults(
resultSet,
(SessionImplementor) workSession,
new QueryParameters(),
Helper.parameterContext(),
true,
false,
null,
null
)
);
resultSet.close();
ps.close();
}
}
);
assertEquals( 1, results.size() );
Object result = results.get( 0 );
assertNotNull( result );
ReportedMessage workReportedMessage = ExtraAssertions.assertTyping( ReportedMessage.class, result );
assertEquals( 0, workReportedMessage.id.intValue() );
assertEquals( "inappropriate", workReportedMessage.reason );
Message workMessage = workReportedMessage.message;
assertNotNull( workMessage );
assertTrue( Hibernate.isInitialized( workMessage ) );
assertEquals( 1, workMessage.mid.intValue() );
assertEquals( "the message", workMessage.msgTxt );
assertTrue( Hibernate.isInitialized( workMessage.poster ) );
Poster workPoster = workMessage.poster;
assertEquals( 2, workPoster.pid.intValue() );
assertEquals( "the poster", workPoster.name );
assertFalse( Hibernate.isInitialized( workPoster.messages ) );
workSession.getTransaction().commit();
workSession.close();
}
// clean up test data
session = openSession();
session.beginTransaction();
session.createQuery( "delete ReportedMessage" ).executeUpdate();
session.createQuery( "delete Message" ).executeUpdate();
session.createQuery( "delete Poster" ).executeUpdate();
session.getTransaction().commit();
session.close();
}
@Entity( name = "ReportedMessage" )
public static class ReportedMessage {
@Id
private Integer id;
private String reason;
@ManyToOne
@JoinColumn
private Message message;
public ReportedMessage() {}
public ReportedMessage(Integer id, String reason, Message message) {
this.id = id;
this.reason = reason;
this.message = message;
}
}
@Entity( name = "Message" )
public static class Message {
@Id
private Integer mid;
private String msgTxt;
@ManyToOne( cascade = CascadeType.MERGE )
@JoinColumn
private Poster poster;
public Message() {}
public Message(Integer mid, String msgTxt) {
this.mid = mid;
this.msgTxt = msgTxt;
}
}
@Entity( name = "Poster" )
public static class Poster {
@Id
private Integer pid;
private String name;
@OneToMany(mappedBy = "poster")
private List<Message> messages = new ArrayList<Message>();
public Poster() {}
public Poster(Integer pid, String name) {
this.pid = pid;
this.name = name;
}
}
}

View File

@ -1,137 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.process;
import jakarta.persistence.CollectionTable;
import jakarta.persistence.Column;
import jakarta.persistence.ElementCollection;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.jdbc.Work;
import org.hibernate.persister.entity.EntityPersister;
import org.junit.Test;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.junit4.ExtraAssertions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/**
* @author Gail Badner
*/
public class EntityWithNonLazyCollectionResultSetProcessorTest extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { Person.class };
}
@Test
public void testEntityWithSet() throws Exception {
final EntityPersister entityPersister = sessionFactory().getEntityPersister( Person.class.getName() );
// create some test data
Session session = openSession();
session.beginTransaction();
Person person = new Person();
person.id = 1;
person.name = "John Doe";
person.nickNames.add( "Jack" );
person.nickNames.add( "Johnny" );
session.save( person );
session.getTransaction().commit();
session.close();
{
final LoadPlan plan = Helper.INSTANCE.buildLoadPlan( sessionFactory(), entityPersister );
final LoadQueryDetails queryDetails = Helper.INSTANCE.buildLoadQueryDetails( plan, sessionFactory() );
final String sql = queryDetails.getSqlStatement();
final ResultSetProcessor resultSetProcessor = queryDetails.getResultSetProcessor();
final List results = new ArrayList();
final Session workSession = openSession();
workSession.beginTransaction();
workSession.doWork(
new Work() {
@Override
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement( sql );
ps.setInt( 1, 1 );
ResultSet resultSet = ps.executeQuery();
results.addAll(
resultSetProcessor.extractResults(
resultSet,
(SessionImplementor) workSession,
new QueryParameters(),
Helper.parameterContext(),
true,
false,
null,
null
)
);
resultSet.close();
ps.close();
}
}
);
assertEquals( 2, results.size() );
Object result1 = results.get( 0 );
assertSame( result1, results.get( 1 ) );
assertNotNull( result1 );
Person workPerson = ExtraAssertions.assertTyping( Person.class, result1 );
assertEquals( 1, workPerson.id.intValue() );
assertEquals( person.name, workPerson.name );
assertTrue( Hibernate.isInitialized( workPerson.nickNames ) );
assertEquals( 2, workPerson.nickNames.size() );
assertEquals( person.nickNames, workPerson.nickNames );
workSession.getTransaction().commit();
workSession.close();
}
// clean up test data
session = openSession();
session.beginTransaction();
session.delete( person );
session.getTransaction().commit();
session.close();
}
@Entity( name = "Person" )
public static class Person {
@Id
private Integer id;
private String name;
@ElementCollection( fetch = FetchType.EAGER )
@CollectionTable( name = "nick_names", joinColumns = @JoinColumn( name = "pid" ) )
@Column( name = "nick" )
private Set<String> nickNames = new HashSet<String>();
}
}

View File

@ -1,170 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.process;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.jdbc.Work;
import org.hibernate.persister.entity.EntityPersister;
import org.junit.Test;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.junit4.ExtraAssertions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/**
* @author Gail Badner
*/
public class EntityWithNonLazyOneToManyListResultSetProcessorTest extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { Poster.class, Message.class };
}
@Test
public void testEntityWithList() throws Exception {
final EntityPersister entityPersister = sessionFactory().getEntityPersister( Poster.class.getName() );
// create some test data
Session session = openSession();
session.beginTransaction();
Poster poster = new Poster();
poster.pid = 0;
poster.name = "John Doe";
Message message1 = new Message();
message1.mid = 1;
message1.msgTxt = "Howdy!";
message1.poster = poster;
poster.messages.add( message1 );
Message message2 = new Message();
message2.mid = 2;
message2.msgTxt = "Bye!";
message2.poster = poster;
poster.messages.add( message2 );
session.save( poster );
session.getTransaction().commit();
session.close();
// session = openSession();
// session.beginTransaction();
// Poster posterGotten = (Poster) session.get( Poster.class, poster.pid );
// assertEquals( 0, posterGotten.pid.intValue() );
// assertEquals( poster.name, posterGotten.name );
// assertTrue( Hibernate.isInitialized( posterGotten.messages ) );
// assertEquals( 2, posterGotten.messages.size() );
// assertEquals( message1.msgTxt, posterGotten.messages.get( 0 ).msgTxt );
// assertEquals( message2.msgTxt, posterGotten.messages.get( 1 ).msgTxt );
// assertSame( posterGotten, posterGotten.messages.get( 0 ).poster );
// assertSame( posterGotten, posterGotten.messages.get( 1 ).poster );
// session.getTransaction().commit();
// session.close();
{
final LoadPlan plan = Helper.INSTANCE.buildLoadPlan( sessionFactory(), entityPersister );
final LoadQueryDetails queryDetails = Helper.INSTANCE.buildLoadQueryDetails( plan, sessionFactory() );
final String sql = queryDetails.getSqlStatement();
final ResultSetProcessor resultSetProcessor = queryDetails.getResultSetProcessor();
final List results = new ArrayList();
final Session workSession = openSession();
workSession.beginTransaction();
workSession.doWork(
new Work() {
@Override
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement( sql );
ps.setInt( 1, 0 );
ResultSet resultSet = ps.executeQuery();
results.addAll(
resultSetProcessor.extractResults(
resultSet,
(SessionImplementor) workSession,
new QueryParameters(),
Helper.parameterContext(),
true,
false,
null,
null
)
);
resultSet.close();
ps.close();
}
}
);
assertEquals( 2, results.size() );
Object result1 = results.get( 0 );
assertNotNull( result1 );
assertSame( result1, results.get( 1 ) );
Poster workPoster = ExtraAssertions.assertTyping( Poster.class, result1 );
assertEquals( 0, workPoster.pid.intValue() );
assertEquals( poster.name, workPoster.name );
assertTrue( Hibernate.isInitialized( workPoster.messages ) );
assertEquals( 2, workPoster.messages.size() );
assertTrue( Hibernate.isInitialized( workPoster.messages ) );
assertEquals( 2, workPoster.messages.size() );
assertEquals( message1.msgTxt, workPoster.messages.get( 0 ).msgTxt );
assertEquals( message2.msgTxt, workPoster.messages.get( 1 ).msgTxt );
assertSame( workPoster, workPoster.messages.get( 0 ).poster );
assertSame( workPoster, workPoster.messages.get( 1 ).poster );
workSession.getTransaction().commit();
workSession.close();
}
// clean up test data
session = openSession();
session.beginTransaction();
session.delete( poster );
session.getTransaction().commit();
session.close();
}
@Entity( name = "Message" )
public static class Message {
@Id
private Integer mid;
private String msgTxt;
@ManyToOne
@JoinColumn
private Poster poster;
}
@Entity( name = "Poster" )
public static class Poster {
@Id
private Integer pid;
private String name;
@OneToMany(mappedBy = "poster", fetch = FetchType.EAGER, cascade = CascadeType.ALL )
private List<Message> messages = new ArrayList<Message>();
}
}

View File

@ -1,188 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.process;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.jdbc.Work;
import org.hibernate.persister.entity.EntityPersister;
import org.junit.Test;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.junit4.ExtraAssertions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Gail Badner
*/
public class EntityWithNonLazyOneToManySetResultSetProcessorTest extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { Poster.class, Message.class };
}
@Test
public void testEntityWithSet() throws Exception {
final EntityPersister entityPersister = sessionFactory().getEntityPersister( Poster.class.getName() );
// create some test data
Session session = openSession();
session.beginTransaction();
Poster poster = new Poster();
poster.pid = 0;
poster.name = "John Doe";
Message message1 = new Message();
message1.mid = 1;
message1.msgTxt = "Howdy!";
message1.poster = poster;
poster.messages.add( message1 );
Message message2 = new Message();
message2.mid = 2;
message2.msgTxt = "Bye!";
message2.poster = poster;
poster.messages.add( message2 );
session.save( poster );
session.getTransaction().commit();
session.close();
session = openSession();
session.beginTransaction();
Poster posterGotten = (Poster) session.get( Poster.class, poster.pid );
assertEquals( 0, posterGotten.pid.intValue() );
assertEquals( poster.name, posterGotten.name );
assertTrue( Hibernate.isInitialized( posterGotten.messages ) );
assertEquals( 2, posterGotten.messages.size() );
for ( Message message : posterGotten.messages ) {
if ( message.mid == 1 ) {
assertEquals( message1.msgTxt, message.msgTxt );
}
else if ( message.mid == 2 ) {
assertEquals( message2.msgTxt, message.msgTxt );
}
else {
fail( "unexpected message id." );
}
assertSame( posterGotten, message.poster );
}
session.getTransaction().commit();
session.close();
{
final LoadPlan plan = Helper.INSTANCE.buildLoadPlan( sessionFactory(), entityPersister );
final LoadQueryDetails queryDetails = Helper.INSTANCE.buildLoadQueryDetails( plan, sessionFactory() );
final String sql = queryDetails.getSqlStatement();
final ResultSetProcessor resultSetProcessor = queryDetails.getResultSetProcessor();
final List results = new ArrayList();
final Session workSession = openSession();
workSession.beginTransaction();
workSession.doWork(
new Work() {
@Override
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement( sql );
ps.setInt( 1, 0 );
ResultSet resultSet = ps.executeQuery();
results.addAll(
resultSetProcessor.extractResults(
resultSet,
(SessionImplementor) workSession,
new QueryParameters(),
Helper.parameterContext(),
true,
false,
null,
null
)
);
resultSet.close();
ps.close();
}
}
);
assertEquals( 2, results.size() );
Object result1 = results.get( 0 );
assertNotNull( result1 );
assertSame( result1, results.get( 1 ) );
Poster workPoster = ExtraAssertions.assertTyping( Poster.class, result1 );
assertEquals( 0, workPoster.pid.intValue() );
assertEquals( poster.name, workPoster.name );
assertTrue( Hibernate.isInitialized( workPoster.messages ) );
assertEquals( 2, workPoster.messages.size() );
assertTrue( Hibernate.isInitialized( posterGotten.messages ) );
assertEquals( 2, workPoster.messages.size() );
for ( Message message : workPoster.messages ) {
if ( message.mid == 1 ) {
assertEquals( message1.msgTxt, message.msgTxt );
}
else if ( message.mid == 2 ) {
assertEquals( message2.msgTxt, message.msgTxt );
}
else {
fail( "unexpected message id." );
}
assertSame( workPoster, message.poster );
}
workSession.getTransaction().commit();
workSession.close();
}
// clean up test data
session = openSession();
session.beginTransaction();
session.delete( poster );
session.getTransaction().commit();
session.close();
}
@Entity( name = "Message" )
public static class Message {
@Id
private Integer mid;
private String msgTxt;
@ManyToOne
@JoinColumn
private Poster poster;
}
@Entity( name = "Poster" )
public static class Poster {
@Id
private Integer pid;
private String name;
@OneToMany(mappedBy = "poster", fetch = FetchType.EAGER, cascade = CascadeType.ALL )
private Set<Message> messages = new HashSet<Message>();
}
}

View File

@ -1,82 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.process;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.engine.spi.LoadQueryInfluencers;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
* @author Steve Ebersole
*/
public class Helper implements QueryBuildingParameters {
/**
* Singleton access
*/
public static final Helper INSTANCE = new Helper();
private static final QueryBuildingParameters queryBuildingParameters = new QueryBuildingParametersImpl(
LoadQueryInfluencers.NONE,
1,
LockMode.NONE,
null
);
private Helper() {
}
public LoadPlan buildLoadPlan(SessionFactoryImplementor sf, EntityPersister entityPersister) {
final FetchStyleLoadPlanBuildingAssociationVisitationStrategy strategy = new FetchStyleLoadPlanBuildingAssociationVisitationStrategy(
sf,
queryBuildingParameters.getQueryInfluencers(),
queryBuildingParameters.getLockMode()
);
return MetamodelDrivenLoadPlanBuilder.buildRootEntityLoadPlan( strategy, entityPersister );
}
public LoadQueryDetails buildLoadQueryDetails(EntityPersister entityPersister, SessionFactoryImplementor sf) {
return buildLoadQueryDetails(
buildLoadPlan( sf, entityPersister ),
sf
);
}
public LoadQueryDetails buildLoadQueryDetails(LoadPlan loadPlan, SessionFactoryImplementor sf) {
return BatchingLoadQueryDetailsFactory.INSTANCE.makeEntityLoadQueryDetails(
loadPlan,
null,
queryBuildingParameters,
sf
);
}
@Override
public LoadQueryInfluencers getQueryInfluencers() {
return queryBuildingParameters.getQueryInfluencers();
}
@Override
public int getBatchSize() {
return queryBuildingParameters.getBatchSize();
}
@Override
public LockMode getLockMode() {
return queryBuildingParameters.getLockMode();
}
@Override
public LockOptions getLockOptions() {
return queryBuildingParameters.getLockOptions();
}
public static NamedParameterContext parameterContext() {
return name -> new int[0];
}
}

View File

@ -1,185 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.process;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.LockOptions;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.jdbc.Work;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.type.Type;
import org.junit.Test;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.orm.test.onetoone.formula.Address;
import org.hibernate.orm.test.onetoone.formula.Person;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author Steve Ebersole
*/
public class NonEncapsulatedCompositeIdResultSetProcessorTest extends BaseCoreFunctionalTestCase {
@Override
protected String[] getMappings() {
return new String[] { "onetoone/formula/Person.hbm.xml" };
}
@Test
public void testCompositeIdWithKeyManyToOne() throws Exception {
final String personId = "John Doe";
Person p = new Person();
p.setName( personId );
final Address a = new Address();
a.setPerson( p );
p.setAddress( a );
a.setType( "HOME" );
a.setStreet( "Main St" );
a.setState( "Sweet Home Alabama" );
a.setZip( "3181" );
Session s = openSession();
Transaction t = s.beginTransaction();
s.persist( p );
t.commit();
s.close();
final EntityPersister personPersister = sessionFactory().getEntityPersister( Person.class.getName() );
final EntityPersister addressPersister = sessionFactory().getEntityPersister( Address.class.getName() );
{
final List results = getResults(
addressPersister,
new Callback() {
@Override
public void bind(PreparedStatement ps) throws SQLException {
ps.setString( 1, personId );
ps.setString( 2, "HOME" );
}
@Override
public QueryParameters getQueryParameters() {
QueryParameters qp = new QueryParameters();
qp.setPositionalParameterTypes( new Type[] { addressPersister.getIdentifierType() } );
qp.setPositionalParameterValues( new Object[] { a } );
qp.setOptionalObject( a );
qp.setOptionalEntityName( addressPersister.getEntityName() );
qp.setOptionalId( a );
qp.setLockOptions( LockOptions.NONE );
return qp;
}
}
);
assertEquals( 1, results.size() );
Object result = results.get( 0 );
assertNotNull( result );
}
// test loading the Person (the entity with normal id def, but mixed composite fk to Address)
{
final List results = getResults(
personPersister,
new Callback() {
@Override
public void bind(PreparedStatement ps) throws SQLException {
ps.setString( 1, personId );
}
@Override
public QueryParameters getQueryParameters() {
QueryParameters qp = new QueryParameters();
qp.setPositionalParameterTypes( new Type[] { personPersister.getIdentifierType() } );
qp.setPositionalParameterValues( new Object[] { personId } );
qp.setOptionalObject( null );
qp.setOptionalEntityName( personPersister.getEntityName() );
qp.setOptionalId( personId );
qp.setLockOptions( LockOptions.NONE );
return qp;
}
}
);
assertEquals( 1, results.size() );
Object result = results.get( 0 );
assertNotNull( result );
}
// CardField cardFieldWork = ExtraAssertions.assertTyping( CardField.class, result );
// assertEquals( cardFieldGotten, cardFieldWork );
// clean up test data
s = openSession();
s.beginTransaction();
s.createQuery( "delete Address" ).executeUpdate();
s.createQuery( "delete Person" ).executeUpdate();
s.getTransaction().commit();
s.close();
}
private List getResults(final EntityPersister entityPersister, final Callback callback) {
final LoadPlan plan = Helper.INSTANCE.buildLoadPlan( sessionFactory(), entityPersister );
final LoadQueryDetails queryDetails = Helper.INSTANCE.buildLoadQueryDetails( plan, sessionFactory() );
final String sql = queryDetails.getSqlStatement();
final ResultSetProcessor resultSetProcessor = queryDetails.getResultSetProcessor();
final List results = new ArrayList();
final Session workSession = openSession();
workSession.beginTransaction();
workSession.doWork(
new Work() {
@Override
public void execute(Connection connection) throws SQLException {
System.out.println( "SQL : " + sql );
PreparedStatement ps = connection.prepareStatement( sql );
callback.bind( ps );
ResultSet resultSet = ps.executeQuery();
//callback.beforeExtractResults( workSession );
results.addAll(
resultSetProcessor.extractResults(
resultSet,
(SessionImplementor) workSession,
callback.getQueryParameters(),
Helper.parameterContext(),
true,
false,
null,
null
)
);
resultSet.close();
ps.close();
}
}
);
workSession.getTransaction().commit();
workSession.close();
return results;
}
private interface Callback {
void bind(PreparedStatement ps) throws SQLException;
QueryParameters getQueryParameters();
}
}

View File

@ -1,126 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.process;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.jdbc.Work;
import org.hibernate.persister.entity.EntityPersister;
import org.junit.Test;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.junit4.ExtraAssertions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author Steve Ebersole
*/
public class SimpleResultSetProcessorTest extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { SimpleEntity.class };
}
@Test
public void testSimpleEntityProcessing() throws Exception {
final EntityPersister entityPersister = sessionFactory().getEntityPersister( SimpleEntity.class.getName() );
// create some test data
Session session = openSession();
session.beginTransaction();
session.save( new SimpleEntity( 1, "the only" ) );
session.getTransaction().commit();
session.close();
{
final LoadPlan plan = Helper.INSTANCE.buildLoadPlan( sessionFactory(), entityPersister );
final LoadQueryDetails queryDetails = Helper.INSTANCE.buildLoadQueryDetails( plan, sessionFactory() );
final String sql = queryDetails.getSqlStatement();
final ResultSetProcessor resultSetProcessor = queryDetails.getResultSetProcessor();
final List results = new ArrayList();
final Session workSession = openSession();
workSession.beginTransaction();
workSession.doWork(
new Work() {
@Override
public void execute(Connection connection) throws SQLException {
( (SessionImplementor) workSession ).getFactory()
.getServiceRegistry()
.getService( JdbcServices.class )
.getSqlStatementLogger()
.logStatement( sql );
PreparedStatement ps = connection.prepareStatement( sql );
ps.setInt( 1, 1 );
ResultSet resultSet = ps.executeQuery();
results.addAll(
resultSetProcessor.extractResults(
resultSet,
(SessionImplementor) workSession,
new QueryParameters(),
Helper.parameterContext(),
true,
false,
null,
null
)
);
resultSet.close();
ps.close();
}
}
);
assertEquals( 1, results.size() );
Object result = results.get( 0 );
assertNotNull( result );
SimpleEntity workEntity = ExtraAssertions.assertTyping( SimpleEntity.class, result );
assertEquals( 1, workEntity.id.intValue() );
assertEquals( "the only", workEntity.name );
workSession.getTransaction().commit();
workSession.close();
}
// clean up test data
session = openSession();
session.beginTransaction();
session.createQuery( "delete SimpleEntity" ).executeUpdate();
session.getTransaction().commit();
session.close();
}
@Entity(name = "SimpleEntity")
public static class SimpleEntity {
@Id public Integer id;
public String name;
public SimpleEntity() {
}
public SimpleEntity(Integer id, String name) {
this.id = id;
this.name = name;
}
}
}

View File

@ -1,33 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.process.inheritance;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
/**
* @author Steve Ebersole
*/
@Entity
public class Contractor extends User {
// illustrates the problematic situation described in HHH-8330
@ManyToOne(fetch= FetchType.EAGER)
@JoinColumn(name="reportsTo_id",nullable=false)
Department reportsTo;
public Contractor(Integer id, Department reportsTo) {
super( id );
this.reportsTo = reportsTo;
}
public Contractor() {
}
}

View File

@ -1,26 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.process.inheritance;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
/**
* @author Steve Ebersole
*/
@Entity
public class Department {
@Id
Integer id;
public Department(Integer id) {
this.id = id;
}
public Department() {
}
}

View File

@ -1,30 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.process.inheritance;
import jakarta.persistence.Entity;
import jakarta.persistence.ManyToOne;
/**
* @author Steve Ebersole
*/
@Entity
public class Employee extends User {
// illustrates the problematic situation described in HHH-8980
@ManyToOne(optional = false)
Department belongsTo;
public Employee(Integer id, Department belongsTo) {
super( id );
this.belongsTo = belongsTo;
}
public Employee() {
}
}

View File

@ -1,45 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.process.inheritance;
import org.hibernate.Session;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.assertNotNull;
/**
* @author Steve Ebersole
*/
public class Test extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { Department.class, User.class, Employee.class, Contractor.class };
}
@org.junit.Test
public void basicTest() {
Session s = openSession();
s.beginTransaction();
User user = new User( 2 );
s.save( user );
s.getTransaction().commit();
s.close();
s = openSession();
s.beginTransaction();
assertNotNull( s.get( User.class, 2 ) );
s.getTransaction().commit();
s.close();
s = openSession();
s.beginTransaction();
s.createQuery( "delete User" ).executeUpdate();
s.getTransaction().commit();
s.close();
}
}

View File

@ -1,31 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.process.inheritance;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Inheritance;
import jakarta.persistence.InheritanceType;
import jakarta.persistence.Table;
/**
* @author Steve Ebersole
*/
@Entity
@Table( name = "`user`" )
@Inheritance(strategy = InheritanceType.JOINED)
class User {
@Id
Integer id;
User(Integer id) {
this.id = id;
}
User() {
}
}

View File

@ -1,55 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.walking;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import java.util.List;
import org.hibernate.persister.entity.EntityPersister;
import org.junit.Test;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
/**
* @author Steve Ebersole
*/
public class BasicWalkingTest extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { Message.class, Poster.class };
}
@Test
public void testIt() {
EntityPersister ep = (EntityPersister) sessionFactory().getClassMetadata(Message.class);
MetamodelGraphWalker.visitEntity( new LoggingAssociationVisitationStrategy(), ep );
}
@Entity( name = "Message" )
public static class Message {
@Id
private Integer id;
private String name;
@ManyToOne
@JoinColumn
private Poster poster;
}
@Entity( name = "Poster" )
public static class Poster {
@Id
private Integer id;
private String name;
@OneToMany(mappedBy = "poster")
private List<Message> messages;
}
}

View File

@ -1,38 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.walking;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.persister.entity.EntityPersister;
import org.junit.Test;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.hibernate.test.annotations.collectionelement.TestCourse;
/**
* @author Steve Ebersole
*/
public class CompositesWalkingTest extends BaseUnitTestCase {
/**
* Test one-level composites defined as part of an entity.
*/
@Test
public void testEntityComposite() {
final SessionFactory sf = new Configuration()
.addAnnotatedClass( TestCourse.class )
.buildSessionFactory();
try {
final EntityPersister ep = (EntityPersister) sf.getClassMetadata( TestCourse.class );
MetamodelGraphWalker.visitEntity( new LoggingAssociationVisitationStrategy(), ep );
}
finally {
sf.close();
}
}
}

View File

@ -1,32 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.walking;
import org.hibernate.persister.entity.EntityPersister;
import org.junit.Test;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.orm.test.onetoone.formula.Address;
/**
* @author Steve Ebersole
*/
public class KeyManyToOneWalkingTest extends BaseCoreFunctionalTestCase {
@Override
protected String[] getMappings() {
return new String[] { "onetoone/formula/Person.hbm.xml" };
}
@Test
public void testWalkingKeyManyToOneGraphs() {
// Address has a composite id with a bi-directional key-many to Person
final EntityPersister ep = (EntityPersister) sessionFactory().getClassMetadata( Address.class );
MetamodelGraphWalker.visitEntity( new LoggingAssociationVisitationStrategy(), ep );
}
}

View File

@ -1,228 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.walking;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.loader.plan.spi.FetchSource;
import org.hibernate.persister.walking.spi.AnyMappingDefinition;
import org.hibernate.persister.walking.spi.AssociationAttributeDefinition;
import org.hibernate.persister.walking.spi.AssociationKey;
import org.hibernate.persister.walking.spi.AttributeDefinition;
import org.hibernate.persister.walking.spi.CollectionDefinition;
import org.hibernate.persister.walking.spi.CollectionElementDefinition;
import org.hibernate.persister.walking.spi.CollectionIndexDefinition;
import org.hibernate.persister.walking.spi.CompositionDefinition;
import org.hibernate.persister.walking.spi.EntityDefinition;
import org.hibernate.persister.walking.spi.EntityIdentifierDefinition;
/**
* @author Steve Ebersole
*/
public class LoggingAssociationVisitationStrategy implements AssociationVisitationStrategy {
private int depth = 1;
@Override
public void start() {
System.out.println( ">> Start" );
}
@Override
public void finish() {
System.out.println( "<< Finish" );
}
@Override
public void startingEntity(EntityDefinition entityDefinition) {
System.out.println(
String.format(
"%s Starting entity (%s)",
StringHelper.repeat( ">>", ++depth ),
entityDefinition.getEntityPersister().getEntityName()
)
);
}
@Override
public void finishingEntity(EntityDefinition entityDefinition) {
System.out.println(
String.format(
"%s Finishing entity (%s)",
StringHelper.repeat( "<<", depth-- ),
entityDefinition.getEntityPersister().getEntityName()
)
);
}
@Override
public void startingEntityIdentifier(EntityIdentifierDefinition entityIdentifierDefinition) {
System.out.println(
String.format(
"%s Starting [%s] entity identifier (%s)",
StringHelper.repeat( ">>", ++depth ),
entityIdentifierDefinition.isEncapsulated() ? "encapsulated" : "non-encapsulated",
entityIdentifierDefinition.getEntityDefinition().getEntityPersister().getEntityName()
)
);
}
@Override
public void finishingEntityIdentifier(EntityIdentifierDefinition entityIdentifierDefinition) {
System.out.println(
String.format(
"%s Finishing entity identifier (%s)",
StringHelper.repeat( "<<", depth-- ),
entityIdentifierDefinition.getEntityDefinition().getEntityPersister().getEntityName()
)
);
}
@Override
public boolean startingAttribute(AttributeDefinition attributeDefinition) {
System.out.println(
String.format(
"%s Handling attribute (%s)",
StringHelper.repeat( ">>", depth + 1 ),
attributeDefinition.getName()
)
);
return true;
}
@Override
public void finishingAttribute(AttributeDefinition attributeDefinition) {
// nothing to do
}
@Override
public void startingComposite(CompositionDefinition compositionDefinition) {
System.out.println(
String.format(
"%s Starting composite (%s)",
StringHelper.repeat( ">>", ++depth ),
compositionDefinition.getName()
)
);
}
@Override
public void finishingComposite(CompositionDefinition compositionDefinition) {
System.out.println(
String.format(
"%s Finishing composite (%s)",
StringHelper.repeat( "<<", depth-- ),
compositionDefinition.getName()
)
);
}
@Override
public void startingCollection(CollectionDefinition collectionDefinition) {
System.out.println(
String.format(
"%s Starting collection (%s)",
StringHelper.repeat( ">>", ++depth ),
collectionDefinition.getCollectionPersister().getRole()
)
);
}
@Override
public void finishingCollection(CollectionDefinition collectionDefinition) {
System.out.println(
String.format(
"%s Finishing collection (%s)",
StringHelper.repeat( ">>", depth-- ),
collectionDefinition.getCollectionPersister().getRole()
)
);
}
@Override
public void startingCollectionIndex(CollectionIndexDefinition collectionIndexDefinition) {
System.out.println(
String.format(
"%s Starting collection index (%s)",
StringHelper.repeat( ">>", ++depth ),
collectionIndexDefinition.getCollectionDefinition().getCollectionPersister().getRole()
)
);
}
@Override
public void finishingCollectionIndex(CollectionIndexDefinition collectionIndexDefinition) {
System.out.println(
String.format(
"%s Finishing collection index (%s)",
StringHelper.repeat( "<<", depth-- ),
collectionIndexDefinition.getCollectionDefinition().getCollectionPersister().getRole()
)
);
}
@Override
public void startingCollectionElements(CollectionElementDefinition elementDefinition) {
System.out.println(
String.format(
"%s Starting collection elements (%s)",
StringHelper.repeat( ">>", ++depth ),
elementDefinition.getCollectionDefinition().getCollectionPersister().getRole()
)
);
}
@Override
public void finishingCollectionElements(CollectionElementDefinition elementDefinition) {
System.out.println(
String.format(
"%s Finishing collection elements (%s)",
StringHelper.repeat( "<<", depth-- ),
elementDefinition.getCollectionDefinition().getCollectionPersister().getRole()
)
);
}
@Override
public void foundAny(AnyMappingDefinition anyDefinition) {
// nothing to do
}
@Override
public void associationKeyRegistered(AssociationKey associationKey) {
System.out.println(
String.format(
"%s AssociationKey registered : %s",
StringHelper.repeat( ">>", depth + 1 ),
associationKey.toString()
)
);
}
@Override
public FetchSource registeredFetchSource(AssociationKey associationKey) {
return null;
}
@Override
public void foundCircularAssociation(
AssociationAttributeDefinition attributeDefinition) {
System.out.println(
String.format(
"%s Handling circular association attribute (%s) : %s",
StringHelper.repeat( ">>", depth + 1 ),
attributeDefinition.toString(),
attributeDefinition.getAssociationKey().toString()
)
);
}
@Override
public boolean isDuplicateAssociationKey(AssociationKey associationKey) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
}

View File

@ -1,31 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.loadplans.walking;
import org.hibernate.persister.entity.EntityPersister;
import org.junit.Test;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.test.loadplans.process.EncapsulatedCompositeAttributeResultSetProcessorTest.Person;
import org.hibernate.test.loadplans.process.EncapsulatedCompositeAttributeResultSetProcessorTest.Customer;
/**
* @author Steve Ebersole
*/
public class NestedCompositeElementTest extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { Person.class, Customer.class };
}
@Test
public void testWalkingKeyManyToOneGraphs() {
final EntityPersister ep = (EntityPersister) sessionFactory().getClassMetadata( Customer.class );
MetamodelGraphWalker.visitEntity( new LoggingAssociationVisitationStrategy(), ep );
}
}

View File

@ -1,41 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.locale;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
/**
* @author Brett Meyer
*/
@Entity(name="IAmAFoo")
// This needs to start with an I.
public class IAmAFoo {
@Id @GeneratedValue
private long id;
@Column
private String foo;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}

View File

@ -1,82 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.locale;
import java.util.Collections;
import java.util.Locale;
import org.hibernate.HibernateException;
import org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory;
import org.hibernate.hql.spi.QueryTranslator;
import org.hibernate.hql.spi.QueryTranslatorFactory;
import org.hibernate.tool.hbm2ddl.SchemaValidator;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Brett Meyer
*/
public class LocaleTest extends BaseNonConfigCoreFunctionalTestCase {
private static final String asciiRegex = "^\\p{ASCII}*$";
private static Locale currentLocale;
@Test
@TestForIssue(jiraKey = "HHH-8579")
public void testAliasWithLocale() {
// Without the HHH-8579 fix, this will generate non-ascii query aliases.
String hql = "from IAmAFoo";
QueryTranslatorFactory ast = new ASTQueryTranslatorFactory();
QueryTranslator queryTranslator = ast.createQueryTranslator(
hql, hql, Collections.EMPTY_MAP, sessionFactory(), null );
queryTranslator.compile( Collections.EMPTY_MAP, false );
String sql = queryTranslator.getSQLString();
assertTrue( sql.matches( asciiRegex ) );
}
@Test
@TestForIssue(jiraKey = "HHH-8765")
public void testMetadataWithLocale() {
try {
// Rather than building TableMetadata and checking for ascii values in table/column names, simply
// attempt to validate.
new SchemaValidator().validate( metadata() );
}
catch (HibernateException e) {
fail("Failed with the Turkish locale, most likely due to the use of String#toLowerCase() within hbm2ddl. "
+ "Search for all instaces and replace with StringHelper#toLowerCase(String)! " + e.getMessage());
}
}
@BeforeClass
public static void beforeClass() {
currentLocale = Locale.getDefault();
// Turkish will generate a "dotless i" when toLowerCase is used on "I".
Locale.setDefault(Locale.forLanguageTag("tr-TR"));
}
@AfterClass
public static void afterClass() {
Locale.setDefault(currentLocale);
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] { IAmAFoo.class };
}
}

View File

@ -1,137 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.queryplan;
import java.util.Arrays;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.query.spi.QueryInterpretationCache;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.query.internal.QueryParameterBindingsImpl;
import org.hibernate.query.spi.QueryParameterBindings;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate;
import static org.junit.Assert.*;
/**
* Tests for HQL query plans
*
* @author Gail Badner
*/
public class GetHqlQueryPlanTest extends BaseCoreFunctionalTestCase {
public String[] getMappings() {
return new String[]{
"queryplan/filter-defs.hbm.xml",
"queryplan/Joined.hbm.xml"
};
}
protected Map getEnabledFilters(Session s) {
return ( ( SessionImplementor ) s ).getLoadQueryInfluencers().getEnabledFilters();
}
@Test
public void testHqlQueryPlan() {
Session s = openSession();
QueryInterpretationCache cache = ( ( SessionImplementor ) s ).getFactory().getQueryInterpretationCache();
assertTrue( getEnabledFilters( s ).isEmpty() );
HQLQueryPlan plan1 = cache.getHQLQueryPlan( "from Person", false, getEnabledFilters( s ) );
HQLQueryPlan plan2 = cache.getHQLQueryPlan( "from Person where name is null", false, getEnabledFilters( s ) );
HQLQueryPlan plan3 = cache.getHQLQueryPlan( "from Person where name = :name", false, getEnabledFilters( s ) );
HQLQueryPlan plan4 = cache.getHQLQueryPlan( "from Person where name = ?1", false, getEnabledFilters( s ) );
assertNotSame( plan1, plan2 );
assertNotSame( plan1, plan3 );
assertNotSame( plan1, plan4 );
assertNotSame( plan2, plan3 );
assertNotSame( plan2, plan4 );
assertNotSame( plan3, plan4 );
assertSame( plan1, cache.getHQLQueryPlan( "from Person", false, getEnabledFilters( s ) ) );
assertSame( plan2, cache.getHQLQueryPlan( "from Person where name is null", false, getEnabledFilters( s ) ) );
assertSame( plan3, cache.getHQLQueryPlan( "from Person where name = :name", false, getEnabledFilters( s ) ) );
assertSame( plan4, cache.getHQLQueryPlan( "from Person where name = ?1", false, getEnabledFilters( s ) ) );
s.close();
}
@Test
@TestForIssue(jiraKey = "HHH-12413")
public void testExpandingQueryStringMultipleTimesWorks() {
doInHibernate( this::sessionFactory, session -> {
QueryInterpretationCache cache = ( ( SessionImplementor ) session ).getFactory().getQueryInterpretationCache();
String queryString = "from Person where name in :names";
HQLQueryPlan plan = cache.getHQLQueryPlan( queryString, false, getEnabledFilters( session ) );
QueryParameterBindings queryParameterBindings = QueryParameterBindingsImpl.from(
plan.getParameterMetadata(),
(SessionFactoryImplementor) session.getSessionFactory(),
false
);
queryParameterBindings.getQueryParameterListBinding( "names" ).setBindValues( Arrays.asList( "a", "b" ) );
String actualQueryString = queryParameterBindings.expandListValuedParameters(queryString, (SharedSessionContractImplementor) session);
String expectedQueryString = "from Person where name in (:names_0, :names_1)";
assertEquals(
expectedQueryString,
actualQueryString
);
// Expanding the same query again should work as before
actualQueryString = queryParameterBindings.expandListValuedParameters(queryString, (SharedSessionContractImplementor) session);
assertEquals(
expectedQueryString,
actualQueryString
);
} );
}
@Test
public void testHqlQueryPlanWithEnabledFilter() {
Session s = openSession();
QueryInterpretationCache cache = ( (SessionImplementor) s ).getFactory().getQueryInterpretationCache();
HQLQueryPlan plan1A = cache.getHQLQueryPlan( "from Person", true, getEnabledFilters( s ) );
HQLQueryPlan plan1B = cache.getHQLQueryPlan( "from Person", false, getEnabledFilters( s ) );
s.enableFilter( "sex" ).setParameter( "sexCode", Character.valueOf( 'F' ) );
HQLQueryPlan plan2A = cache.getHQLQueryPlan( "from Person", true, getEnabledFilters( s ) );
HQLQueryPlan plan2B = cache.getHQLQueryPlan( "from Person", false, getEnabledFilters( s ) );
s.disableFilter( "sex" );
HQLQueryPlan plan3A = cache.getHQLQueryPlan( "from Person", true, getEnabledFilters( s ) );
HQLQueryPlan plan3B = cache.getHQLQueryPlan( "from Person", false, getEnabledFilters( s ) );
s.enableFilter( "sex" ).setParameter( "sexCode", Character.valueOf( 'M' ) );
HQLQueryPlan plan4A = cache.getHQLQueryPlan( "from Person", true, getEnabledFilters( s ) );
HQLQueryPlan plan4B = cache.getHQLQueryPlan( "from Person", false, getEnabledFilters( s ) );
assertSame( plan1A, plan3A );
assertSame( plan1B, plan3B );
assertSame( plan2A, plan4A );
assertSame( plan2B, plan4B );
assertNotSame( plan1A, plan1B );
assertNotSame( plan1A, plan2A );
assertNotSame( plan1A, plan2B );
assertNotSame( plan1B, plan2A );
assertNotSame( plan1B, plan2B );
s.close();
}
}

View File

@ -1,52 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.queryplan;
import org.junit.Test;
import org.hibernate.engine.query.spi.NativeSQLQueryPlan;
import org.hibernate.query.spi.QueryInterpretationCache;
import org.hibernate.engine.query.spi.sql.NativeSQLQueryReturn;
import org.hibernate.engine.query.spi.sql.NativeSQLQueryScalarReturn;
import org.hibernate.engine.query.spi.sql.NativeSQLQuerySpecification;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.assertEquals;
/**
* Tests equals() for NativeSQLQueryReturn implementations.
*
* @author Michael Stevens
*/
public class NativeSQLQueryPlanEqualsTest extends BaseCoreFunctionalTestCase {
public String[] getMappings() {
return new String[] {};
}
@Test
public void testNativeSQLQuerySpecEquals() {
QueryInterpretationCache cache = new QueryInterpretationCache( sessionFactory() );
NativeSQLQuerySpecification firstSpec = createSpec();
NativeSQLQuerySpecification secondSpec = createSpec();
NativeSQLQueryPlan firstPlan = cache.getNativeSQLQueryPlan(firstSpec);
NativeSQLQueryPlan secondPlan = cache.getNativeSQLQueryPlan(secondSpec);
assertEquals(firstPlan, secondPlan);
}
private NativeSQLQuerySpecification createSpec() {
String blah = "blah";
String select = "select blah from blah";
NativeSQLQueryReturn[] queryReturns = new NativeSQLQueryScalarReturn[] {
new NativeSQLQueryScalarReturn( blah, sessionFactory().getTypeResolver().basic( "int" ) )
};
return new NativeSQLQuerySpecification( select, queryReturns, null );
}
}

View File

@ -1,46 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.test.sql;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
/**
* @author Andrea Boriero
*/
public class NativeQueryDoesNotSupportIterationTest
extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] {TestEntity.class};
}
@Test(expected = UnsupportedOperationException.class)
public void iterateShouldThrowAnUnsupportedOperationException() {
try (Session session = openSession();) {
final NativeQuery sqlQuery = session.createNativeQuery(
"select * from TEST_ENTITY" );
sqlQuery.iterate();
}
}
@Entity(name = "TestEntity")
@Table(name = "TEST_ENTITY")
public static class TestEntity {
@Id
public Long id;
}
}

View File

@ -1,56 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.test.sql.hand.query;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.query.spi.sql.NativeSQLQueryReturn;
import org.hibernate.query.NativeQuery;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Andrea Boriero
*/
public class NamedNativeQueryMementoBuilderTest extends BaseCoreFunctionalTestCase {
public String[] getMappings() {
return new String[] { "sql/hand/query/NativeSQLQueries.hbm.xml" };
}
@Override
public void configure(Configuration cfg) {
super.configure( cfg );
cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
}
@Test
public void testRegisteredNamedSQLQueryWithScalar()
{
final NamedNativeQueryMementoBuilder builder = new NamedNativeQueryMementoBuilder();
builder.setName("namedQuery");
builder.setQuery("select count(*) AS c from ORGANIZATION");
builder.setQueryReturns(new NativeSQLQueryReturn[1]);
sessionFactory().registerNamedSQLQueryDefinition("namedQuery", builder.createNamedQueryDefinition());
final Session s = openSession();
s.beginTransaction();
final NativeQuery query = (NativeQuery) s.getNamedQuery( "namedQuery");
query.addScalar("c");
final Number result = (Number) query.uniqueResult();
s.getTransaction().commit();
s.close();
assertNotNull(result);
assertTrue(0 == result.intValue());
}
}

View File

@ -1,242 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.orm.test.sql.storedproc;
import java.util.List;
import jakarta.persistence.ParameterMode;
import org.hibernate.JDBCException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.procedure.ProcedureCall;
import org.hibernate.procedure.ProcedureOutputs;
import org.hibernate.result.Output;
import org.hibernate.result.ResultSetOutput;
import org.hibernate.testing.RequiresDialect;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.junit.Test;
import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
@RequiresDialect(H2Dialect.class)
public class StoredProcedureParameterRegistrationTest extends BaseCoreFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { H2ProcTesting.MyEntity.class };
}
@Override
protected void configure(Configuration configuration) {
super.configure( configuration );
H2ProcTesting.applyProcDefinitions( configuration );
}
// A warning should be logged if database metadata indicates named parameters are not supported.
@Test
public void testInParametersByName() {
Session session = openSession();
session.beginTransaction();
ProcedureCall query = session.createStoredProcedureCall( "findUserRange" );
query.registerParameter( "start", Integer.class, ParameterMode.IN ).bindValue( 1 );
query.registerParameter( "end", Integer.class, ParameterMode.IN ).bindValue( 2 );
ProcedureOutputs procedureResult = query.getOutputs();
Output currentOutput = procedureResult.getCurrent();
assertNotNull( currentOutput );
ResultSetOutput resultSetReturn = assertTyping( ResultSetOutput.class, currentOutput );
List results = resultSetReturn.getResultList();
assertEquals( 1, results.size() );
Object result = results.get( 0 );
assertTyping( Object[].class, result );
Integer id = (Integer) ( (Object[]) result )[0];
String name = (String) ( (Object[]) result )[1];
assertEquals( 1, (int) id );
assertEquals( "User 1", name );
session.getTransaction().commit();
session.close();
}
@Test
public void testInParametersByPosition() {
Session session = openSession();
session.beginTransaction();
ProcedureCall query = session.createStoredProcedureCall( "findUserRange" );
query.registerParameter( 1, Integer.class, ParameterMode.IN )
.bindValue( 1 );
query.registerParameter( 2, Integer.class, ParameterMode.IN )
.bindValue( 2 );
ProcedureOutputs procedureResult = query.getOutputs();
Output currentOutput = procedureResult.getCurrent();
assertNotNull( currentOutput );
ResultSetOutput resultSetReturn = assertTyping( ResultSetOutput.class, currentOutput );
List results = resultSetReturn.getResultList();
assertEquals( 1, results.size() );
Object result = results.get( 0 );
assertTyping( Object[].class, result );
Integer id = (Integer) ( (Object[]) result )[0];
String name = (String) ( (Object[]) result )[1];
assertEquals( 1, (int) id );
assertEquals( "User 1", name );
session.getTransaction().commit();
session.close();
}
@Test
public void testInParametersNotSet() {
Session session = openSession();
session.beginTransaction();
// since the procedure does not define defaults for parameters this should result in SQLExceptions on
// execution
{
ProcedureCall query = session.createStoredProcedureCall( "findUserRange" );
query.registerParameter( 1, Integer.class, ParameterMode.IN );
query.registerParameter( 2, Integer.class, ParameterMode.IN ).bindValue( 2 );
try {
query.getOutputs();
fail( "Expecting failure due to missing parameter bind" );
}
catch (JDBCException expected) {
}
}
// H2 does not support named parameters
// {
// ProcedureCall query = session.createStoredProcedureCall( "findUserRange" );
// query.registerParameter( "start", Integer.class, ParameterMode.IN );
// query.registerParameter( "end", Integer.class, ParameterMode.IN ).bindValue( 2 );
// try {
// query.getOutputs();
// fail( "Expecting failure due to missing parameter bind" );
// }
// catch (JDBCException expected) {
// }
// }
session.getTransaction().commit();
session.close();
}
@Test
public void testInParametersNotSet() {
Session session = openSession();
session.beginTransaction();
// since the procedure does not define defaults for parameters this should result in SQLExceptions on
// execution
{
ProcedureCall query = session.createStoredProcedureCall( "findUserRange" );
query.registerParameter( 1, Integer.class, ParameterMode.IN );
query.registerParameter( 2, Integer.class, ParameterMode.IN ).bindValue( 2 );
try {
query.getOutputs();
fail( "Expecting failure due to missing parameter bind" );
}
catch (JDBCException expected) {
}
}
// H2 does not support named parameters
// {
// ProcedureCall query = session.createStoredProcedureCall( "findUserRange" );
// query.registerParameter( "start", Integer.class, ParameterMode.IN );
// query.registerParameter( "end", Integer.class, ParameterMode.IN ).bindValue( 2 );
// try {
// query.getOutputs();
// fail( "Expecting failure due to missing parameter bind" );
// }
// catch (JDBCException expected) {
// }
// }
session.getTransaction().commit();
session.close();
}
@Test
public void testInParametersNotSetPass() {
Session session = openSession();
session.beginTransaction();
// unlike #testInParametersNotSet here we are asking that the NULL be passed
// so these executions should succeed
ProcedureCall query = session.createStoredProcedureCall( "findUserRange" );
query.registerParameter( 1, Integer.class, ParameterMode.IN ).enablePassingNulls( true );
query.registerParameter( 2, Integer.class, ParameterMode.IN ).bindValue( 2 );
query.getOutputs();
// H2 does not support named parameters
// {
// ProcedureCall query = session.createStoredProcedureCall( "findUserRange" );
// query.registerParameter( "start", Integer.class, ParameterMode.IN );
// query.registerParameter( "end", Integer.class, ParameterMode.IN ).bindValue( 2 );
// try {
// query.getOutputs();
// fail( "Expecting failure due to missing parameter bind" );
// }
// catch (JDBCException expected) {
// }
// }
session.getTransaction().commit();
session.close();
}
@Test
@SuppressWarnings("unchecked")
public void testInParametersNullnessPassingInNamedQueriesViaHints() {
Session session = openSession();
session.beginTransaction();
// similar to #testInParametersNotSet and #testInParametersNotSetPass in terms of testing
// support for specifying whether to pass NULL argument values or not. This version tests
// named procedure support via hints.
// first a fixture - this execution should fail
{
ProcedureCall query = session.getNamedProcedureCall( "findUserRangeNoNullPassing" );
query.getParameterRegistration( 2 ).bindValue( 2 );
try {
query.getOutputs();
fail( "Expecting failure due to missing parameter bind" );
}
catch (JDBCException ignore) {
}
}
// here we enable NULL passing via hint through a named parameter
{
ProcedureCall query = session.getNamedProcedureCall( "findUserRangeNamedNullPassing" );
query.getParameterRegistration( "secondArg" ).bindValue( 2 );
query.getOutputs();
}
// here we enable NULL passing via hint through a named parameter
{
ProcedureCall query = session.getNamedProcedureCall( "findUserRangeOrdinalNullPassing" );
query.getParameterRegistration( 2 ).bindValue( 2 );
query.getOutputs();
}
session.getTransaction().commit();
session.close();
}
}