diff --git a/hibernate-core/src/test_legacy/org/hibernate/query/criteria/internal/AliasWithCriterionTest.java b/hibernate-core/src/test_legacy/org/hibernate/query/criteria/internal/AliasWithCriterionTest.java deleted file mode 100644 index cc27b94fa3..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/query/criteria/internal/AliasWithCriterionTest.java +++ /dev/null @@ -1,240 +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 . - */ -package org.hibernate.query.criteria.internal; - -import java.util.Date; -import java.util.Set; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.ManyToOne; -import jakarta.persistence.OneToMany; -import jakarta.persistence.Temporal; -import jakarta.persistence.TemporalType; - -import org.hibernate.criterion.CriteriaSpecification; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.ProjectionList; -import org.hibernate.criterion.Projections; -import org.hibernate.criterion.Restrictions; -import org.hibernate.dialect.H2Dialect; -import org.hibernate.sql.JoinType; - -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertTrue; - -/** - * @author Vlad Mihalcea - */ -public class AliasWithCriterionTest extends BaseCoreFunctionalTestCase { - - @Test - @RequiresDialect( H2Dialect.class ) - public void testCaseClause() { - doInHibernate( this::sessionFactory, session -> { - Criteria criteria = session.createCriteria( TableA.class ); - - final String TABLE_B_ALIAS = "tableBAlias"; - final String TABLE_C_ALIAS = "tableCAlias"; - - Criterion tableCRestriction = Restrictions.eq( TABLE_C_ALIAS + ".tableCBoolean", false ); - criteria.createAlias( - TABLE_B_ALIAS + ".tableCs", - TABLE_C_ALIAS, - JoinType.LEFT_OUTER_JOIN, - tableCRestriction - ); - - Criterion tableBRestriction = Restrictions.eq( TABLE_B_ALIAS + ".tableBDate", new Date() ); - criteria.createAlias( "tableBs", TABLE_B_ALIAS, JoinType.LEFT_OUTER_JOIN, tableBRestriction ); - - criteria.add( Restrictions.eq( "tableACharacter", "c" ) ); - - ProjectionList projectionList = Projections.projectionList(); - projectionList.add( Projections.property( "tableACharacter" ) ); - criteria.setProjection( projectionList ); - - criteria.list(); - } ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - TableA.class, - TableB.class, - TableC.class, - }; - } - - @Entity(name = "TableA") - public static class TableA { - - @Id - @Column(name = "table_a_id") - private Long tableAId; - - @Column(name = "table_a_character") - private String tableACharacter; - - @OneToMany(mappedBy = "tableA") - private Set tableBs; - - public TableA() { - } - - public Long getTableAId() { - return this.tableAId; - } - - public void setTableAId_(Long _tableAId_) { - this.tableAId = _tableAId_; - } - - public String getTableACharacter() { - return this.tableACharacter; - } - - public void setTableACharacter(String _tableACharacter_) { - this.tableACharacter = _tableACharacter_; - } - - public Set getTableBs() { - return this.tableBs; - } - - public void setTableBs(Set tableBs) { - this.tableBs = tableBs; - } - - } - - @Entity(name = "TableB") - public static class TableB { - - @Id - @Column(name = "table_b_id") - private Long tableBId; - - @Column(name = "table_a_id", insertable = false, updatable = false) - private Long tableAId; - - @Temporal(TemporalType.DATE) - @Column(name = "table_b_date") - private Date tableBDate; - - @ManyToOne - @JoinColumn(name = "table_a_id") - private TableA tableA; - - @OneToMany(mappedBy = "tableB") - private Set tableCs; - - - public TableB() { - } - - public Long getTableBId() { - return this.tableBId; - } - - public void setTableBId(Long _tableBId_) { - this.tableBId = _tableBId_; - } - - public Long getTableAId() { - return this.tableAId; - } - - public void setTableAId(Long _tableAId_) { - this.tableAId = _tableAId_; - } - - public Date getTableBDate() { - return this.tableBDate; - } - - public void setTableBDate(Date _tableBDate_) { - this.tableBDate = _tableBDate_; - } - - public TableA getTableA() { - return tableA; - } - - public void setTableA(TableA tableA) { - this.tableA = tableA; - } - - public Set getTableCs() { - return tableCs; - } - - public void setTableCs(Set tableCs) { - this.tableCs = tableCs; - } - - } - - @Entity(name = "TableC") - public static class TableC { - - @Id - @Column(name = "table_c_id") - private Long tableCId; - - @Column(name = "table_b_id", insertable = false, updatable = false) - private Long tableBId; - - @Column(name = "table_c_boolean") - private Boolean tableCBoolean; - - @ManyToOne - @JoinColumn(name = "table_b_id") - private TableB tableB; - - public TableC() { - } - - public Long getTableCId() { - return this.tableCId; - } - - public void setTableCId(Long tableCId) { - this.tableCId = tableCId; - } - - public Long getTableBId() { - return this.tableBId; - } - - public void setTableBId(Long tableBId) { - this.tableBId = tableBId; - } - - public Boolean getTableCBoolean() { - return this.tableCBoolean; - } - - public void setTableCBoolean(Boolean tableCBoolean) { - this.tableCBoolean = tableCBoolean; - } - - public TableB getTableB() { - return tableB; - } - - public void setTableB(TableB tableB) { - this.tableB = tableB; - } - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java deleted file mode 100644 index 1fd0d18b48..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/annotations/naturalid/NaturalIdOnSingleManyToOneTest.java +++ /dev/null @@ -1,132 +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 . - */ -package org.hibernate.test.annotations.naturalid; - -import java.util.List; - -import org.junit.After; -import org.junit.Test; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.cfg.Configuration; -import org.hibernate.metadata.ClassMetadata; -import org.hibernate.stat.Statistics; -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - * Test case for NaturalId annotation. See ANN-750. - * - * @author Emmanuel Bernard - * @author Hardy Ferentschik - */ -@SuppressWarnings("unchecked") -@TestForIssue( jiraKey = "ANN-750" ) -public class NaturalIdOnSingleManyToOneTest extends BaseCoreFunctionalTestCase { - - @After - public void cleanupData() { - super.cleanupCache(); - Session s = sessionFactory().openSession(); - s.beginTransaction(); - s.createQuery( "delete NaturalIdOnManyToOne" ).executeUpdate(); - s.createQuery( "delete Citizen" ).executeUpdate(); - s.createQuery( "delete State" ).executeUpdate(); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testMappingProperties() { - log.warn("Commented out test"); - - ClassMetadata metaData = sessionFactory().getClassMetadata( - NaturalIdOnManyToOne.class - ); - assertTrue( - "Class should have a natural key", metaData - .hasNaturalIdentifier() - ); - int[] propertiesIndex = metaData.getNaturalIdentifierProperties(); - assertTrue( "Wrong number of elements", propertiesIndex.length == 1 ); - } - - @Test - public void testManyToOneNaturalIdCached() { - NaturalIdOnManyToOne singleManyToOne = new NaturalIdOnManyToOne(); - Citizen c1 = new Citizen(); - c1.setFirstname( "Emmanuel" ); - c1.setLastname( "Bernard" ); - c1.setSsn( "1234" ); - - State france = new State(); - france.setName( "Ile de France" ); - c1.setState( france ); - - singleManyToOne.setCitizen( c1 ); - - Session s = openSession(); - Transaction tx = s.beginTransaction(); - s.persist( france ); - s.persist( c1 ); - s.persist( singleManyToOne ); - tx.commit(); - s.close(); - - s.getSessionFactory().getCache().evictNaturalIdRegions(); - Statistics stats = sessionFactory().getStatistics(); - stats.setStatisticsEnabled( true ); - stats.clear(); - assertEquals( "NaturalId cache puts should be zero", 0, stats.getNaturalIdCachePutCount() ); - assertEquals( "NaturalId cache hits should be zero", 0, stats.getNaturalIdCacheHitCount() ); - assertEquals( "NaturalId Cache Puts", 0, stats.getNaturalIdCachePutCount() ); - assertEquals( "NaturalId cache misses should be zero", 0, stats.getNaturalIdCacheMissCount() ); - - s = openSession(); - tx = s.beginTransaction(); - Criteria criteria = s.createCriteria( NaturalIdOnManyToOne.class ); - criteria.add( Restrictions.naturalId().set( "citizen", c1 ) ); - criteria.setCacheable( true ); - - // first query - List results = criteria.list(); - assertEquals( 1, results.size() ); - assertEquals( "NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount() ); - assertEquals( "NaturalId Cache Misses", 1, stats.getNaturalIdCacheMissCount() ); - assertEquals( "NaturalId Cache Puts", 2, stats.getNaturalIdCachePutCount() ); // one for Citizen, one for NaturalIdOnManyToOne - assertEquals( "NaturalId Cache Queries", 1, stats.getNaturalIdQueryExecutionCount() ); - - // query a second time - result should be in session cache - criteria.list(); - assertEquals( "NaturalId Cache Hits", 0, stats.getNaturalIdCacheHitCount() ); - assertEquals( "NaturalId Cache Misses", 1, stats.getNaturalIdCacheMissCount() ); - assertEquals( "NaturalId Cache Puts", 2, stats.getNaturalIdCachePutCount() ); - assertEquals( "NaturalId Cache Queries", 1, stats.getNaturalIdQueryExecutionCount() ); - - // cleanup - tx.rollback(); - s.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Citizen.class, State.class, - NaturalIdOnManyToOne.class - }; - } - - @Override - protected void configure(Configuration cfg) { - cfg.setProperty( "hibernate.cache.use_query_cache", "true" ); - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/annotations/onetomany/OerderByNullsFirstLastTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/annotations/onetomany/OerderByNullsFirstLastTest.java deleted file mode 100644 index 122e2b72ee..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/annotations/onetomany/OerderByNullsFirstLastTest.java +++ /dev/null @@ -1,86 +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.annotations.onetomany; - -import java.util.Iterator; - -import org.hibernate.NullPrecedence; -import org.hibernate.dialect.H2Dialect; -import org.hibernate.dialect.MySQLDialect; -import org.hibernate.dialect.SQLServer2008Dialect; - -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Assert; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil2.inSession; - -/** - * @author Andrea Boriero - */ -public class OerderByNullsFirstLastTest extends BaseCoreFunctionalTestCase { - - @Test - @TestForIssue(jiraKey = "HHH-465") - @RequiresDialect(value = { H2Dialect.class, MySQLDialect.class, SQLServer2008Dialect.class }, - comment = "By default H2 places NULL values first, so testing 'NULLS LAST' expression. " + - "For MySQL and SQL Server 2008 testing overridden Dialect#renderOrderByElement(String, String, String, NullPrecedence) method. " + - "MySQL and SQL Server 2008 does not support NULLS FIRST / LAST syntax at the moment, so transforming the expression to 'CASE WHEN ...'.") - public void testCriteriaNullsFirstLast() { - inSession( session -> { - try{ - // Populating database with test data. - session.getTransaction().begin(); - Zoo zoo1 = new Zoo( null ); - Zoo zoo2 = new Zoo( "Warsaw ZOO" ); - session.persist( zoo1 ); - session.persist( zoo2 ); - session.getTransaction().commit(); - - session.clear(); - - session.getTransaction().begin(); - - Criteria criteria = session.createCriteria( Zoo.class ); - criteria.addOrder( org.hibernate.criterion.Order.asc( "name" ).nulls( NullPrecedence.LAST ) ); - Iterator iterator = (Iterator) criteria.list().iterator(); - - Assert.assertEquals( zoo2.getName(), iterator.next().getName() ); - Assert.assertNull( iterator.next().getName() ); - session.getTransaction().commit(); - - session.clear(); - - // Cleanup data. - session.getTransaction().begin(); - session.delete( zoo1 ); - session.delete( zoo2 ); - session.getTransaction().commit(); - } - catch (Exception e){ - if(session.getTransaction().isActive()){ - session.getTransaction().rollback(); - } - throw e; - } - } ); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - Order.class, OrderItem.class, Zoo.class, Tiger.class, - Monkey.class, Visitor.class, Box.class, Item.class, - BankAccount.class, Transaction.class, - Comment.class, Forum.class, Post.class, User.class, - Asset.class, Computer.class, Employee.class, - A.class, B.class, C.class - }; - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/ComplexJoinAliasTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/ComplexJoinAliasTest.java deleted file mode 100644 index 1bf95d88d5..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/ComplexJoinAliasTest.java +++ /dev/null @@ -1,105 +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 . - */ -package org.hibernate.test.criteria; - -import java.util.Arrays; - -import org.junit.Test; - -import org.hibernate.Session; -import org.hibernate.criterion.Restrictions; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import static org.junit.Assert.assertEquals; - -/** - * Hibernate generates the wrong alias on a Criteria query involving a join - * on a composite identifier. For example, in the test below without the fix - * to JoinWalker, it generates this SQL: - * - * - * select - * this_.role_code as role1_0_1_, - * this_.is_deleted as is2_0_1_, - * this_.record_version as record3_0_1_, - * complexjoi3_.code as code1_0_, - * complexjoi3_.is_deleted as is2_1_0_, - * complexjoi3_.record_version as record3_1_0_ - * from - * list_action_roles this_ - * left outer join - * roles complexjoi3_ - * on this_.role_code=complexjoi3_.code - * where - * this_.is_deleted=? - * and complexjoi1_.is_deleted=? - * - * - * Which results in this error from the SQL server: - * - * - * Unknown column 'complexjoi1_.is_deleted' in 'where clause' - * - * - * Analysis of the problem: - * - * The entity persister class with the composite identifier has a fake - * property for it, called "_identifierMapper" (see HbmBinder.bindCompositeId() - * and similarly in Annotations). This property name ends up in the path - * used by JoinWalker.walkEntityTree() when it calls walkComponentTree(). - * However that path is used by CriteriaJoinWalker.generateTableAlias() - * to look up the correct criteria (and hence the alias) from the - * translator, a CriteriaQueryTranslator. - * - * The alias was created in CriteriaQueryTranslator.createCriteriaSQLAliasMap - * for a Criteria without this extra _identifierMapper path component. - * So when CriteriaJoinWalker tries to use the path with _identifierMapper - * to look up the criteria to find the correct alias to use, in - * generateTableAlias(), it doesn't find one, so it generates a new alias. - * - * That new alias no longer matches the one that will be rendered out in - * the WHERE clause, so the WHERE clause will refer to table names using - * aliases that are not used anywhere else in the query, and the SQL server - * will fail to parse the statement. - * - * The solution appears to be to exclude "_identifierMapper" components in - * the alias path when building it. I don't know what other implications - * that might have, but it seems like an implementation nastiness that - * shouldn't be exposed. - * - * @author Chris Wilson - * @link https://hibernate.onjira.com/browse/HHH-4630 - */ - -public class ComplexJoinAliasTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { - ListActionRole.class, - Role.class - }; - } - - @Test - public void testCriteriaThroughCompositeId() throws Exception { - Session session = openSession(); - - Criteria listActionRoles = session.createCriteria( ListActionRole.class ); - listActionRoles.add( Restrictions.eq( "isDeleted", false ) ); - - Criteria roles = listActionRoles.createCriteria( "role" ); - roles.add( Restrictions.eq( "isDeleted", false ) ); - - assertEquals( - Arrays.asList( new ListActionRole[] { } ), - listActionRoles.list() - ); - - session.close(); - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/CriteriaAliasFetchTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/CriteriaAliasFetchTest.java deleted file mode 100644 index b848df6316..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/CriteriaAliasFetchTest.java +++ /dev/null @@ -1,142 +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 . - */ -package org.hibernate.test.criteria; - -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.util.List; - -import jakarta.persistence.Entity; -import jakarta.persistence.FetchType; -import jakarta.persistence.Id; -import jakarta.persistence.ManyToOne; -import jakarta.persistence.OneToMany; - -import org.hibernate.FetchMode; -import org.hibernate.boot.MetadataSources; -import org.hibernate.criterion.CriteriaSpecification; -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; - -/** - * @author Thomas Reinhardt - */ -public class CriteriaAliasFetchTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - protected void applyMetadataSources(MetadataSources sources) { - super.applyMetadataSources( sources ); - sources.addAnnotatedClass( Cat.class ); - sources.addAnnotatedClass( Kitten.class ); - } - - @Override - protected void cleanupTest() throws Exception { - doInHibernate( this::sessionFactory, session -> { - session.createQuery( "delete from " + Kitten.class.getName() ).executeUpdate(); - session.createQuery( "delete from " + Cat.class.getName() ).executeUpdate(); - } ); - } - - @Override - protected void prepareTest() throws Exception { - doInHibernate( this::sessionFactory, session -> { - - // make 5 cats with 3 kittens each - for ( int i = 0; i < 5; i++ ) { - Cat cat = new Cat(); - cat.catId = i; - cat.name = "cat_" + i; - session.save( cat ); - for ( int j = 0; j < 3; j++ ) { - Kitten k = new Kitten(); - k.kittenId = 5 * i + j; - k.name = "kitty_" + i + "_" + j; - k.cat = cat; - cat.kittens.add( k ); - session.save( k ); - } - } - - session.flush(); - session.clear(); - } ); - } - - public void assertOnlyOneSelect(Criteria criteria) { - sessionFactory().getStatistics().setStatisticsEnabled( true ); - sessionFactory().getStatistics().clear(); - - try { - List cats = criteria.list(); - - assertEquals( 5, cats.size() ); - - for ( Cat cat : cats ) { - assertEquals( 3, cat.kittens.size() ); - - for ( Kitten kitten : cat.kittens ) { - assertNotNull( kitten.cat ); - } - } - - assertEquals( "too many statements generated", 1, sessionFactory().getStatistics().getPrepareStatementCount() ); - } - finally { - sessionFactory().getStatistics().setStatisticsEnabled( false ); - } - } - - @Test - @TestForIssue(jiraKey = "HHH-7842") - public void testFetchWithAlias() { - doInHibernate( this::sessionFactory, session -> { - - assertOnlyOneSelect( session.createCriteria( Cat.class, "c" ) - .setFetchMode( "c.kittens", FetchMode.JOIN ) - .setResultTransformer( CriteriaSpecification.DISTINCT_ROOT_ENTITY ) ); - - } ); - } - - @Test - public void testFixForHHH7842DoesNotBreakOldBehavior() { - doInHibernate( this::sessionFactory, session -> { - - assertOnlyOneSelect( session.createCriteria( Cat.class ) - .setFetchMode( "kittens", FetchMode.JOIN ) - .setResultTransformer( CriteriaSpecification.DISTINCT_ROOT_ENTITY ) ); - - } ); - } - - @Entity(name = "Cat") - public static class Cat { - - @Id - public Integer catId; - public String name; - - @OneToMany(mappedBy = "cat") - public java.util.Set kittens = new java.util.HashSet<>(); - } - - @Entity(name = "Kitten") - public static class Kitten { - - @Id - public Integer kittenId; - public String name; - - @ManyToOne(fetch = FetchType.LAZY) - public Cat cat; - } - -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/CriteriaLockingTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/CriteriaLockingTest.java deleted file mode 100644 index ccb9288980..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/CriteriaLockingTest.java +++ /dev/null @@ -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 . - */ -package org.hibernate.test.criteria; - -import org.hibernate.LockMode; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.internal.CoreMessageLogger; -import org.hibernate.loader.Loader; - -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 org.junit.runner.RunWith; - -import org.jboss.byteman.contrib.bmunit.BMRule; -import org.jboss.byteman.contrib.bmunit.BMRules; -import org.jboss.byteman.contrib.bmunit.BMUnitRunner; -import org.jboss.logging.Logger; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - * @author Sanne Grinovero - * @author Andrea Boriero - */ -@TestForIssue(jiraKey = "HHH-8788") -@RunWith(BMUnitRunner.class) -public class CriteriaLockingTest extends BaseCoreFunctionalTestCase { - - @Rule - public LoggerInspectionRule logInspection = new LoggerInspectionRule( - Logger.getMessageLogger(CoreMessageLogger.class, Loader.class.getName()) - ); - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {Bid.class, Item.class}; - } - - @Test - @BMRules(rules = { - @BMRule(targetClass = "org.hibernate.dialect.Dialect", - targetMethod = "useFollowOnLocking", - action = "return true", - name = "H2DialectUseFollowOnLocking") - }) - public void testSetLockModeNONEDoNotLogAWarnMessageWhenTheDialectUseFollowOnLockingIsTrue() { - buildSessionFactory(); - Triggerable triggerable = logInspection.watchForLogMessages( "HHH000444" ); - - final Session s = openSession(); - final Transaction tx = s.beginTransaction(); - - Item item = new Item(); - item.name = "ZZZZ"; - s.persist( item ); - - s.flush(); - - Criteria criteria = s.createCriteria( Item.class ) - .setLockMode( LockMode.NONE ); - - criteria.list(); - - tx.rollback(); - s.close(); - - releaseSessionFactory(); - - assertFalse( triggerable.wasTriggered() ); - } - - @Test - @BMRules(rules = { - @BMRule(targetClass = "org.hibernate.dialect.Dialect", - targetMethod = "useFollowOnLocking", - action = "return true", - name = "H2DialectUseFollowOnLocking") - }) - public void testSetLockModeDifferentFromNONELogAWarnMessageWhenTheDialectUseFollowOnLockingIsTrue() { - buildSessionFactory(); - Triggerable triggerable = logInspection.watchForLogMessages( "HHH000444" ); - - final Session s = openSession(); - final Transaction tx = s.beginTransaction(); - - Item item = new Item(); - item.name = "ZZZZ"; - s.persist( item ); - - s.flush(); - - Criteria criteria = s.createCriteria( Item.class ) - .setLockMode( LockMode.OPTIMISTIC ); - - criteria.list(); - - tx.rollback(); - s.close(); - releaseSessionFactory(); - - assertTrue( triggerable.wasTriggered() ); - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/CriteriaOrderByTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/CriteriaOrderByTest.java deleted file mode 100644 index 0775092cb1..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/CriteriaOrderByTest.java +++ /dev/null @@ -1,115 +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 . - */ -package org.hibernate.test.criteria; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.criterion.Projections; -import org.hibernate.sql.JoinType; -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.hibernate.transform.ResultTransformer; -import org.junit.Assert; -import org.junit.Test; - -import java.util.List; - -/** - * @author tknowlton at iamhisfriend dot org - */ -public class CriteriaOrderByTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { Bid.class, Item.class }; - } - - @Test - @TestForIssue(jiraKey = "HHH-7116") - public void testCriteriaOrderBy() { - final Session s = openSession(); - final Transaction tx = s.beginTransaction(); - - Item item; - Bid bid; - - item = new Item(); - item.name = "ZZZZ"; - s.persist( item ); - - bid = new Bid(); - bid.amount = 444.44f; - bid.item = item; - s.persist( bid ); - - item = new Item(); - item.name = "AAAA"; - s.persist( item ); - - bid = new Bid(); - bid.amount = 222.22f; - bid.item = item; - s.persist( bid ); - - item = new Item(); - item.name = "MMMM"; - s.persist( item ); - - bid = new Bid(); - bid.amount = 999.99f; - bid.item = item; - s.persist( bid ); - - s.flush(); - - // For each item, ordered by name, show all bids made by bidders on this item. - // The joined collections item.bids and bidder.bids have orderings specified on the mappings. - // For some reason, the association mappings' ordering specifications are not honored if default (INNER) join - // type is used. - final Criteria criteria = s - .createCriteria( Item.class ) - .addOrder( org.hibernate.criterion.Order.asc( "this.name" ) ) - .createAlias( "this.bids", "i_bid", JoinType.LEFT_OUTER_JOIN ) - .setProjection( - Projections.projectionList().add( Projections.property( "this.name" ), "item_name" ) - .add( Projections.property( "i_bid.amount" ), "bid_amount" ) ) - .setResultTransformer( new ResultTransformer() { - boolean first = true; - Object[] previous; - - @Override - public Object transformTuple(Object[] tuple, String[] aliases) { - if ( first ) { - first = false; - previous = tuple; - } - else { - final String previousName = (String) previous[0]; - final String name = (String) tuple[0]; - - Assert.assertTrue( - "The resultset tuples should be ordered by item name, as specified on the Criteria", - previousName.compareTo( name ) < 1 ); - - previous = tuple; - } - - return tuple; - } - - @Override - public List transformList(List collection) { - return collection; - } - } ); - - criteria.list(); - - tx.rollback(); - s.close(); - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/CriteriaQueryTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/CriteriaQueryTest.java deleted file mode 100644 index 9c80852157..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/CriteriaQueryTest.java +++ /dev/null @@ -1,2111 +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 . - */ -package org.hibernate.test.criteria; - -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.hibernate.FetchMode; -import org.hibernate.Hibernate; -import org.hibernate.JDBCException; -import org.hibernate.QueryException; -import org.hibernate.ScrollableResults; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.criterion.DetachedCriteria; -import org.hibernate.criterion.Example; -import org.hibernate.criterion.MatchMode; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.Projection; -import org.hibernate.criterion.Projections; -import org.hibernate.criterion.Property; -import org.hibernate.criterion.Restrictions; -import org.hibernate.criterion.Subqueries; -import org.hibernate.dialect.Oracle8iDialect; -import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.dialect.SybaseASE15Dialect; -import org.hibernate.exception.SQLGrammarException; -import org.hibernate.internal.util.SerializationHelper; -import org.hibernate.transform.Transformers; -import org.hibernate.type.StandardBasicTypes; -import org.hibernate.type.Type; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.hibernate.test.hql.Animal; -import org.hibernate.test.hql.Reptile; -import org.hibernate.test.util.jdbc.PreparedStatementSpyConnectionProvider; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -/** - * @author Gavin King - * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) - */ -@RequiresDialectFeature({ - DialectChecks.SupportsSequences.class, - DialectChecks.SupportsJdbcDriverProxying.class -}) -public class CriteriaQueryTest extends BaseNonConfigCoreFunctionalTestCase { - - private PreparedStatementSpyConnectionProvider connectionProvider = new PreparedStatementSpyConnectionProvider( true, false ); - - @Override - public String[] getMappings() { - return new String[] { - "criteria/Enrolment.hbm.xml", "criteria/Foo.hbm.xml", "hql/Animal.hbm.xml", "criteria/Person.hbm.xml" - }; - } - - @Override - protected void addSettings(Map settings) { - settings.put( AvailableSettings.USE_QUERY_CACHE, "true" ); - settings.put( - AvailableSettings.CACHE_REGION_PREFIX, - "criteriaquerytest" - ); - settings.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, "true" ); - settings.put( AvailableSettings.GENERATE_STATISTICS, "true" ); - settings.put( - AvailableSettings.CONNECTION_PROVIDER, - connectionProvider - ); - } - - @Override - protected void releaseResources() { - super.releaseResources(); - connectionProvider.stop(); - } - - @Test - @TestForIssue( jiraKey = "HHH-7209" ) - public void testVarargJunctionSyntax() { - Session session = openSession(); - session.beginTransaction(); - session.createCriteria( Course.class ) - .add( - Restrictions.and( - Property.forName( "description" ).like( "Hibernate%" ), - Property.forName( "description" ).like( "%ORM%" ) - ) - ) - .list(); - - session.createCriteria( Course.class ) - .add( - Restrictions.and( - Property.forName( "description" ).like( "Hibernate%" ), - Restrictions.or( - Property.forName( "description" ).like( "%ORM%" ), - Property.forName( "description" ).like( "%Search%" ) - ) - - ) - ) - .list(); - - session.getTransaction().commit(); - session.close(); - } - - @Test - public void testEscapeCharacter() { - Session session = openSession(); - Transaction t = session.beginTransaction(); - Course c1 = new Course(); - c1.setCourseCode( "course-1" ); - c1.setDescription( "%1" ); - Course c2 = new Course(); - c2.setCourseCode( "course-2" ); - c2.setDescription( "%2" ); - Course c3 = new Course(); - c3.setCourseCode( "course-3" ); - c3.setDescription( "control" ); - session.persist( c1 ); - session.persist( c2 ); - session.persist( c3 ); - session.flush(); - session.clear(); - - // finds all courses which have a description equal to '%1' - Course example = new Course(); - example.setDescription( "&%1" ); - List result = session.createCriteria( Course.class ) - .add( Example.create( example ).ignoreCase().enableLike().setEscapeCharacter( new Character( '&' ) ) ) - .list(); - assertEquals( 1, result.size() ); - // finds all courses which contain '%' as the first char in the description - example.setDescription( "&%%" ); - result = session.createCriteria( Course.class ) - .add( Example.create( example ).ignoreCase().enableLike().setEscapeCharacter( new Character( '&' ) ) ) - .list(); - assertEquals( 2, result.size() ); - - session.createQuery( "delete Course" ).executeUpdate(); - t.commit(); - session.close(); - } - - @Test - public void testScrollCriteria() { - Session session = openSession(); - Transaction t = session.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - session.persist(course); - session.flush(); - session.clear(); - ScrollableResults sr = session.createCriteria(Course.class).scroll(); - assertTrue( sr.next() ); - course = (Course) sr.get(0); - assertNotNull(course); - sr.close(); - session.delete(course); - - t.commit(); - session.close(); - } - - @Test - @SkipForDialect( value = SybaseASE15Dialect.class, strictMatching = true, jiraKey = "HHH-3032", comment = "I was told this is fixed in Sybase ASE 15.7") - public void testSubselect() { - Session session = openSession(); - Transaction t = session.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - session.persist(course); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - session.persist(gavin); - - Enrolment enrolment2 = new Enrolment(); - enrolment2.setCourse(course); - enrolment2.setCourseCode(course.getCourseCode()); - enrolment2.setSemester((short) 3); - enrolment2.setYear((short) 1998); - enrolment2.setStudent(gavin); - enrolment2.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add(enrolment2); - session.persist(enrolment2); - - DetachedCriteria dc = DetachedCriteria.forClass(Student.class) - .add( Property.forName("studentNumber").eq( new Long(232) ) ) - .setProjection( Property.forName("name") ); - - session.createCriteria(Student.class) - .add( Subqueries.propertyEqAll("name", dc) ) - .list(); - - session.createCriteria(Student.class) - .add( Subqueries.exists(dc) ) - .list(); - - session.createCriteria(Student.class) - .add( Property.forName("name").eqAll(dc) ) - .list(); - - session.createCriteria(Student.class) - .add( Subqueries.in("Gavin King", dc) ) - .list(); - - DetachedCriteria dc2 = DetachedCriteria.forClass(Student.class, "st") - .add( Property.forName("st.studentNumber").eqProperty("e.studentNumber") ) - .setProjection( Property.forName("name") ); - - session.createCriteria(Enrolment.class, "e") - .add( Subqueries.eq("Gavin King", dc2) ) - .list(); - - DetachedCriteria dc3 = DetachedCriteria.forClass(Student.class, "st") - .createCriteria("enrolments") - .createCriteria("course") - .add( Property.forName("description").eq("Hibernate Training") ) - .setProjection( Property.forName("st.name") ); - - session.createCriteria(Enrolment.class, "e") - .add( Subqueries.eq("Gavin King", dc3) ) - .list(); - - DetachedCriteria dc4 = DetachedCriteria.forClass(Student.class, "st") - .setProjection( Property.forName("name").as( "stname" ) ); - - dc4.getExecutableCriteria( session ).list(); - - // SQL Server and Oracle doesn't normally support ORDER BY in subqueries... - if ( !( getDialect() instanceof SQLServerDialect ) && - ! ( getDialect() instanceof Oracle8iDialect ) ) { - dc4.getExecutableCriteria(session).addOrder(Order.asc("stname")).list(); - } - - session.createCriteria(Enrolment.class, "e") - .add( Subqueries.eq("Gavin King", dc4) ) - .list(); - - session.delete(enrolment2); - session.delete(gavin); - session.delete(course); - t.commit(); - session.close(); - } - - @Test - @SkipForDialect( value = SybaseASE15Dialect.class, strictMatching = true, jiraKey = "HHH-3032", comment = "I was told this is fixed in Sybase ASE 15.7") - public void testSubselectWithComponent() { - Session session = openSession(); - Transaction t = session.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - session.persist(course); - - CityState odessaWa = new CityState( "Odessa", "WA" ); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setCityState( odessaWa ); - session.persist(gavin); - - Enrolment enrolment2 = new Enrolment(); - enrolment2.setCourse(course); - enrolment2.setCourseCode(course.getCourseCode()); - enrolment2.setSemester((short) 3); - enrolment2.setYear((short) 1998); - enrolment2.setStudent(gavin); - enrolment2.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add(enrolment2); - session.persist(enrolment2); - - DetachedCriteria dc = DetachedCriteria.forClass(Student.class) - .add( Property.forName("cityState").eq( odessaWa ) ) - .setProjection( Property.forName("cityState") ); - - session.createCriteria(Student.class) - .add( Subqueries.exists(dc) ) - .list(); - t.commit(); - session.close(); - - session = openSession(); - t = session.beginTransaction(); - try { - session.createCriteria(Student.class) - .add( Subqueries.propertyEqAll("cityState", dc) ) - .list(); - fail( "should have failed because cannot compare subquery results with multiple columns" ); - } - catch ( QueryException ex ) { - // expected - } - finally { - t.rollback(); - session.close(); - } - - session = openSession(); - t = session.beginTransaction(); - try { - session.createCriteria(Student.class) - .add( Property.forName("cityState").eqAll(dc) ) - .list(); - fail( "should have failed because cannot compare subquery results with multiple columns" ); - } - catch ( QueryException ex ) { - // expected - } - finally { - t.rollback(); - session.close(); - } - - session = openSession(); - t = session.beginTransaction(); - try { - session.createCriteria(Student.class) - .add( Subqueries.in( odessaWa, dc) ) - .list(); - fail( "should have failed because cannot compare subquery results with multiple columns" ); - } - catch ( JDBCException ex ) { - // expected - } - finally { - t.rollback(); - session.close(); - } - - session = openSession(); - t = session.beginTransaction(); - DetachedCriteria dc2 = DetachedCriteria.forClass(Student.class, "st1") - .add( Property.forName("st1.cityState").eqProperty("st2.cityState") ) - .setProjection( Property.forName("cityState") ); - try { - session.createCriteria(Student.class, "st2") - .add( Subqueries.eq( odessaWa, dc2) ) - .list(); - fail( "should have failed because cannot compare subquery results with multiple columns" ); - } - catch ( JDBCException ex ) { - // expected - } - finally { - t.rollback(); - session.close(); - } - - session = openSession(); - t = session.beginTransaction(); - DetachedCriteria dc3 = DetachedCriteria.forClass(Student.class, "st") - .createCriteria("enrolments") - .createCriteria("course") - .add( Property.forName("description").eq("Hibernate Training") ) - .setProjection( Property.forName("st.cityState") ); - try { - session.createCriteria(Enrolment.class, "e") - .add( Subqueries.eq( odessaWa, dc3) ) - .list(); - fail( "should have failed because cannot compare subquery results with multiple columns" ); - } - catch ( JDBCException ex ) { - // expected - } - finally { - t.rollback(); - session.close(); - } - - session = openSession(); - t = session.beginTransaction(); - session.delete(enrolment2); - session.delete(gavin); - session.delete(course); - t.commit(); - session.close(); - - } - - @Test - public void testDetachedCriteria() { - DetachedCriteria dc = DetachedCriteria.forClass(Student.class) - .add( Property.forName("name").eq("Gavin King") ) - .addOrder( Order.asc("studentNumber") ) - .setProjection( Property.forName("studentNumber") ); - - byte[] bytes = SerializationHelper.serialize(dc); - - dc = (DetachedCriteria) SerializationHelper.deserialize( bytes ); - - Session session = openSession(); - Transaction t = session.beginTransaction(); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - Student bizarroGavin = new Student(); - bizarroGavin.setName("Gavin King"); - bizarroGavin.setStudentNumber(666); - session.persist(bizarroGavin); - session.persist(gavin); - - List result = dc.getExecutableCriteria(session) - .setMaxResults(3) - .list(); - - assertEquals( result.size(), 2 ); - assertEquals( result.get(0), new Long(232) ); - assertEquals( result.get(1), new Long(666) ); - - session.delete(gavin); - session.delete(bizarroGavin); - t.commit(); - session.close(); - } - - @Test - public void testDetachedCriteriaTimeout() { - doInHibernate( this::sessionFactory, session -> { - DetachedCriteria dc = DetachedCriteria.forClass(Student.class) - .setTimeout( 100 ); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - - session.persist(gavin); - session.flush(); - - connectionProvider.clear(); - List result = dc.getExecutableCriteria(session).list(); - PreparedStatement preparedStatement = connectionProvider.getPreparedStatements().get( 0 ); - try { - verify(preparedStatement, times(1)).setQueryTimeout( 100 ); - } - catch (SQLException e) { - fail(e.getMessage()); - } - - assertEquals( result.size(), 1 ); - - session.delete(gavin); - } ); - } - - @Test - public void testProjectionCache() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.save(course); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(666); - s.save(gavin); - - Student xam = new Student(); - xam.setName("Max Rydahl Andersen"); - xam.setStudentNumber(101); - s.save(xam); - - Enrolment enrolment1 = new Enrolment(); - enrolment1.setCourse(course); - enrolment1.setCourseCode(course.getCourseCode()); - enrolment1.setSemester((short) 1); - enrolment1.setYear((short) 1999); - enrolment1.setStudent(xam); - enrolment1.setStudentNumber(xam.getStudentNumber()); - xam.getEnrolments().add(enrolment1); - s.save(enrolment1); - - Enrolment enrolment2 = new Enrolment(); - enrolment2.setCourse(course); - enrolment2.setCourseCode(course.getCourseCode()); - enrolment2.setSemester((short) 3); - enrolment2.setYear((short) 1998); - enrolment2.setStudent(gavin); - enrolment2.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add(enrolment2); - s.save(enrolment2); - - List list = s.createCriteria(Enrolment.class) - .createAlias( "student", "s" ) - .createAlias( "course", "c" ) - .add( Restrictions.isNotEmpty( "s.enrolments" ) ) - .setProjection( - Projections.projectionList() - .add( Projections.property( "s.name" ) ) - .add( Projections.property( "c.description" ) ) - ) - .setCacheable( true ) - .list(); - - assertEquals( list.size(), 2 ); - assertEquals( ( (Object[]) list.get(0) ).length, 2 ); - assertEquals( ( (Object[]) list.get(1) ).length, 2 ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - - s.createCriteria(Enrolment.class) - .createAlias( "student", "s" ) - .createAlias( "course", "c" ) - .add( Restrictions.isNotEmpty( "s.enrolments" ) ) - .setProjection( - Projections.projectionList() - .add( Projections.property( "s.name" ) ) - .add( Projections.property( "c.description" ) ) - ) - .setCacheable( true ) - .list(); - - assertEquals( list.size(), 2 ); - assertEquals( ( (Object[]) list.get(0) ).length, 2 ); - assertEquals( ( (Object[]) list.get(1) ).length, 2 ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - - s.createCriteria(Enrolment.class) - .createAlias( "student", "s" ) - .createAlias( "course", "c" ) - .add( Restrictions.isNotEmpty( "s.enrolments" ) ) - .setProjection( - Projections.projectionList() - .add( Projections.property( "s.name" ) ) - .add( Projections.property( "c.description" ) ) - ) - .setCacheable( true ) - .list(); - - assertEquals( list.size(), 2 ); - assertEquals( ( (Object[]) list.get(0) ).length, 2 ); - assertEquals( ( (Object[]) list.get(1) ).length, 2 ); - - s.delete(enrolment1); - s.delete(enrolment2); - s.delete(course); - s.delete(gavin); - s.delete(xam); - - t.commit(); - s.close(); - } - - @Test - public void testProjections() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.save(course); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(667); - s.save(gavin); - - Student xam = new Student(); - xam.setName("Max Rydahl Andersen"); - xam.setStudentNumber(101); - s.save(xam); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 1); - enrolment.setYear((short) 1999); - enrolment.setStudent(xam); - enrolment.setStudentNumber(xam.getStudentNumber()); - xam.getEnrolments().add(enrolment); - s.save(enrolment); - - enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add(enrolment); - s.save(enrolment); - - //s.flush(); - - Long count = (Long) s.createCriteria(Enrolment.class) - .setProjection( Projections.count("studentNumber").setDistinct() ) - .uniqueResult(); - assertEquals(count, new Long(2)); - - count = (Long) s.createCriteria(Enrolment.class) - .setProjection( Projections.countDistinct("studentNumber") ) - .uniqueResult(); - assertEquals(count, new Long(2)); - - count = (Long) s.createCriteria(Enrolment.class) - .setProjection( Projections.countDistinct("courseCode").as( "cnt" ) ) - .uniqueResult(); - assertEquals(count, new Long(1)); - - Object object = s.createCriteria(Enrolment.class) - .setProjection( Projections.projectionList() - .add( Projections.count("studentNumber") ) - .add( Projections.max("studentNumber") ) - .add( Projections.min("studentNumber") ) - .add( Projections.avg("studentNumber") ) - ) - .uniqueResult(); - Object[] result = (Object[])object; - - assertEquals(new Long(2),result[0]); - assertEquals(new Long(667),result[1]); - assertEquals(new Long(101),result[2]); - assertEquals( 384.0, ( (Double) result[3] ).doubleValue(), 0.01 ); - - - List resultWithMaps = s.createCriteria(Enrolment.class) - .setProjection( Projections.distinct( Projections.projectionList() - .add( Projections.property("studentNumber"), "stNumber" ) - .add( Projections.property("courseCode"), "cCode" ) ) - ) - .add( Restrictions.gt( "studentNumber", new Long(665) ) ) - .add( Restrictions.lt( "studentNumber", new Long(668) ) ) - .addOrder( Order.asc("stNumber") ) - .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP) - .list(); - - assertEquals(1, resultWithMaps.size()); - Map m1 = (Map) resultWithMaps.get(0); - - assertEquals(new Long(667), m1.get("stNumber")); - assertEquals(course.getCourseCode(), m1.get("cCode")); - - resultWithMaps = s.createCriteria(Enrolment.class) - .setProjection( Projections.property("studentNumber").as("stNumber") ) - .addOrder( Order.desc("stNumber") ) - .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP) - .list(); - - assertEquals(2, resultWithMaps.size()); - Map m0 = (Map) resultWithMaps.get(0); - m1 = (Map) resultWithMaps.get(1); - - assertEquals(new Long(101), m1.get("stNumber")); - assertEquals(new Long(667), m0.get("stNumber")); - - - List resultWithAliasedBean = s.createCriteria(Enrolment.class) - .createAlias("student", "st") - .createAlias("course", "co") - .setProjection( Projections.projectionList() - .add( Projections.property("st.name"), "studentName" ) - .add( Projections.property("co.description"), "courseDescription" ) - ) - .addOrder( Order.desc("studentName") ) - .setResultTransformer( Transformers.aliasToBean(StudentDTO.class) ) - .list(); - - assertEquals(2, resultWithAliasedBean.size()); - - StudentDTO dto = (StudentDTO) resultWithAliasedBean.get(0); - assertNotNull(dto.getDescription()); - assertNotNull(dto.getName()); - - s.createCriteria(Student.class) - .add( Restrictions.like("name", "Gavin", MatchMode.START) ) - .addOrder( Order.asc("name") ) - .createCriteria("enrolments", "e") - .addOrder( Order.desc("year") ) - .addOrder( Order.desc("semester") ) - .createCriteria("course","c") - .addOrder( Order.asc("description") ) - .setProjection( Projections.projectionList() - .add( Projections.property("this.name") ) - .add( Projections.property("e.year") ) - .add( Projections.property("e.semester") ) - .add( Projections.property("c.courseCode") ) - .add( Projections.property("c.description") ) - ) - .uniqueResult(); - - Projection p1 = Projections.projectionList() - .add( Projections.count("studentNumber") ) - .add( Projections.max("studentNumber") ) - .add( Projections.rowCount() ); - - Projection p2 = Projections.projectionList() - .add( Projections.min("studentNumber") ) - .add( Projections.avg("studentNumber") ) - .add( Projections.sqlProjection( - "1 as constOne, count(*) as countStar", - new String[] { "constOne", "countStar" }, - new Type[] { StandardBasicTypes.INTEGER, StandardBasicTypes.INTEGER } - ) ); - - Object[] array = (Object[]) s.createCriteria(Enrolment.class) - .setProjection( Projections.projectionList().add(p1).add(p2) ) - .uniqueResult(); - - assertEquals( array.length, 7 ); - - List list = s.createCriteria(Enrolment.class) - .createAlias("student", "st") - .createAlias("course", "co") - .setProjection( Projections.projectionList() - .add( Projections.groupProperty("co.courseCode") ) - .add( Projections.count("st.studentNumber").setDistinct() ) - .add( Projections.groupProperty("year") ) - ) - .list(); - - assertEquals( list.size(), 2 ); - - Object g = s.createCriteria(Student.class) - .add( Restrictions.idEq( new Long(667) ) ) - .setFetchMode("enrolments", FetchMode.JOIN) - //.setFetchMode("enrolments.course", FetchMode.JOIN) //TODO: would love to make that work... - .uniqueResult(); - assertSame(g, gavin); - - s.delete(gavin); - s.delete(xam); - s.delete(course); - - t.commit(); - s.close(); - } - - @Test - public void testProjectionsUsingProperty() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - course.getCourseMeetings().add( new CourseMeeting( course, "Monday", 1, "1313 Mockingbird Lane" ) ); - s.save(course); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(667); - CityState odessaWa = new CityState( "Odessa", "WA" ); - gavin.setCityState( odessaWa ); - gavin.setPreferredCourse( course ); - s.save(gavin); - - Student xam = new Student(); - xam.setName("Max Rydahl Andersen"); - xam.setStudentNumber(101); - s.save(xam); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 1); - enrolment.setYear((short) 1999); - enrolment.setStudent(xam); - enrolment.setStudentNumber(xam.getStudentNumber()); - xam.getEnrolments().add(enrolment); - s.save(enrolment); - - enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add(enrolment); - s.save(enrolment); - - s.flush(); - - List resultList = s.createCriteria(Enrolment.class) - .setProjection( Projections.projectionList() - .add( Property.forName( "student" ), "student" ) - .add( Property.forName( "course" ), "course" ) - .add( Property.forName( "semester" ), "semester" ) - .add( Property.forName("year"), "year" ) - ) - .list(); - assertEquals( 2, resultList.size() ); - for ( Iterator it = resultList.iterator(); it.hasNext(); ) { - Object[] objects = ( Object[] ) it.next(); - assertEquals( 4, objects.length ); - assertTrue( objects[ 0 ] instanceof Student ); - assertTrue( objects[ 1 ] instanceof Course ); - assertTrue( objects[ 2 ] instanceof Short ); - assertTrue( objects[ 3 ] instanceof Short ); - } - - resultList = s.createCriteria(Student.class) - .setProjection( Projections.projectionList() - .add( Projections.id().as( "studentNumber" )) - .add( Property.forName( "name" ), "name" ) - .add( Property.forName( "cityState" ), "cityState" ) - .add( Property.forName("preferredCourse"), "preferredCourse" ) - ) - .list(); - assertEquals( 2, resultList.size() ); - for ( Iterator it = resultList.iterator(); it.hasNext(); ) { - Object[] objects = ( Object[] ) it.next(); - assertEquals( 4, objects.length ); - assertTrue( objects[ 0 ] instanceof Long ); - assertTrue( objects[ 1 ] instanceof String ); - if ( "Gavin King".equals( objects[ 1 ] ) ) { - assertTrue( objects[ 2 ] instanceof CityState ); - assertTrue( objects[ 3 ] instanceof Course ); - } - else { - assertNull( objects[ 2 ] ); - assertNull( objects[ 3 ] ); - } - } - - resultList = s.createCriteria(Student.class) - .add(Restrictions.eq("name", "Gavin King")) - .setProjection( Projections.projectionList() - .add( Projections.id().as( "studentNumber" )) - .add( Property.forName( "name" ), "name" ) - .add( Property.forName( "cityState" ), "cityState" ) - .add( Property.forName("preferredCourse"), "preferredCourse" ) - ) - .list(); - assertEquals( 1, resultList.size() ); - - Object[] aResult = ( Object[] ) s.createCriteria(Student.class) - .add( Restrictions.idEq( new Long( 667 ) ) ) - .setProjection( Projections.projectionList() - .add( Projections.id().as( "studentNumber" )) - .add( Property.forName( "name" ), "name" ) - .add( Property.forName( "cityState" ), "cityState" ) - .add( Property.forName("preferredCourse"), "preferredCourse" ) - ) - .uniqueResult(); - assertNotNull( aResult ); - assertEquals( 4, aResult.length ); - assertTrue( aResult[ 0 ] instanceof Long ); - assertTrue( aResult[ 1 ] instanceof String ); - assertTrue( aResult[ 2 ] instanceof CityState ); - assertTrue( aResult[ 3 ] instanceof Course ); - - Long count = (Long) s.createCriteria(Enrolment.class) - .setProjection( Property.forName("studentNumber").count().setDistinct() ) - .uniqueResult(); - assertEquals(count, new Long(2)); - - Object object = s.createCriteria(Enrolment.class) - .setProjection( Projections.projectionList() - .add( Property.forName("studentNumber").count() ) - .add( Property.forName("studentNumber").max() ) - .add( Property.forName("studentNumber").min() ) - .add( Property.forName("studentNumber").avg() ) - ) - .uniqueResult(); - Object[] result = (Object[])object; - - assertEquals(new Long(2),result[0]); - assertEquals(new Long(667),result[1]); - assertEquals(new Long(101),result[2]); - assertEquals(384.0, ( (Double) result[3] ).doubleValue(), 0.01); - - - s.createCriteria(Enrolment.class) - .add( Property.forName("studentNumber").gt( new Long(665) ) ) - .add( Property.forName("studentNumber").lt( new Long(668) ) ) - .add( Property.forName("courseCode").like("HIB", MatchMode.START) ) - .add( Property.forName("year").eq( new Short( (short) 1999 ) ) ) - .addOrder( Property.forName("studentNumber").asc() ) - .uniqueResult(); - - List resultWithMaps = s.createCriteria(Enrolment.class) - .setProjection( Projections.projectionList() - .add( Property.forName("studentNumber").as("stNumber") ) - .add( Property.forName("courseCode").as("cCode") ) - ) - .add( Property.forName("studentNumber").gt( new Long(665) ) ) - .add( Property.forName("studentNumber").lt( new Long(668) ) ) - .addOrder( Property.forName("studentNumber").asc() ) - .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP) - .list(); - - assertEquals(1, resultWithMaps.size()); - Map m1 = (Map) resultWithMaps.get(0); - - assertEquals(new Long(667), m1.get("stNumber")); - assertEquals(course.getCourseCode(), m1.get("cCode")); - - resultWithMaps = s.createCriteria(Enrolment.class) - .setProjection( Property.forName("studentNumber").as("stNumber") ) - .addOrder( Order.desc("stNumber") ) - .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP) - .list(); - - assertEquals(2, resultWithMaps.size()); - Map m0 = (Map) resultWithMaps.get(0); - m1 = (Map) resultWithMaps.get(1); - - assertEquals(new Long(101), m1.get("stNumber")); - assertEquals(new Long(667), m0.get("stNumber")); - - - List resultWithAliasedBean = s.createCriteria(Enrolment.class) - .createAlias("student", "st") - .createAlias("course", "co") - .setProjection( Projections.projectionList() - .add( Property.forName("st.name").as("studentName") ) - .add( Property.forName("co.description").as("courseDescription") ) - ) - .addOrder( Order.desc("studentName") ) - .setResultTransformer( Transformers.aliasToBean(StudentDTO.class) ) - .list(); - - assertEquals(2, resultWithAliasedBean.size()); - - StudentDTO dto = (StudentDTO) resultWithAliasedBean.get(0); - assertNotNull(dto.getDescription()); - assertNotNull(dto.getName()); - - CourseMeeting courseMeetingDto = ( CourseMeeting ) s.createCriteria(CourseMeeting.class) - .setProjection( Projections.projectionList() - .add( Property.forName("id").as("id") ) - .add( Property.forName("course").as("course") ) - ) - .addOrder( Order.desc("id") ) - .setResultTransformer( Transformers.aliasToBean(CourseMeeting.class) ) - .uniqueResult(); - - assertNotNull( courseMeetingDto.getId() ); - assertEquals( course.getCourseCode(), courseMeetingDto.getId().getCourseCode() ); - assertEquals( "Monday", courseMeetingDto.getId().getDay() ); - assertEquals( "1313 Mockingbird Lane", courseMeetingDto.getId().getLocation() ); - assertEquals( 1, courseMeetingDto.getId().getPeriod() ); - assertEquals( course.getDescription(), courseMeetingDto.getCourse().getDescription() ); - - s.createCriteria(Student.class) - .add( Restrictions.like("name", "Gavin", MatchMode.START) ) - .addOrder( Order.asc("name") ) - .createCriteria("enrolments", "e") - .addOrder( Order.desc("year") ) - .addOrder( Order.desc("semester") ) - .createCriteria("course","c") - .addOrder( Order.asc("description") ) - .setProjection( Projections.projectionList() - .add( Property.forName("this.name") ) - .add( Property.forName("e.year") ) - .add( Property.forName("e.semester") ) - .add( Property.forName("c.courseCode") ) - .add( Property.forName("c.description") ) - ) - .uniqueResult(); - - Projection p1 = Projections.projectionList() - .add( Property.forName("studentNumber").count() ) - .add( Property.forName("studentNumber").max() ) - .add( Projections.rowCount() ); - - Projection p2 = Projections.projectionList() - .add( Property.forName("studentNumber").min() ) - .add( Property.forName("studentNumber").avg() ) - .add( Projections.sqlProjection( - "1 as constOne, count(*) as countStar", - new String[] { "constOne", "countStar" }, - new Type[] { StandardBasicTypes.INTEGER, StandardBasicTypes.INTEGER } - ) ); - - Object[] array = (Object[]) s.createCriteria(Enrolment.class) - .setProjection( Projections.projectionList().add(p1).add(p2) ) - .uniqueResult(); - - assertEquals( array.length, 7 ); - - List list = s.createCriteria(Enrolment.class) - .createAlias("student", "st") - .createAlias("course", "co") - .setProjection( Projections.projectionList() - .add( Property.forName("co.courseCode").group() ) - .add( Property.forName("st.studentNumber").count().setDistinct() ) - .add( Property.forName("year").group() ) - ) - .list(); - - assertEquals( list.size(), 2 ); - - list = s.createCriteria(Enrolment.class) - .createAlias("student", "st") - .createAlias("course", "co") - .setProjection( Projections.projectionList() - .add( Property.forName("co.courseCode").group().as( "courseCode" )) - .add( Property.forName("st.studentNumber").count().setDistinct().as( "studentNumber" )) - .add( Property.forName("year").group()) - ) - .addOrder( Order.asc( "courseCode" ) ) - .addOrder( Order.asc( "studentNumber" ) ) - .list(); - - assertEquals( list.size(), 2 ); - - list = s.createCriteria(Enrolment.class) - .createAlias("student", "st") - .createAlias("course", "co") - .setProjection( Projections.projectionList() - .add( Property.forName("co.courseCode").group().as( "cCode" )) - .add( Property.forName("st.studentNumber").count().setDistinct().as( "stNumber" )) - .add( Property.forName("year").group()) - ) - .addOrder( Order.asc( "cCode" ) ) - .addOrder( Order.asc( "stNumber" ) ) - .list(); - - assertEquals( list.size(), 2 ); - - s.delete(gavin); - s.delete(xam); - s.delete(course); - - t.commit(); - s.close(); - } - - @Test - public void testDistinctProjectionsOfComponents() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.save(course); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(667); - gavin.setCityState( new CityState( "Odessa", "WA" ) ); - s.save(gavin); - - Student xam = new Student(); - xam.setName("Max Rydahl Andersen"); - xam.setStudentNumber(101); - xam.setPreferredCourse( course ); - xam.setCityState( new CityState( "Odessa", "WA" ) ); - s.save(xam); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 1); - enrolment.setYear((short) 1999); - enrolment.setStudent(xam); - enrolment.setStudentNumber(xam.getStudentNumber()); - xam.getEnrolments().add(enrolment); - s.save(enrolment); - - enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add(enrolment); - s.save(enrolment); - - s.flush(); - - Object result = s.createCriteria( Student.class ) - .setProjection( Projections.distinct( Property.forName( "cityState" ) ) ) - .uniqueResult(); - assertTrue( result instanceof CityState ); - assertEquals( ( ( CityState ) result ).getCity(), "Odessa" ); - assertEquals( ( ( CityState ) result ).getState(), "WA" ); - - result = s.createCriteria( Student.class ) - .setProjection( Projections.distinct( Property.forName( "cityState" ).as( "cityState" ) ) ) - .addOrder( Order.asc( "cityState" ) ) - .uniqueResult(); - assertTrue( result instanceof CityState ); - assertEquals( ( ( CityState ) result ).getCity(), "Odessa" ); - assertEquals( ( ( CityState ) result ).getState(), "WA" ); - - result = s.createCriteria( Student.class ) - .setProjection( Projections.count( "cityState.city" ) ) - .uniqueResult(); - assertEquals( 2, ((Long) result).longValue() ); - - result = s.createCriteria( Student.class ) - .setProjection( Projections.countDistinct( "cityState.city" ) ) - .uniqueResult(); - assertEquals( 1, ( ( Long ) result ).longValue() ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - try { - result = s.createCriteria( Student.class ) - .setProjection( Projections.count( "cityState" ) ) - .uniqueResult(); - if ( ! getDialect().supportsTupleCounts() ) { - fail( "expected SQLGrammarException" ); - } - assertEquals( 1, ( ( Long ) result ).longValue() ); - } - catch ( SQLGrammarException ex ) { - if ( ! getDialect().supportsTupleCounts() ) { - // expected - } - else { - throw ex; - } - } - finally { - t.rollback(); - s.close(); - } - - s = openSession(); - t = s.beginTransaction(); - try { - result = s.createCriteria( Student.class ) - .setProjection( Projections.countDistinct( "cityState" ) ) - .uniqueResult(); - if ( ! getDialect().supportsTupleDistinctCounts() ) { - fail( "expected SQLGrammarException" ); - } - assertEquals( 1, ( ( Long ) result ).longValue() ); - } - catch ( SQLGrammarException ex ) { - if ( ! getDialect().supportsTupleDistinctCounts() ) { - // expected - } - else { - throw ex; - } - } - finally { - t.rollback(); - s.close(); - } - - s = openSession(); - t = s.beginTransaction(); - s.delete(gavin); - s.delete(xam); - s.delete(course); - - t.commit(); - s.close(); - } - - @Test - public void testGroupByComponent() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.save(course); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(667); - gavin.setCityState( new CityState( "Odessa", "WA" ) ); - s.save(gavin); - - Student xam = new Student(); - xam.setName("Max Rydahl Andersen"); - xam.setStudentNumber(101); - xam.setPreferredCourse( course ); - xam.setCityState( new CityState( "Odessa", "WA" ) ); - s.save(xam); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 1); - enrolment.setYear((short) 1999); - enrolment.setStudent(xam); - enrolment.setStudentNumber(xam.getStudentNumber()); - xam.getEnrolments().add(enrolment); - s.save(enrolment); - - enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add(enrolment); - s.save(enrolment); - - s.flush(); - - Object result = s.createCriteria( Student.class ) - .setProjection( Projections.groupProperty( "cityState" ) ) - .uniqueResult(); - assertTrue( result instanceof CityState ); - assertEquals( ( ( CityState ) result ).getCity(), "Odessa" ); - assertEquals( ( ( CityState ) result ).getState(), "WA" ); - - result = s.createCriteria( Student.class, "st") - .setProjection( Projections.groupProperty( "st.cityState" ) ) - .uniqueResult(); - assertTrue( result instanceof CityState ); - assertEquals( ( ( CityState ) result ).getCity(), "Odessa" ); - assertEquals( ( ( CityState ) result ).getState(), "WA" ); - - result = s.createCriteria( Student.class, "st") - .setProjection( Projections.groupProperty( "st.cityState" ) ) - .addOrder( Order.asc( "cityState" ) ) - .uniqueResult(); - assertTrue( result instanceof CityState ); - assertEquals( ( ( CityState ) result ).getCity(), "Odessa" ); - assertEquals( ( ( CityState ) result ).getState(), "WA" ); - - result = s.createCriteria( Student.class, "st") - .setProjection( Projections.groupProperty( "st.cityState" ).as( "cityState" ) ) - .addOrder( Order.asc( "cityState" ) ) - .uniqueResult(); - assertTrue( result instanceof CityState ); - assertEquals( ( ( CityState ) result ).getCity(), "Odessa" ); - assertEquals( ( ( CityState ) result ).getState(), "WA" ); - - result = s.createCriteria( Student.class, "st") - .setProjection( Projections.groupProperty( "st.cityState" ).as( "cityState" ) ) - .addOrder( Order.asc( "cityState" ) ) - .uniqueResult(); - assertTrue( result instanceof CityState ); - assertEquals( ( ( CityState ) result ).getCity(), "Odessa" ); - assertEquals( ( ( CityState ) result ).getState(), "WA" ); - - result = s.createCriteria( Student.class, "st") - .setProjection( Projections.groupProperty( "st.cityState" ).as( "cityState" ) ) - .add( Restrictions.eq( "st.cityState", new CityState( "Odessa", "WA" ) ) ) - .addOrder( Order.asc( "cityState" ) ) - .uniqueResult(); - assertTrue( result instanceof CityState ); - assertEquals( ( ( CityState ) result ).getCity(), "Odessa" ); - assertEquals( ( ( CityState ) result ).getState(), "WA" ); - - List list = s.createCriteria(Enrolment.class) - .createAlias("student", "st") - .createAlias("course", "co") - .setProjection( Projections.projectionList() - .add( Property.forName("co.courseCode").group() ) - .add( Property.forName("st.cityState").group() ) - .add( Property.forName("year").group() ) - ) - .list(); - - - s.delete(gavin); - s.delete(xam); - s.delete(course); - - t.commit(); - s.close(); - } - - @Test - public void testRestrictionOnSubclassCollection() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - s.createCriteria( Reptile.class ) - .add( Restrictions.isEmpty( "offspring" ) ) - .list(); - - s.createCriteria( Reptile.class ) - .add( Restrictions.isNotEmpty( "offspring" ) ) - .list(); - - t.rollback(); - s.close(); - } - - @Test - public void testClassProperty() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - // HQL: from Animal a where a.mother.class = Reptile - Criteria c = s.createCriteria(Animal.class,"a") - .createAlias("mother","m") - .add( Property.forName("m.class").eq(Reptile.class) ); - c.list(); - t.rollback(); - s.close(); - } - - @Test - public void testClassProperty2() { - Session session = openSession(); - Transaction t = session.beginTransaction(); - GreatFoo foo = new GreatFoo(); - Bar b = new Bar(); - b.setMyFoo(foo); - foo.setId(1); - b.setId(1); - session.persist(b); - session.flush(); - t.commit(); - session=openSession(); - t=session.beginTransaction(); - // OK, one BAR in DB - assertEquals(1, session.createCriteria(Bar.class).list().size()); - Criteria crit = session.createCriteria(Bar.class, "b").createAlias( - "myFoo", "m").add( - Property.forName("m.class").eq(GreatFoo.class)); - assertEquals(1, crit.list().size()); - crit = session.createCriteria(Bar.class, "b").createAlias("myFoo", "m") - .add(Restrictions.eq("m.class", GreatFoo.class)); - assertEquals(1, crit.list().size()); - t.commit(); - session.close(); - } - - @Test - public void testProjectedId() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - s.createCriteria(Course.class).setProjection( Projections.property("courseCode") ).list(); - s.createCriteria(Course.class).setProjection( Projections.id() ).list(); - t.rollback(); - s.close(); - } - - @Test - public void testProjectedEmbeddedCompositeId() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.save(course); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(667); - s.save(gavin); - - Student xam = new Student(); - xam.setName("Max Rydahl Andersen"); - xam.setStudentNumber(101); - s.save(xam); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 1); - enrolment.setYear((short) 1999); - enrolment.setStudent(xam); - enrolment.setStudentNumber(xam.getStudentNumber()); - xam.getEnrolments().add(enrolment); - s.save(enrolment); - - enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add(enrolment); - s.save(enrolment); - - s.flush(); - - List enrolments = s.createCriteria( Enrolment.class).setProjection( Projections.id() ).list(); - t.rollback(); - s.close(); - } - - @Test - public void testProjectedCompositeId() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - course.getCourseMeetings().add( new CourseMeeting( course, "Monday", 1, "1313 Mockingbird Lane" ) ); - s.save(course); - s.flush(); - s.clear(); - List data = s.createCriteria( CourseMeeting.class).setProjection( Projections.id() ).list(); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - try { - s.createCriteria( CourseMeeting.class).setProjection( Projections.count( "id" ) ).list(); - fail( "should have thrown SQLGrammarException" ); - } - catch ( SQLGrammarException ex ) { - // expected - } - finally { - t.rollback(); - s.close(); - } - - s = openSession(); - t = s.beginTransaction(); - try { - s.createCriteria( CourseMeeting.class).setProjection( Projections.countDistinct( "id" ) ).list(); - if ( ! getDialect().supportsTupleDistinctCounts() ) { - fail( "expected SQLGrammarException" ); - } - } - catch ( SQLGrammarException ex ) { - if ( ! getDialect().supportsTupleDistinctCounts() ) { - // expected - } - else { - throw ex; - } - } - finally { - t.rollback(); - s.close(); - } - - s = openSession(); - t = s.beginTransaction(); - s.delete( course ); - t.commit(); - s.close(); - } - - @Test - public void testProjectedCompositeIdWithAlias() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode( "HIB" ); - course.setDescription( "Hibernate Training" ); - course.getCourseMeetings().add( new CourseMeeting( course, "Monday", 1, "1313 Mockingbird Lane" ) ); - s.save(course); - s.flush(); - - List data = s.createCriteria( CourseMeeting.class).setProjection( Projections.id().as( "id" ) ).list(); - t.rollback(); - s.close(); - } - - @Test - public void testProjectedComponent() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Student gaith = new Student(); - gaith.setName("Gaith Bell"); - gaith.setStudentNumber(123); - gaith.setCityState( new CityState( "Chicago", "Illinois" ) ); - s.save( gaith ); - s.flush(); - - List cityStates = s.createCriteria( Student.class).setProjection( Projections.property( "cityState" ) ).list(); - t.rollback(); - s.close(); - } - - @Test - public void testProjectedListIncludesComponent() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Student gaith = new Student(); - gaith.setName("Gaith Bell"); - gaith.setStudentNumber(123); - gaith.setCityState( new CityState( "Chicago", "Illinois" ) ); - s.save(gaith); - s.flush(); - List data = s.createCriteria( Student.class) - .setProjection( Projections.projectionList() - .add( Projections.property( "cityState" ) ) - .add( Projections.property("name") ) ) - .list(); - t.rollback(); - s.close(); - } - - @Test - public void testProjectedListIncludesEmbeddedCompositeId() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.save(course); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(667); - s.save(gavin); - - Student xam = new Student(); - xam.setName("Max Rydahl Andersen"); - xam.setStudentNumber(101); - s.save(xam); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 1); - enrolment.setYear((short) 1999); - enrolment.setStudent(xam); - enrolment.setStudentNumber(xam.getStudentNumber()); - xam.getEnrolments().add(enrolment); - s.save(enrolment); - - enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add(enrolment); - s.save(enrolment); - s.flush(); - List data = s.createCriteria( Enrolment.class) - .setProjection( Projections.projectionList() - .add( Projections.property( "semester" ) ) - .add( Projections.property("year") ) - .add( Projections.id() ) ) - .list(); - t.rollback(); - s.close(); - } - - @Test - public void testSubcriteriaJoinTypes() { - Session session = openSession(); - Transaction t = session.beginTransaction(); - - Course courseA = new Course(); - courseA.setCourseCode("HIB-A"); - courseA.setDescription("Hibernate Training A"); - session.persist(courseA); - - Course courseB = new Course(); - courseB.setCourseCode("HIB-B"); - courseB.setDescription("Hibernate Training B"); - session.persist(courseB); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse(courseA); - session.persist(gavin); - - Student leonardo = new Student(); - leonardo.setName("Leonardo Quijano"); - leonardo.setStudentNumber(233); - leonardo.setPreferredCourse(courseB); - session.persist(leonardo); - - Student johnDoe = new Student(); - johnDoe.setName("John Doe"); - johnDoe.setStudentNumber(235); - johnDoe.setPreferredCourse(null); - session.persist(johnDoe); - - List result = session.createCriteria( Student.class ) - .setProjection( Property.forName("preferredCourse.courseCode") ) - .createCriteria( "preferredCourse", Criteria.LEFT_JOIN ) - .addOrder( Order.asc( "courseCode" ) ) - .list(); - assertEquals( 3, result.size() ); - // can't be sure of NULL comparison ordering aside from they should - // either come first or last - if ( result.get( 0 ) == null ) { - assertEquals( "HIB-A", result.get(1) ); - assertEquals( "HIB-B", result.get(2) ); - } - else { - assertNull( result.get(2) ); - assertEquals( "HIB-A", result.get(0) ); - assertEquals( "HIB-B", result.get(1) ); - } - - result = session.createCriteria( Student.class ) - .setFetchMode( "preferredCourse", FetchMode.JOIN ) - .createCriteria( "preferredCourse", Criteria.LEFT_JOIN ) - .addOrder( Order.asc( "courseCode" ) ) - .list(); - assertEquals( 3, result.size() ); - assertNotNull( result.get(0) ); - assertNotNull( result.get( 1 ) ); - assertNotNull( result.get( 2 ) ); - - result = session.createCriteria( Student.class ) - .setFetchMode( "preferredCourse", FetchMode.JOIN ) - .createAlias( "preferredCourse", "pc", Criteria.LEFT_JOIN ) - .addOrder( Order.asc( "pc.courseCode" ) ) - .list(); - assertEquals( 3, result.size() ); - assertNotNull( result.get(0) ); - assertNotNull( result.get(1) ); - assertNotNull( result.get( 2 ) ); - - session.delete(gavin); - session.delete(leonardo); - session.delete(johnDoe); - session.delete(courseA); - session.delete(courseB); - t.commit(); - session.close(); - } - - @Test - public void testAliasJoinCriterion() { - Session session = openSession(); - Transaction t = session.beginTransaction(); - - Course courseA = new Course(); - courseA.setCourseCode("HIB-A"); - courseA.setDescription("Hibernate Training A"); - session.persist(courseA); - - Course courseB = new Course(); - courseB.setCourseCode("HIB-B"); - courseB.setDescription("Hibernate Training B"); - session.persist(courseB); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse(courseA); - session.persist(gavin); - - Student leonardo = new Student(); - leonardo.setName("Leonardo Quijano"); - leonardo.setStudentNumber(233); - leonardo.setPreferredCourse(courseB); - session.persist(leonardo); - - Student johnDoe = new Student(); - johnDoe.setName("John Doe"); - johnDoe.setStudentNumber(235); - johnDoe.setPreferredCourse(null); - session.persist(johnDoe); - - // test == on one value exists - List result = session.createCriteria( Student.class ) - .createAlias( "preferredCourse", "pc", Criteria.LEFT_JOIN, Restrictions.eq("pc.courseCode", "HIB-A") ) - .setProjection( Property.forName("pc.courseCode") ) - .addOrder(Order.asc("pc.courseCode")) - .list(); - - assertEquals( 3, result.size() ); - - // can't be sure of NULL comparison ordering aside from they should - // either come first or last - if ( result.get( 0 ) == null ) { - assertNull(result.get(1)); - assertEquals( "HIB-A", result.get(2) ); - } - else { - assertNull( result.get(2) ); - assertNull( result.get(1) ); - assertEquals( "HIB-A", result.get(0) ); - } - - // test == on non existent value - result = session.createCriteria( Student.class ) - .createAlias( "preferredCourse", "pc", Criteria.LEFT_JOIN, Restrictions.eq("pc.courseCode", "HIB-R") ) - .setProjection( Property.forName("pc.courseCode") ) - .addOrder(Order.asc("pc.courseCode")) - .list(); - - assertEquals( 3, result.size() ); - assertNull( result.get(2) ); - assertNull( result.get(1) ); - assertNull(result.get(0) ); - - // test != on one existing value - result = session.createCriteria( Student.class ) - .createAlias( "preferredCourse", "pc", Criteria.LEFT_JOIN, Restrictions.ne("pc.courseCode", "HIB-A") ) - .setProjection( Property.forName("pc.courseCode") ) - .addOrder(Order.asc("pc.courseCode")) - .list(); - - assertEquals( 3, result.size() ); - // can't be sure of NULL comparison ordering aside from they should - // either come first or last - if ( result.get( 0 ) == null ) { - assertNull( result.get(1) ); - assertEquals( "HIB-B", result.get(2) ); - } - else { - assertEquals( "HIB-B", result.get(0) ); - assertNull( result.get(1) ); - assertNull( result.get(2) ); - } - - session.delete(gavin); - session.delete(leonardo); - session.delete(johnDoe); - session.delete(courseA); - session.delete(courseB); - t.commit(); - session.close(); - } - - @Test - public void testCriteriaCollectionOfValue() { - Session session = openSession(); - Transaction t = session.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - Set crossListedAs = new HashSet(); - crossListedAs.add("Java Persistence 101"); - crossListedAs.add("CS101"); - course.setCrossListedAs(crossListedAs); - session.persist(course); - session.flush(); - session.clear(); - List results = session.createCriteria(Course.class) - .createCriteria("crossListedAs") - .add(Restrictions.eq("elements", "CS101")) - .list(); - - assertEquals( 1, results.size() ); - course = (Course)results.get(0); - assertEquals( 2, course.getCrossListedAs().size() ); - - session.delete(course); - - t.commit(); - session.close(); - - } - - @Test - @TestForIssue( jiraKey = "HHH-6766" ) - public void testMultiplePropertiesSubquery() { - Session session = openSession(); - Transaction tx = session.beginTransaction(); - - Man lukasz = new Man(); - lukasz.setName( "Lukasz" ); - lukasz.setHeight( 170 ); - lukasz.setWeight( 60 ); - session.persist( lukasz ); - - Man robert = new Man(); - robert.setName( "Robert" ); - robert.setHeight( 170 ); - robert.setWeight( 78 ); - session.persist( robert ); - - Woman kinga = new Woman(); - kinga.setName( "Kinga" ); - kinga.setHeight( 170 ); - kinga.setWeight( 60 ); - session.persist( kinga ); - - tx.commit(); - session.close(); - - session = openSession(); - tx = session.beginTransaction(); - - DetachedCriteria sizeQuery = DetachedCriteria.forClass( Man.class ).setProjection( - Projections.projectionList().add( Projections.property( "weight" ) ) - .add( Projections.property( "height" ) ) ) - .add( Restrictions.eq( "name", "Lukasz" ) - ); - List result; - if ( getDialect().supportsRowValueConstructorSyntax() ) { - result = session.createCriteria( Woman.class ) - .add( Subqueries.propertiesEq( new String[] { "weight", "height" }, sizeQuery ) ) - .list(); - assertEquals( 1, result.size() ); - assertEquals( kinga, result.get( 0 ) ); - } - if ( getDialect().supportsRowValueConstructorSyntaxInInList() ) { - result = session.createCriteria( Woman.class ) - .add( Subqueries.propertiesIn( new String[] { "weight", "height" }, sizeQuery ) ) - .list(); - assertEquals( 1, result.size() ); - assertEquals( kinga, result.get( 0 ) ); - } - - tx.commit(); - session.close(); - - session = openSession(); - tx = session.beginTransaction(); - sizeQuery = DetachedCriteria.forClass( Man.class ).setProjection( - Projections.projectionList().add( Projections.property( "weight" ) ) - .add( Projections.property( "height" ) ) - ) - .add( - Restrictions.ne( "name", "Lukasz" ) - ); - if ( getDialect().supportsRowValueConstructorSyntax() ) { - result = session.createCriteria( Woman.class ) - .add( Subqueries.propertiesNotEq( new String[] { "weight", "height" }, sizeQuery ) ) - .list(); - assertEquals( 1, result.size() ); - assertEquals( kinga, result.get( 0 ) ); - } - if (getDialect().supportsRowValueConstructorSyntaxInInList()) { - result = session.createCriteria( Woman.class ) - .add( Subqueries.propertiesNotIn( new String[] { "weight", "height" }, sizeQuery ) ) - .list(); - assertEquals( 1, result.size() ); - assertEquals( kinga, result.get( 0 ) ); - } - - tx.commit(); - session.close(); - } - - @Test - public void testCriteriaCollectionOfComponent() { - Session session = openSession(); - Transaction t = session.beginTransaction(); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - - Map addresses = new HashMap(); - StudentAddress addr = new StudentAddress(); - addr.setLine1("101 Main St."); - addr.setCity("Anytown"); - addr.setState("NY"); - addr.setZip("10016"); - addresses.put("HOME", addr); - - addr = new StudentAddress(); - addr.setLine1("202 Spring St."); - addr.setCity("Springfield"); - addr.setState("MA"); - addr.setZip("99999"); - addresses.put("SCHOOL", addr); - - gavin.setAddresses(addresses); - session.persist(gavin); - - Student xam = new Student(); - xam.setName("Max Rydahl Andersen"); - xam.setStudentNumber(101); - - addresses = new HashMap(); - addr = new StudentAddress(); - addr.setLine1("123 3rd Ave"); - addr.setCity("New York"); - addr.setState("NY"); - addr.setZip("10004"); - addresses.put("HOME", addr); - - xam.setAddresses(addresses); - session.persist(xam); - - session.flush(); - session.clear(); - - // search on a component property - List results = session.createCriteria(Student.class) - .createCriteria("addresses") - .add(Restrictions.eq("state", "MA")) - .list(); - - assertEquals(1, results.size()); - - gavin = (Student)results.get(0); - assertEquals(2, gavin.getAddresses().keySet().size()); - - session.delete(gavin); - session.delete(xam); - - t.commit(); - session.close(); - - } - - @Test - @TestForIssue(jiraKey = "HHH-7194") - public void testNestedCorrelatedSubquery() throws Exception { - Session session = openSession(); - Transaction t = session.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - session.persist(course); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse(course); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse( course ); - enrolment.setCourseCode( course.getCourseCode() ); - enrolment.setSemester( ( short ) 1 ); - enrolment.setYear( ( short ) 1999 ); - enrolment.setStudent( gavin ); - enrolment.setStudentNumber( gavin.getStudentNumber() ); - - session.persist(course); - session.persist(gavin); - session.persist(enrolment); - - session.flush(); - session.clear(); - - //execute a nested subquery - DetachedCriteria mainCriteria = DetachedCriteria.forClass(Student.class, "student"); - - DetachedCriteria nestedSubQuery = DetachedCriteria.forClass( Enrolment.class, "maxStudentEnrolment" ); - nestedSubQuery.add(Restrictions.eqProperty("student.preferredCourse", "maxStudentEnrolment.course")); - nestedSubQuery.setProjection(Projections.max("maxStudentEnrolment.year")); - - DetachedCriteria subQuery = DetachedCriteria.forClass( Enrolment.class, "enrolment" ); - subQuery.add(Subqueries.propertyEq("enrolment.year", nestedSubQuery)); - subQuery.setProjection(Projections.property("student")); - - mainCriteria.add(Subqueries.exists(subQuery)); - - //query should complete and return gavin in the list - List results = mainCriteria.getExecutableCriteria(session).list(); - assertEquals(1, results.size()); - assertEquals(gavin.getStudentNumber(), ((Student) results.get(0)).getStudentNumber()); - - t.rollback(); - session.close(); - } - - @Test - public void testCriteriaFetchMode() { - Session session = openSession(); - Transaction t = session.beginTransaction(); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - - Country gb = new Country("GB", "United Kingdom"); - Country fr = new Country("FR", "France"); - session.persist(gb); - session.persist(fr); - - List studyAbroads = new ArrayList(); - StudyAbroad sa1 = new StudyAbroad(gb, new Date()); - StudyAbroad sa2 = new StudyAbroad(fr, new Date(sa1.getDate().getTime()+1)); - studyAbroads.add(sa1); - studyAbroads.add(sa2); - gavin.setStudyAbroads(studyAbroads); - - session.persist(gavin); - - session.flush(); - session.clear(); - - List results = session.createCriteria(Student.class) - .setFetchMode("studyAbroads", FetchMode.JOIN) - .setFetchMode("studyAbroads.country", FetchMode.JOIN) - .list(); - - - assertEquals(results.size(), 2); - Student st = (Student)results.get(0); - - assertNotNull(st.getStudyAbroads()); - assertTrue(Hibernate.isInitialized(st.getStudyAbroads())); - assertEquals(st.getStudyAbroads().size(), 2); - Country c1 = ((StudyAbroad)st.getStudyAbroads().get(0)).getCountry(); - Country c2 = ((StudyAbroad)st.getStudyAbroads().get(1)).getCountry(); - assertTrue( Hibernate.isInitialized( c1 )); - assertEquals(c1.getName(), "United Kingdom"); - - session.delete(st); - session.delete(c1); - session.delete(c2); - - t.commit(); - session.close(); - - } - - @Test - @TestForIssue( jiraKey = "HHH-6643" ) - public void testNotNot() { - Student student1 = new Student(); - student1.setName("Foo1 Foo1"); - student1.setStudentNumber(1); - Student student2 = new Student(); - student2.setName("Foo2 Foo2"); - student2.setStudentNumber(2); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - s.persist( student1 ); - s.persist( student2 ); - s.flush(); - s.clear(); - - // Although this example is simplified and the "not not" is pointless, - // double negatives can occur in some dynamic applications (regardless - // if it results from bad design or not). Test to ensure the dialect - // handles them as expected. - List students = s.createCriteria( Student.class ).add( - Restrictions.not( - Restrictions.not( - Restrictions.eq( "studentNumber", 1l ) ) ) - ).list(); - - assertEquals( students.size(), 1 ); - assertEquals( students.get( 0 ).getStudentNumber(), 1 ); - - t.rollback(); - s.close(); - } - - @Test - @TestForIssue( jiraKey = "HHH-2951" ) - public void testNullCriteria() { - Course course = new Course(); - course.setCourseCode( "1234" ); - course.setDescription( null ); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - s.persist( course ); - s.flush(); - s.clear(); - - // Ensure Restrictions creates "where foo is null", instead of - // "where foo = null" - List courses = s.createCriteria( Course.class ).add( - Restrictions.eqOrIsNull( "description", null) ).list(); - - assertEquals( courses.size(), 1 ); - assertEquals( courses.get( 0 ).getCourseCode(), course.getCourseCode() ); - - t.rollback(); - s.close(); - } - -} - diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/CriterionTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/CriterionTest.java deleted file mode 100644 index 06030ae2f7..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/CriterionTest.java +++ /dev/null @@ -1,106 +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.IrrelevantEntity; -import org.hibernate.SessionFactory; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Restrictions; -import org.hibernate.dialect.Dialect; -import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.internal.CriteriaImpl; -import org.hibernate.loader.criteria.CriteriaQueryTranslator; - -import org.hibernate.testing.junit4.BaseUnitTestCase; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * @author Steve Ebersole - */ -public class CriterionTest extends BaseUnitTestCase { - @Test - public void testIlikeRendering() { - SessionFactory sf = new Configuration() - .addAnnotatedClass( IrrelevantEntity.class ) - .setProperty( AvailableSettings.DIALECT, IlikeSupportingDialect.class.getName() ) - .setProperty( Environment.HBM2DDL_AUTO, "create-drop" ) - .buildSessionFactory(); - try { - final Criteria criteria = sf.openSession().createCriteria( IrrelevantEntity.class ); - final CriteriaQueryTranslator translator = new CriteriaQueryTranslator( - (SessionFactoryImplementor) sf, - (CriteriaImpl) criteria, - IrrelevantEntity.class.getName(), - "a" - ); - final Criterion ilikeExpression = Restrictions.ilike( "name", "abc" ); - final String ilikeExpressionSqlFragment = ilikeExpression.toSqlString( criteria, translator ); - assertEquals( "a.name insensitiveLike ?", ilikeExpressionSqlFragment ); - } - finally { - sf.close(); - } - } - - @Test - public void testIlikeMimicing() { - SessionFactory sf = new Configuration() - .addAnnotatedClass( IrrelevantEntity.class ) - .setProperty( AvailableSettings.DIALECT, NonIlikeSupportingDialect.class.getName() ) - .setProperty( Environment.HBM2DDL_AUTO, "create-drop" ) - .buildSessionFactory(); - try { - final Criteria criteria = sf.openSession().createCriteria( IrrelevantEntity.class ); - final CriteriaQueryTranslator translator = new CriteriaQueryTranslator( - (SessionFactoryImplementor) sf, - (CriteriaImpl) criteria, - IrrelevantEntity.class.getName(), - "a" - ); - final Criterion ilikeExpression = Restrictions.ilike( "name", "abc" ); - final String ilikeExpressionSqlFragment = ilikeExpression.toSqlString( criteria, translator ); - assertEquals( "lowLowLow(a.name) like ?", ilikeExpressionSqlFragment ); - } - finally { - sf.close(); - } - } - - public static class IlikeSupportingDialect extends Dialect { - @Override - public boolean supportsCaseInsensitiveLike() { - return true; - } - - @Override - public String getCaseInsensitiveLike() { - return "insensitiveLike"; - } - } - - public static class NonIlikeSupportingDialect extends Dialect { - @Override - public boolean supportsCaseInsensitiveLike() { - return false; - } - - @Override - public String getCaseInsensitiveLike() { - throw new UnsupportedOperationException(); - } - - @Override - public String getLowercaseFunction() { - return "lowLowLow"; - } - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/InTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/InTest.java deleted file mode 100644 index dc06b79740..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/InTest.java +++ /dev/null @@ -1,79 +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 . - */ -package org.hibernate.test.criteria; - -import static org.junit.Assert.assertEquals; - -import java.util.Collections; -import java.util.List; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.criterion.Restrictions; -import org.hibernate.dialect.DerbyDialect; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Test; - -/** - * @author Dragan Bozanovic (draganb) - */ -public class InTest extends BaseCoreFunctionalTestCase { - - public String[] getMappings() { - return new String[]{ "criteria/Person.hbm.xml" }; - } - - @Test - public void testIn() { - Session session = openSession(); - Transaction tx = session.beginTransaction(); - session.save( new Woman() ); - session.save( new Man() ); - session.flush(); - tx.commit(); - session.close(); - session = openSession(); - tx = session.beginTransaction(); - List persons = session.createCriteria( Person.class ).add( - Restrictions.in( "class", Woman.class ) ).list(); - assertEquals( 1, persons.size() ); - tx.rollback(); - session.close(); - } - - @Test - @TestForIssue( jiraKey = "HHH-8901" ) - @RequiresDialectFeature(DialectChecks.NotSupportsEmptyInListCheck.class) - @SkipForDialect(value = DerbyDialect.class, comment = "Derby doesn't like `x in (null)`") - public void testEmptyInListForDialectNotSupportsEmptyInList() { - Session session = openSession(); - Transaction tx = session.beginTransaction(); - session.save( new Woman() ); - session.save( new Man() ); - session.flush(); - tx.commit(); - session.close(); - session = openSession(); - tx = session.beginTransaction(); - List persons = session.createCriteria( Person.class ).add( - Restrictions.in( "name", Collections.emptySet() ) ).list(); - assertEquals( 0, persons.size() ); - tx.rollback(); - session.close(); - } - - @Override - protected boolean isCleanupTestDataRequired() { - return true; - } - -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/LikeTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/LikeTest.java deleted file mode 100644 index d7c4f23645..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/LikeTest.java +++ /dev/null @@ -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 . - */ -package org.hibernate.test.criteria; -import java.util.List; - -import org.junit.Test; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.criterion.Restrictions; -import org.hibernate.dialect.MySQLDialect; -import org.hibernate.dialect.PostgreSQL81Dialect; -import org.hibernate.dialect.PostgreSQLDialect; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import static org.junit.Assert.assertEquals; - - -public class LikeTest extends BaseCoreFunctionalTestCase { - public String[] getMappings() { - return new String[]{"criteria/TestObject.hbm.xml"}; - } - - @Test - public void testLike(){ - Session session = openSession(); - Transaction tx = session.beginTransaction(); - TestObject obj = new TestObject(); - String uniq = "uniq" + System.currentTimeMillis(); - obj.setText( "XyZ " + uniq + " blablabla" ); - session.save( obj ); - session.flush(); - tx.commit(); - session.close(); - String pattern = "XyZ " + uniq + "%"; - // retrieve object - case sensitive - works ok - session = openSession(); - tx = session.beginTransaction(); - List objects = session.createCriteria( TestObject.class ).add( - Restrictions.like( "text", pattern ) ).list(); - assertEquals( 1, objects.size() ); - session.clear(); - - // retrieve object - case insensitive - works ok - objects = session.createCriteria( TestObject.class ).add( - Restrictions.like( "text", pattern ).ignoreCase() ).list(); - - assertEquals( 1, objects.size() ); - session.clear(); - if ( !( getDialect() instanceof MySQLDialect ) && ! ( getDialect() instanceof PostgreSQLDialect ) && ! ( getDialect() instanceof PostgreSQL81Dialect )) { - // retrieve object - case insensitive via custom expression - works - // ok - objects = session.createCriteria( TestObject.class ).add( - StringExpression.stringExpression( "text", pattern, true ) ) - .list(); - - assertEquals( 1, objects.size() ); - session.clear(); - - // retrieve object - case sensitive via custom expression - not - // working - objects = session.createCriteria( TestObject.class ) - .add( - StringExpression.stringExpression( "text", pattern, - false ) ).list(); - assertEquals( 1, objects.size() ); - } - tx.rollback(); - session.close(); - - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/LongInElementsTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/LongInElementsTest.java deleted file mode 100644 index 8d27ba5f13..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/LongInElementsTest.java +++ /dev/null @@ -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 . - */ -package org.hibernate.test.criteria; - -import java.util.ArrayList; -import java.util.List; - -import org.hibernate.query.Query; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.dialect.Oracle8iDialect; -import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.dialect.SybaseDialect; -import org.hibernate.dialect.TeradataDialect; - -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.hibernate.test.hql.StateProvince; -import org.junit.Ignore; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * HHH-2166 Long "in" lists in queries results in a Java stack overflow - * exception. to reproduce this issue, you should add - * "-Xss128k" to the surefire plugin (test on Fedora 12) - * - * @author Strong Liu - */ -@Ignore -public class LongInElementsTest extends BaseCoreFunctionalTestCase { - private static final int ELEMENTS_SIZE = 4000; - - @Override - public String[] getMappings() { - return new String[] { "criteria/Animal.hbm.xml" }; - } - - @Test - @TestForIssue( jiraKey = "HHH-2166" ) - @SkipForDialect( - value = { SQLServerDialect.class, Oracle8iDialect.class, TeradataDialect.class, SybaseDialect.class }, - comment = "this test fails on oracle and ms sql server, for more info, see HHH-1123" - ) - public void testLongInElementsByHQL() { - Session session = openSession(); - Transaction t = session.beginTransaction(); - - StateProvince beijing = new StateProvince(); - beijing.setIsoCode( "100089" ); - beijing.setName( "beijing" ); - session.persist( beijing ); - session.flush(); - session.clear(); - - Query query = session - .createQuery( "from org.hibernate.test.hql.StateProvince sp where sp.id in ( :idList )" ); - query.setParameterList( "idList" , createLotsOfElements() ); - List list = query.list(); - session.flush(); - session.clear(); - assertEquals( 1 , list.size() ); - session.delete( beijing ); - t.commit(); - session.close(); - - } - - @Test - @TestForIssue( jiraKey = "HHH-2166" ) - @SkipForDialect( - value = { SQLServerDialect.class, Oracle8iDialect.class, TeradataDialect.class, SybaseDialect.class }, - comment = "this test fails on oracle and ms sql server, for more info, see HHH-1123" - ) - public void testLongInElementsByCriteria() { - Session session = openSession(); - Transaction t = session.beginTransaction(); - - StateProvince beijing = new StateProvince(); - beijing.setIsoCode( "100089" ); - beijing.setName( "beijing" ); - session.persist( beijing ); - session.flush(); - session.clear(); - - Criteria criteria = session.createCriteria( StateProvince.class ); - criteria.add( Restrictions.in( "id" , createLotsOfElements() ) ); - List list = criteria.list(); - session.flush(); - session.clear(); - assertEquals( 1 , list.size() ); - session.delete( beijing ); - t.commit(); - session.close(); - - } - - private List createLotsOfElements() { - List list = new ArrayList(); - for ( int i = 0; i < ELEMENTS_SIZE; i++ ) { - list.add( Long.valueOf( i ) ); - } - return list; - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/NationalizedIgnoreCaseTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/NationalizedIgnoreCaseTest.java deleted file mode 100644 index 7718bef7ab..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/NationalizedIgnoreCaseTest.java +++ /dev/null @@ -1,94 +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.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.Table; - -import org.hibernate.annotations.Nationalized; -import org.hibernate.criterion.Restrictions; -import org.hibernate.dialect.DB2Dialect; -import org.hibernate.dialect.DerbyDialect; -import org.hibernate.dialect.PostgreSQL81Dialect; - -import org.hibernate.testing.SkipForDialect; -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.assertEquals; - -/** - * @author Chris Cranford (aka Naros) - */ -@TestForIssue( jiraKey = "HHH-8657" ) -@SkipForDialect(value = DB2Dialect.class, comment = "DB2 jdbc driver doesn't support setNString") -@SkipForDialect(value = DerbyDialect.class, comment = "Derby jdbc driver doesn't support setNString") -@SkipForDialect(value = PostgreSQL81Dialect.class, comment = "PostgreSQL jdbc driver doesn't support setNString") -public class NationalizedIgnoreCaseTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { User.class }; - } - - @Test - public void testIgnoreCaseCriteria() { - - User user1 = new User(1, "Chris"); - User user2 = new User(2, "Steve"); - - doInHibernate( this::sessionFactory, session -> { - session.save(user1); - session.save(user2); - } ); - - doInHibernate( this::sessionFactory, session -> { - Criteria criteria = session.createCriteria(User.class); - criteria.add(Restrictions.eq("name", user1.getName().toLowerCase()).ignoreCase()); - assertEquals(1, criteria.list().size()); - } ); - } - - @Entity(name = "User") - @Table(name = "users") - public static class User { - - private Integer id; - private String name; - - public User() { - - } - - public User(Integer id, String name) { - this.id = id; - this.name = name; - } - - @Id - public Integer getId() { - return id; - } - public void setId(Integer id) { - this.id = id; - } - - @Nationalized - @Column(nullable = false) - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/OuterJoinCriteriaTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/OuterJoinCriteriaTest.java deleted file mode 100644 index 337b105aaf..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/OuterJoinCriteriaTest.java +++ /dev/null @@ -1,626 +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 . - */ -package org.hibernate.test.criteria; - -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.junit.Test; - -import org.hibernate.Session; -import org.hibernate.criterion.CriteriaSpecification; -import org.hibernate.criterion.Restrictions; -import org.hibernate.sql.JoinFragment; -import org.hibernate.sql.JoinType; -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -/** - * @author Mattias Jiderhamn - * @author Gail Badner - */ -public class OuterJoinCriteriaTest extends BaseCoreFunctionalTestCase { - private Order order1; - private Order order2; - private Order order3; - - @Override - public String[] getMappings() { - return new String[] { "criteria/Order.hbm.xml" }; - } - - @Test - public void testSubcriteriaWithNonNullRestrictions() { - Session s = openSession(); - s.getTransaction().begin(); - - Criteria rootCriteria = s.createCriteria( Order.class ); - Criteria subCriteria = rootCriteria.createCriteria( "orderLines", JoinFragment.LEFT_OUTER_JOIN ); - assertNotSame( rootCriteria, subCriteria ); - - // add restrictions to subCriteria, ensuring we stay on subCriteria - assertSame( subCriteria, subCriteria.add( Restrictions.eq( "articleId", "3000" ) ) ); - - List orders = rootCriteria.list(); - - // order1 and order3 should be returned because each has articleId == "3000" - // both should have their full collection - assertEquals( 2, orders.size() ); - for ( Iterator it = orders.iterator(); it.hasNext(); ) { - Order o = (Order) it.next(); - if ( order1.getOrderId() == o.getOrderId() ) { - assertEquals( order1.getLines().size(), o.getLines().size() ); - } - else if ( order3.getOrderId() == o.getOrderId() ) { - assertEquals( order3.getLines().size(), o.getLines().size() ); - } - else { - fail( "unknown order" ); - } - } - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testSubcriteriaWithNonNullRestrictionsAliasToEntityMap() { - Session s = openSession(); - s.getTransaction().begin(); - - Criteria rootCriteria = s.createCriteria( Order.class, "o" ); - Criteria subCriteria = rootCriteria.createCriteria( "orderLines", "ol", JoinFragment.LEFT_OUTER_JOIN ); - assertNotSame( rootCriteria, subCriteria ); - - // add restriction to subCriteria, ensuring we stay on subCriteria - assertSame( subCriteria, subCriteria.add( Restrictions.eq( "articleId", "3000" ) ) ); - - List orders = rootCriteria.setResultTransformer( Criteria.ALIAS_TO_ENTITY_MAP ).list(); - - // order1 and order3 should be returned because each has articleId == "3000"; - // the orders should both should have their full collection; - assertEquals( 2, orders.size() ); - for ( Iterator it = orders.iterator(); it.hasNext(); ) { - Map map = (Map) it.next(); - Order o = ( Order ) map.get( "o" ); - // the orderLine returned from the map should have articleId = "3000" - OrderLine ol = ( OrderLine ) map.get( "ol" ); - if ( order1.getOrderId() == o.getOrderId() ) { - assertEquals( order1.getLines().size(), o.getLines().size() ); - assertEquals( "3000", ol.getArticleId() ); - } - else if ( order3.getOrderId() == o.getOrderId() ) { - assertEquals( order3.getLines().size(), o.getLines().size() ); - assertEquals( "3000", ol.getArticleId() ); - } - else { - fail( "unknown order" ); - } - } - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testSubcriteriaWithNullOrNonNullRestrictions() { - Session s = openSession(); - s.getTransaction().begin(); - - Criteria rootCriteria = s.createCriteria( Order.class ); - Criteria subCriteria = rootCriteria.createCriteria( "orderLines", JoinFragment.LEFT_OUTER_JOIN ); - assertNotSame( rootCriteria, subCriteria ); - - // add restrictions to subCriteria, ensuring we stay on subCriteria - // add restriction to subCriteria, ensuring we stay on subCriteria - assertSame( - subCriteria, - subCriteria.add( - Restrictions.or( - Restrictions.isNull( "articleId" ), // Allow null - Restrictions.eq( "articleId", "1000" ) - ) - ) - ); - - List orders = rootCriteria.list(); - - // order1 should be returned because it has an orderline with articleId == "1000"; - // order2 should be returned because it has no orderlines - assertEquals( 2, orders.size() ); - for ( Iterator it = orders.iterator(); it.hasNext(); ) { - Order o = ( Order ) it.next(); - if ( order1.getOrderId() == o.getOrderId() ) { - // o.getLines() should contain all of its orderLines - assertEquals( order1.getLines().size(), o.getLines().size() ); - } - else if ( order2.getOrderId() == o.getOrderId() ) { - assertEquals( order2.getLines() , o.getLines() ); - assertTrue( o.getLines().isEmpty() ); - } - else { - fail( "unknown order" ); - } - } - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testSubcriteriaWithNullOrNonNullRestrictionsAliasToEntityMap() { - Session s = openSession(); - s.getTransaction().begin(); - - Criteria rootCriteria = s.createCriteria( Order.class, "o" ); - Criteria subCriteria = rootCriteria.createCriteria( "orderLines", "ol", JoinFragment.LEFT_OUTER_JOIN ); - assertNotSame( rootCriteria, subCriteria ); - - // add restriction to subCriteria, ensuring we stay on subCriteria - assertSame( - subCriteria, - subCriteria.add( - Restrictions.or( - Restrictions.isNull( "ol.articleId" ), // Allow null - Restrictions.eq( "ol.articleId", "1000" ) - ) - ) - ); - - List orders = rootCriteria.setResultTransformer( Criteria.ALIAS_TO_ENTITY_MAP ).list(); - - // order1 should be returned because it has an orderline with articleId == "1000"; - // order2 should be returned because it has no orderlines - assertEquals( 2, orders.size() ); - for ( Iterator it = orders.iterator(); it.hasNext(); ) { - Map map = (Map) it.next(); - Order o = ( Order ) map.get( "o" ); - // the orderLine returned from the map should either be null or have articleId = "1000" - OrderLine ol = ( OrderLine ) map.get( "ol" ); - if ( order1.getOrderId() == o.getOrderId() ) { - // o.getLines() should contain all of its orderLines - assertEquals( order1.getLines().size(), o.getLines().size() ); - assertNotNull( ol ); - assertEquals( "1000", ol.getArticleId() ); - } - else if ( order2.getOrderId() == o.getOrderId() ) { - assertEquals( order2.getLines() , o.getLines() ); - assertTrue( o.getLines().isEmpty() ); - assertNull( ol ); - } - else { - fail( "unknown order" ); - } - } - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testSubcriteriaWithClauseAliasToEntityMap() { - Session s = openSession(); - s.getTransaction().begin(); - - Criteria rootCriteria = s.createCriteria( Order.class, "o" ); - Criteria subCriteria = rootCriteria.createCriteria( - "orderLines", - "ol", JoinFragment.LEFT_OUTER_JOIN, - Restrictions.or( - Restrictions.isNull( "ol.articleId" ), // Allow null - Restrictions.eq( "ol.articleId", "1000" ) - ) - ); - assertNotSame( rootCriteria, subCriteria ); - - List orders = rootCriteria.setResultTransformer( Criteria.ALIAS_TO_ENTITY_MAP ).list(); - - // all orders should be returned (via map.get( "o" )) with their full collections; - assertEquals( 3, orders.size() ); - for ( Iterator it = orders.iterator(); it.hasNext(); ) { - Map map = ( Map ) it.next(); - Order o = ( Order ) map.get( "o" ); - // the orderLine returned from the map should either be null or have articleId = "1000" - OrderLine ol = ( OrderLine ) map.get( "ol" ); - if ( order1.getOrderId() == o.getOrderId() ) { - // o.getLines() should contain all of its orderLines - assertEquals( order1.getLines().size(), o.getLines().size() ); - assertNotNull( ol ); - assertEquals( "1000", ol.getArticleId() ); - } - else if ( order2.getOrderId() == o.getOrderId() ) { - assertTrue( o.getLines().isEmpty() ); - assertNull( ol ); - } - else if ( order3.getOrderId() == o.getOrderId() ) { - assertEquals( order3.getLines().size(), o.getLines().size() ); - assertNull( ol); - } - else { - fail( "unknown order" ); - } - } - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testAliasWithNonNullRestrictions() { - Session s = openSession(); - s.getTransaction().begin(); - - Criteria rootCriteria = s.createCriteria( Order.class ); - // create alias, ensuring we stay on the root criteria - assertSame( rootCriteria, rootCriteria.createAlias( "orderLines", "ol", JoinFragment.LEFT_OUTER_JOIN ) ); - - // add restrictions to rootCriteria - assertSame( rootCriteria, rootCriteria.add( Restrictions.eq( "ol.articleId", "3000" ) ) ); - - List orders = rootCriteria.list(); - - // order1 and order3 should be returned because each has articleId == "3000" - // the contained collections should only have the orderLine with articleId == "3000" - assertEquals( 2, orders.size() ); - for ( Iterator it = orders.iterator(); it.hasNext(); ) { - Order o = (Order) it.next(); - if ( order1.getOrderId() == o.getOrderId() ) { - assertEquals( 1, o.getLines().size() ); - assertEquals( "3000", o.getLines().iterator().next().getArticleId() ); - } - else if ( order3.getOrderId() == o.getOrderId() ) { - assertEquals( 1, o.getLines().size() ); - assertEquals( "3000", o.getLines().iterator().next().getArticleId() ); - } - else { - fail( "unknown order" ); - } - } - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testAliasWithNullOrNonNullRestrictions() { - Session s = openSession(); - s.getTransaction().begin(); - - Criteria rootCriteria = s.createCriteria( Order.class ); - // create alias, ensuring we stay on the root criteria - assertSame( rootCriteria, rootCriteria.createAlias( "orderLines", "ol", JoinFragment.LEFT_OUTER_JOIN ) ); - - // add restrictions to rootCriteria - assertSame( - rootCriteria, - rootCriteria.add( - Restrictions.or( - Restrictions.isNull( "ol.articleId" ), // Allow null - Restrictions.eq( "ol.articleId", "1000" ) - ) - ) - ); - - List orders = rootCriteria.list(); - - // order1 should be returned because it has an orderline with articleId == "1000"; - // the contained collection for order1 should only have the orderLine with articleId == "1000"; - // order2 should be returned because it has no orderlines - assertEquals( 2, orders.size() ); - for ( Object order : orders ) { - Order o = (Order) order; - if ( order1.getOrderId() == o.getOrderId() ) { - assertEquals( "1000", o.getLines().iterator().next().getArticleId() ); - } - else if ( order2.getOrderId() == o.getOrderId() ) { - assertEquals( 0, o.getLines().size() ); - } - else { - fail( "unknown order" ); - } - } - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testNonNullSubcriteriaRestrictionsOnRootCriteria() { - Session s = openSession(); - s.getTransaction().begin(); - - Criteria rootCriteria = s.createCriteria( Order.class ); - Criteria subCriteria = rootCriteria.createCriteria( "orderLines", "ol", JoinFragment.LEFT_OUTER_JOIN ); - assertNotSame( rootCriteria, subCriteria ); - - // add restriction to rootCriteria (NOT subcriteria) - assertSame( rootCriteria, rootCriteria.add( Restrictions.eq( "ol.articleId", "3000" ) ) ); - - List orders = rootCriteria.list(); - - // results should be the same as testAliasWithNonNullRestrictions() (using Criteria.createAlias()) - // order1 and order3 should be returned because each has articleId == "3000" - // the contained collections should only have the orderLine with articleId == "3000" - assertEquals( 2, orders.size() ); - for ( Iterator it = orders.iterator(); it.hasNext(); ) { - Order o = (Order) it.next(); - if ( order1.getOrderId() == o.getOrderId() ) { - assertEquals( 1, o.getLines().size() ); - assertEquals( "3000", o.getLines().iterator().next().getArticleId() ); - } - else if ( order3.getOrderId() == o.getOrderId() ) { - assertEquals( 1, o.getLines().size() ); - assertEquals( "3000", o.getLines().iterator().next().getArticleId() ); - } - else { - fail( "unknown order" ); - } - } - s.getTransaction().commit(); - s.close(); - } - - @Test - @TestForIssue( jiraKey = "HHH-9597") - public void testMultipleSubCriteriaRestrictionsOnCollections() { - Session s = openSession(); - s.getTransaction().begin(); - - Criteria rootCriteria = s.createCriteria(Order.class, "order"); - rootCriteria.createCriteria( "order.orderLines", "line", JoinType.LEFT_OUTER_JOIN ) - .add(Restrictions.eq("line.articleId", "3000")); - rootCriteria.createCriteria( "order.orderContacts", "contact", JoinType.LEFT_OUTER_JOIN ) - .add(Restrictions.eq("contact.contact", "Contact1")); - // result should be order1, because that's the only Order with: - // 1) orderLines containing an OrderLine with articleId == "3000" - // and 2) orderContacts containing an OrderContact with contact == "Contact1" - // Since both restrictions are in subcriteria, both collections should be non-filtered - // (i.e. includes all elements in both collections) - Order result = (Order) rootCriteria.uniqueResult(); - assertEquals( order1.getOrderId(), result.getOrderId() ); - assertEquals( 2, result.getContacts().size() ); - assertEquals( 2, result.getLines().size() ); - s.getTransaction().commit(); - s.close(); - } - - @Test - @TestForIssue( jiraKey = "HHH-9597") - public void testMultipleRootCriteriaRestrictionsOnCollections() { - Session s = openSession(); - s.getTransaction().begin(); - - Criteria rootCriteria = s.createCriteria(Order.class, "order"); - rootCriteria.createAlias( "order.orderLines", "line", JoinType.LEFT_OUTER_JOIN ) - .add(Restrictions.eq("line.articleId", "3000")); - rootCriteria.createAlias("order.orderContacts", "contact", JoinType.LEFT_OUTER_JOIN) - .add( Restrictions.eq( "contact.contact", "Contact1" ) ); - // result should be order1, because that's the only Order with: - // 1) orderLines containing an OrderLine with articleId == "3000" - // and 2) orderContacts containing an OrderContact with contact == "Contact1" - // Since both restrictions are in root criteria, both collections should be filtered - // to contain only the elements that satisfy the restrictions. - Order result = (Order) rootCriteria.uniqueResult(); - assertEquals( order1.getOrderId(), result.getOrderId() ); - assertEquals( 1, result.getLines().size() ); - assertEquals( "3000", result.getLines().iterator().next().getArticleId() ); - assertEquals( 1, result.getContacts().size() ); - assertEquals( "Contact1", result.getContacts().iterator().next().getContact() ); - s.getTransaction().commit(); - s.close(); - } - - @Test - @TestForIssue( jiraKey = "HHH-9597") - public void testRootAndSubCriteriaRestrictionsOnCollections() { - // the result of all Criteria in this test will be order1, because that's the only Order with: - // 1) orderLines containing an OrderLine with articleId == "3000" - // and 2) orderContacts containing an OrderContact with contact == "Contact1" - - Session s = openSession(); - s.getTransaction().begin(); - Criteria rootCriteria = s.createCriteria(Order.class, "order"); - rootCriteria.createCriteria("order.orderContacts", "contact", JoinType.LEFT_OUTER_JOIN) - .add( Restrictions.eq( "contact.contact", "Contact1" ) ); - rootCriteria.createAlias("order.orderLines", "line", JoinType.LEFT_OUTER_JOIN) - .add(Restrictions.eq("line.articleId", "3000")); - // Since restriction on orderLines is on root criteria, that collection should be filtered. - // Since restriction on orderContacts is on a subcriteria, that collection should be - // non-filtered (contain all its elements) - Order result = (Order) rootCriteria.uniqueResult(); - assertEquals( order1.getOrderId(), result.getOrderId() ); - assertEquals( 1, result.getLines().size() ); - assertEquals( "3000", result.getLines().iterator().next().getArticleId() ); - assertEquals( 2, result.getContacts().size() ); - s.getTransaction().commit(); - s.close(); - - // The following should have the same result as the previous, since it has the same - // restrictions applied in reverse order. - - s = openSession(); - s.getTransaction().begin(); - rootCriteria = s.createCriteria(Order.class, "order"); - rootCriteria.createCriteria("order.orderContacts", "contact", JoinType.LEFT_OUTER_JOIN) - .add(Restrictions.eq("contact.contact", "Contact1")); - rootCriteria.createAlias( "order.orderLines", "line", JoinType.LEFT_OUTER_JOIN ) - .add(Restrictions.eq("line.articleId", "3000")); - // Since restriction on orderLines is on root criteria, that collection should be filtered. - // Since restriction on orderContacts is on a subcriteria, that collection should be - // non-filtered (contain all its elements) - result = (Order) rootCriteria.uniqueResult(); - assertEquals( order1.getOrderId(), result.getOrderId() ); - assertEquals( 1, result.getLines().size() ); - assertEquals( "3000", result.getLines().iterator().next().getArticleId() ); - assertEquals( 2, result.getContacts().size() ); - s.getTransaction().commit(); - s.close(); - - // Even though the following seem redundant, there was a failure due to HHH-9597 - // that reproduced when filtering Order.orderContacts, but not order.orderLines. - - s = openSession(); - s.getTransaction().begin(); - rootCriteria = s.createCriteria(Order.class, "order"); - rootCriteria.createAlias( "order.orderContacts", "contact", JoinType.LEFT_OUTER_JOIN ) - .add(Restrictions.eq("contact.contact", "Contact1")); - rootCriteria.createCriteria( "order.orderLines", "line", JoinType.LEFT_OUTER_JOIN ) - .add(Restrictions.eq("line.articleId", "3000")); - // Since restriction on orderContacts is on root criteria, that collection should be filtered. - // Since restriction on orderLines is on a subcriteria, that collection should be - // non-filtered (contain all its elements) - result = (Order) rootCriteria.uniqueResult(); - assertEquals( order1.getOrderId(), result.getOrderId() ); - assertEquals( 2, result.getLines().size() ); - assertEquals( 1, result.getContacts().size() ); - assertEquals( "Contact1", result.getContacts().iterator().next().getContact() ); - s.getTransaction().commit(); - s.close(); - - // The following should have the same result as the previous, since it has the same - // restrictions applied in reverse order. - - s = openSession(); - s.getTransaction().begin(); - rootCriteria = s.createCriteria(Order.class, "order"); - rootCriteria.createCriteria( "order.orderLines", "line", JoinType.LEFT_OUTER_JOIN ) - .add(Restrictions.eq("line.articleId", "3000")); - rootCriteria.createAlias( "order.orderContacts", "contact", JoinType.LEFT_OUTER_JOIN ) - .add(Restrictions.eq("contact.contact", "Contact1")); - result = (Order) rootCriteria.uniqueResult(); - assertEquals( order1.getOrderId(), result.getOrderId() ); - assertEquals( 2, result.getLines().size() ); - assertEquals( 1, result.getContacts().size() ); - assertEquals( "Contact1", result.getContacts().iterator().next().getContact() ); - s.getTransaction().commit(); - s.close(); - } - - @Test - @TestForIssue( jiraKey = "HHH-9597") - public void testSubCriteriaRestrictionsOnCollectionsNestedInManyToOne() { - // the result of all Criteria in this test will be order1, because that's the only Order with: - // 1) orderContacts containing an OrderContact with contact == "Contact1" - // and 2) orderAddress.notifiedAddresses containing an Address with addressText == "over the rainbow" - - Session s = openSession(); - s.getTransaction().begin(); - Criteria rootCriteria = s.createCriteria(Order.class, "order"); - rootCriteria.createCriteria("order.orderContacts", "contact", JoinType.LEFT_OUTER_JOIN) - .add( Restrictions.eq( "contact.contact", "Contact1" ) ); - rootCriteria.createCriteria( "order.orderAddress", "orderAddress", JoinType.LEFT_OUTER_JOIN ) - .createCriteria( "orderAddress.notifiedAddresses", "notifiedAddress", JoinType.LEFT_OUTER_JOIN ) - .add( Restrictions.eq( "notifiedAddress.addressText", "over the rainbow" ) ); - - // Since restrictions are on subcriteria, the collections should n on orderLines is on root criteria, that collection should be filtered. - // Since restriction on orderContacts is on a subcriteria, that collection should be - // non-filtered (contain all its elements) - Order result = (Order) rootCriteria.uniqueResult(); - assertEquals( order1.getOrderId(), result.getOrderId() ); - assertEquals( 2, result.getContacts().size() ); - assertEquals( 2, result.getOrderAddress().getNotifiedAddresses().size() ); - s.getTransaction().commit(); - s.close(); - - // The following should have the same result as the previous, since it has the same - // restrictions applied in reverse order. - - s = openSession(); - s.getTransaction().begin(); - rootCriteria = s.createCriteria(Order.class, "order"); - rootCriteria.createCriteria( "order.orderAddress", "orderAddress", JoinType.LEFT_OUTER_JOIN ) - .createCriteria( "orderAddress.notifiedAddresses", "notifiedAddress", JoinType.LEFT_OUTER_JOIN ) - .add( Restrictions.eq( "notifiedAddress.addressText", "over the rainbow" ) ); - rootCriteria.createCriteria("order.orderContacts", "contact", JoinType.LEFT_OUTER_JOIN) - .add( Restrictions.eq( "contact.contact", "Contact1" ) ); - // Since restrictions are on subcriteria, the collections should n on orderLines is on root criteria, that collection should be filtered. - // Since restriction on orderContacts is on a subcriteria, that collection should be - // non-filtered (contain all its elements) - result = (Order) rootCriteria.uniqueResult(); - assertEquals( order1.getOrderId(), result.getOrderId() ); - assertEquals( 2, result.getContacts().size() ); - assertEquals( 2, result.getOrderAddress().getNotifiedAddresses().size() ); - s.getTransaction().commit(); - s.close(); - } - - protected void prepareTest() { - Session s = openSession(); - s.getTransaction().begin(); - - // Order with one mathing line - order1 = new Order(); - OrderLine line = new OrderLine(); - line.setArticleId( "1000" ); - order1.addLine( line ); - line = new OrderLine(); - line.setArticleId( "3000" ); - order1.addLine( line ); - s.persist( order1 ); - - OrderContact contact = new OrderContact(); - contact.setContact( "Contact1" ); - order1.addContact( contact ); - contact = new OrderContact(); - contact.setContact( "Contact2" ); - order1.addContact( contact ); - - OrderAddress orderAddress = new OrderAddress(); - Address address = new Address(); - address.setAddressText( "over the rainbow" ); - orderAddress.setDeliveryAddress( address ); - Address otherAddress = new Address(); - otherAddress.setAddressText( "other place" ); - orderAddress.getNotifiedAddresses().add( address ); - orderAddress.getNotifiedAddresses().add( otherAddress ); - order1.setOrderAddress( orderAddress ); - - s.persist( order1 ); - - // Order with no lines - order2 = new Order(); - contact = new OrderContact(); - contact.setContact( "Contact1" ); - order2.addContact( contact ); - s.persist( order2 ); - - // Order with non-matching line - order3 = new Order(); - line = new OrderLine(); - line.setArticleId( "3000" ); - order3.addLine( line ); - s.persist( order3 ); - - s.getTransaction().commit(); - s.close(); - } - - protected void cleanupTest() { - Session s = openSession(); - s.getTransaction().begin(); - - List orders = s.createQuery( "from Order" ).list(); - - for( Object order : orders ) { - s.delete( order ); - } - s.createQuery( "delete from OrderContact" ).executeUpdate(); - - s.createQuery( "delete from OrderLine" ).executeUpdate(); - - s.createQuery( "delete from Order" ).executeUpdate(); - - s.getTransaction().commit(); - s.close(); - } - - private static boolean isBlank(String s) { - return s == null || s.trim().length() == 0; - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/SessionCreateQueryFromCriteriaTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/SessionCreateQueryFromCriteriaTest.java deleted file mode 100644 index e11f763ffd..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/SessionCreateQueryFromCriteriaTest.java +++ /dev/null @@ -1,150 +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 . - */ -package org.hibernate.test.criteria; - -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import jakarta.persistence.Table; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.CriteriaQuery; -import jakarta.persistence.criteria.Root; -import java.util.Optional; -import java.util.stream.Stream; - -import org.hibernate.ScrollableResults; -import org.hibernate.Session; -import org.hibernate.dialect.AbstractHANADialect; -import org.junit.After; -import org.junit.Test; -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - -/** - * @author Andrea Boriero - */ -@TestForIssue(jiraKey = "HHH-10950") -public class SessionCreateQueryFromCriteriaTest extends BaseCoreFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {TestEntity.class}; - } - - @After - public void tearDown() { - try (Session s = openSession()) { - session.getTransaction().begin(); - try { - s.createQuery( "delete from TestEntity" ).executeUpdate(); - s.getTransaction().commit(); - } - catch (Exception e) { - if ( s.getTransaction().isActive() ) { - s.getTransaction().rollback(); - } - throw e; - } - } - } - - @Test - public void testUniqueResult() { - final String entityName = "expected"; - try (Session session = openSession()) { - final CriteriaQuery query = createTestEntityCriteriaQuery( entityName, session ); - final Optional result = session.createQuery( query ).uniqueResultOptional(); - assertThat( result.isPresent(), is( false ) ); - } - } - - private CriteriaQuery createTestEntityCriteriaQuery( - String entityName, - Session session) { - final CriteriaBuilder builder = session.getCriteriaBuilder(); - final CriteriaQuery query = - builder.createQuery( TestEntity.class ); - final Root fromTestEntity = query.from( TestEntity.class ); - query.select( fromTestEntity ); - query.where( builder.equal( - fromTestEntity.get( "name" ), - entityName - ) ); - return query; - } - - @Test - public void testStreamMethod() { - final String entityName = "expected"; - insertTestEntity( entityName ); - try (Session session = openSession()) { - final CriteriaQuery query = createTestEntityCriteriaQuery( - entityName, - session - ); - final Stream stream = session.createQuery( query ).stream(); - assertThat( stream.count(), is( 1L ) ); - } - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = "HANA only supports forward-only cursors") - public void testScrollMethod() { - final String entityName = "expected"; - insertTestEntity( entityName ); - try (Session session = openSession()) { - final CriteriaQuery query = createTestEntityCriteriaQuery( - entityName, - session - ); - try (final ScrollableResults scroll = session.createQuery( query ).scroll()) { - assertThat( scroll.first(), is( true ) ); - } - - } - } - - private void insertTestEntity(String name) { - final TestEntity entity = new TestEntity(); - entity.setName( name ); - try (Session s = openSession()) { - session.getTransaction().begin(); - try { - s.save( entity ); - s.getTransaction().commit(); - } - catch (Exception e) { - if ( s.getTransaction().isActive() ) { - s.getTransaction().rollback(); - } - throw e; - } - } - } - - @Entity(name = "TestEntity") - @Table(name = "TEST_ENTITY") - public static class TestEntity { - @Id - @GeneratedValue - private long id; - - private String name; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/limitexpression/Country.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/limitexpression/Country.java deleted file mode 100644 index 18681f0f42..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/limitexpression/Country.java +++ /dev/null @@ -1,19 +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 . - */ -package org.hibernate.test.criteria.limitexpression; - -public class Country { - private String code; - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/limitexpression/LimitExpressionTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/limitexpression/LimitExpressionTest.java deleted file mode 100644 index 3916318328..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/limitexpression/LimitExpressionTest.java +++ /dev/null @@ -1,80 +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 . - */ -package org.hibernate.test.criteria.limitexpression; - -import java.util.Arrays; -import java.util.List; - -import org.hibernate.criterion.Restrictions; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.hibernate.testing.transaction.TransactionUtil; - -import org.junit.Test; - -import static junit.framework.TestCase.assertTrue; -import static junit.framework.TestCase.fail; - -/** - * @author Andrea Boriero - */ - -@RequiresDialectFeature( - value = DialectChecks.SupportLimitCheck.class, - comment = "Dialect does not support limit" -) -public class LimitExpressionTest extends BaseNonConfigCoreFunctionalTestCase { - - @Override - public String[] getMappings() { - return new String[] {"criteria/limitexpression/domain.hbm.xml"}; - } - - @Override - public String getCacheConcurrencyStrategy() { - return null; - } - - @Test - @TestForIssue(jiraKey = "HHH-915") - public void testWithFetchJoin() { - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - final List stateCodes = Arrays.asList( "DC", "CT" ); - final Criteria crit = session.createCriteria( Person.class ); - crit.createCriteria( "states" ).add( Restrictions.in( "code", stateCodes ) ); - crit.setMaxResults( 10 ); - crit.list(); - } ); - } - - @Test - @TestForIssue(jiraKey = "HHH-11278") - public void testAnEmptyListIsReturnedWhenSetMaxResultsToZero() { - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - final Criteria crit = session.createCriteria( Person.class ); - crit.setMaxResults( 0 ); - final List list = crit.list(); - assertTrue( "The list should be empty with setMaxResults 0", list.isEmpty() ); - } ); - } - - @Override - protected void prepareTest() throws Exception { - TransactionUtil.doInHibernate( this::sessionFactory, session -> { - Person p = new Person(); - session.save( p ); - }); - } - - @Override - protected boolean isCleanupTestDataRequired() { - return true; - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/limitexpression/Person.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/limitexpression/Person.java deleted file mode 100644 index 4829d48ecb..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/limitexpression/Person.java +++ /dev/null @@ -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 . - */ -package org.hibernate.test.criteria.limitexpression; - -import java.util.Set; - -public class Person { - private Long id; - private Set states; - private Set countries; - - public Set getStates() { - return states; - } - - public void setStates(Set states) { - this.states = states; - } - - public Set getCountries() { - return countries; - } - - public void setCountries(Set countries) { - this.countries = countries; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/limitexpression/UsState.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/limitexpression/UsState.java deleted file mode 100644 index 1db54342b4..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/limitexpression/UsState.java +++ /dev/null @@ -1,19 +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 . - */ -package org.hibernate.test.criteria.limitexpression; - -public class UsState { - private String code; - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/limitexpression/domain.hbm.xml b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/limitexpression/domain.hbm.xml deleted file mode 100644 index f3e1144574..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/limitexpression/domain.hbm.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/many_to_many/CriteriaManyToManyTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/many_to_many/CriteriaManyToManyTest.java deleted file mode 100644 index 3e6708948c..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/many_to_many/CriteriaManyToManyTest.java +++ /dev/null @@ -1,149 +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 . - */ -package org.hibernate.test.criteria.many_to_many; - -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.criterion.Restrictions; -import org.hibernate.sql.JoinType; - -import org.hibernate.testing.junit4.BaseNonConfigCoreFunctionalTestCase; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - * @author Janario Oliveira - */ -public class CriteriaManyToManyTest extends BaseNonConfigCoreFunctionalTestCase { - - private Seller[] persist(String prefix) { - Session session = openSession(); - - Transaction tx = session.beginTransaction(); - Seller seller1 = new Seller( prefix + "-seller1" ); - Seller seller2 = new Seller( prefix + "-seller2" ); - - Customer customer1 = new Customer( prefix + "-customer1" ); - Customer customer2 = new Customer( prefix + "-customer2" ); - Customer customer3 = new Customer( prefix + "-customer3" ); - - seller1.addCustomer( customer1 ); - seller1.addCustomer( customer2 ); - seller2.addCustomer( customer2 ); - seller2.addCustomer( customer3 ); - - session.persist( customer1 ); - session.persist( customer2 ); - session.persist( customer3 ); - session.persist( seller1 ); - session.persist( seller2 ); - - tx.commit(); - session.close(); - return new Seller[] {seller1, seller2}; - } - - @Test - public void testJoinTable() { - Seller[] sellers = persist( "join-table" ); - Seller seller1 = sellers[0]; - Seller seller2 = sellers[1]; - - Session session = openSession(); - - Criteria criteria = session.createCriteria( Seller.class, "s" ); - criteria.createCriteria( - "s.soldTo", - "c", - JoinType.INNER_JOIN, - Restrictions.eq( "name", "join-table-customer1" ) - ); - criteria.setResultTransformer( Criteria.DISTINCT_ROOT_ENTITY ); - @SuppressWarnings("unchecked") - List results = criteria.list(); - assertTrue( results.size() == 1 ); - assertTrue( results.contains( seller1 ) ); - assertFalse( results.contains( seller2 ) ); - - - criteria = session.createCriteria( Seller.class, "s" ); - criteria.createCriteria( - "s.soldTo", - "c", - JoinType.INNER_JOIN, - Restrictions.eq( "name", "join-table-customer2" ) - ); - criteria.setResultTransformer( Criteria.DISTINCT_ROOT_ENTITY ); - - @SuppressWarnings("unchecked") - List results2 = criteria.list(); - assertTrue( results2.size() == 2 ); - assertTrue( results2.contains( seller1 ) ); - assertTrue( results2.contains( seller2 ) ); - - session.close(); - } - - @Test - public void testMappedBy() { - Set customersAll = new LinkedHashSet(); - Seller[] sellers = persist( "mappedby" ); - customersAll.addAll( sellers[0].getSoldTo() ); - customersAll.addAll( sellers[1].getSoldTo() ); - - Customer[] customers = customersAll.toArray( new Customer[customersAll.size()] ); - Customer customer1 = customers[0]; - Customer customer2 = customers[1]; - Customer customer3 = customers[2]; - - Session session = openSession(); - - Criteria criteria = session.createCriteria( Customer.class, "c" ); - criteria.createCriteria( - "c.boughtFrom", - "s", - JoinType.INNER_JOIN, - Restrictions.eq( "name", "mappedby-seller1" ) - ); - criteria.setResultTransformer( Criteria.DISTINCT_ROOT_ENTITY ); - @SuppressWarnings("unchecked") - List results = criteria.list(); - assertTrue( results.size() == 2 ); - assertTrue( results.contains( customer1 ) ); - assertTrue( results.contains( customer2 ) ); - assertFalse( results.contains( customer3 ) ); - - - criteria = session.createCriteria( Customer.class, "c" ); - criteria.createCriteria( - "c.boughtFrom", - "s", - JoinType.INNER_JOIN, - Restrictions.eq( "name", "mappedby-seller2" ) - ); - criteria.setResultTransformer( Criteria.DISTINCT_ROOT_ENTITY ); - @SuppressWarnings("unchecked") - List results2 = criteria.list(); - assertTrue( results2.size() == 2 ); - assertFalse( results2.contains( customer1 ) ); - assertTrue( results2.contains( customer2 ) ); - assertTrue( results2.contains( customer3 ) ); - - session.close(); - } - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {Seller.class, Customer.class}; - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/many_to_many/Customer.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/many_to_many/Customer.java deleted file mode 100644 index 93f3d1bd10..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/many_to_many/Customer.java +++ /dev/null @@ -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 . - */ -package org.hibernate.test.criteria.many_to_many; - -import java.util.HashSet; -import java.util.Set; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import jakarta.persistence.ManyToMany; - -/** - * @author Janario Oliveira - */ -@Entity -public class Customer { - @Id - @GeneratedValue - private Integer id; - private String name; - - @ManyToMany(mappedBy = "soldTo") - private Set boughtFrom = new HashSet(); - - protected Customer() { - } - - public Customer(String name) { - this.name = name; - } - - public Set getBoughtFrom() { - return boughtFrom; - } - - @Override - public boolean equals(Object o) { - if ( !( o instanceof Customer ) ) { - return false; - } - - Customer customer = (Customer) o; - return name.equals( customer.name ); - - } - - @Override - public int hashCode() { - return name.hashCode(); - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/many_to_many/Seller.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/many_to_many/Seller.java deleted file mode 100644 index 24a4b51bbf..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/many_to_many/Seller.java +++ /dev/null @@ -1,64 +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 . - */ -package org.hibernate.test.criteria.many_to_many; - -import java.util.HashSet; -import java.util.Set; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.Id; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.JoinTable; -import jakarta.persistence.ManyToMany; - -/** - * @author Janario Oliveira - */ -@Entity -public class Seller { - @Id - @GeneratedValue - private Integer id; - private String name; - - @ManyToMany - @JoinTable(name = "seller_customer", - joinColumns = @JoinColumn(name = "seller_id"), - inverseJoinColumns = @JoinColumn(name = "customer_id")) - private Set soldTo = new HashSet(); - - protected Seller() { - } - - public Seller(String name) { - this.name = name; - } - - public Set getSoldTo() { - return soldTo; - } - - public void addCustomer(Customer customer) { - customer.getBoughtFrom().add( this ); - soldTo.add( customer ); - } - - @Override - public boolean equals(Object o) { - if ( !( o instanceof Seller ) ) { - return false; - } - - Seller seller = (Seller) o; - return name.equals( seller.name ); - } - - @Override - public int hashCode() { - return name.hashCode(); - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/mapsid/MapsIdOneToOneSelectTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/criteria/mapsid/MapsIdOneToOneSelectTest.java deleted file mode 100644 index b21aeff564..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/criteria/mapsid/MapsIdOneToOneSelectTest.java +++ /dev/null @@ -1,151 +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 . - */ - -package org.hibernate.test.criteria.mapsid; - -import java.io.Serializable; -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.MapsId; -import jakarta.persistence.OneToOne; -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.CriteriaQuery; -import jakarta.persistence.criteria.Root; -import jakarta.validation.constraints.NotNull; - -import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase; - -import org.hibernate.testing.TestForIssue; -import org.junit.Before; -import org.junit.Test; - -import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; -import static org.junit.Assert.assertNotNull; - -/** - * @author Cody Lerum - */ -public class MapsIdOneToOneSelectTest extends BaseEntityManagerFunctionalTestCase { - - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ - Post.class, PostDetails.class - }; - } - - @Before - public void prepareTestData() { - doInJPA( this::entityManagerFactory, entityManager -> { - Post post = new Post(); - post.setId( 1 ); - post.setName( "Name" ); - entityManager.persist( post ); - - PostDetails details = new PostDetails(); - details.setName( "Details Name" ); - details.setPost( post ); - entityManager.persist( details ); - }); - } - - @TestForIssue(jiraKey = "HHH-9296") - @Test - public void selectByParent() { - doInJPA( this::entityManagerFactory, entityManager -> { - Post post = entityManager.find( Post.class, 1 ); - - CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - CriteriaQuery query = cb.createQuery( PostDetails.class ); - Root root = query.from( PostDetails.class ); - query.where( cb.equal( root.get( "post" ), post ) ); - final PostDetails result = entityManager.createQuery( query ).getSingleResult(); - assertNotNull( result ); - }); - } - - @TestForIssue(jiraKey = "HHH-9296") - @Test - public void findByParentId() { - doInJPA( this::entityManagerFactory, entityManager -> { - Post post = entityManager.find( Post.class, 1 ); - PostDetails result = entityManager.find( PostDetails.class, post.getId() ); - assertNotNull( result ); - }); - } - - @Entity(name = "Post") - public static class Post implements Serializable { - - private static final long serialVersionUID = 1L; - - private Integer id; - - private String name; - - @Id - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @NotNull - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - } - - @Entity(name = "PostDetails") - public static class PostDetails implements Serializable { - - private static final long serialVersionUID = 1L; - - private Integer id; - - private String name; - - private Post post; - - @Id - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - @NotNull - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @OneToOne - @JoinColumn(name = "id") - @MapsId - public Post getPost() { - return post; - } - - public void setPost(Post post) { - this.post = post; - } - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/hql/CriteriaHQLAlignmentTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/hql/CriteriaHQLAlignmentTest.java deleted file mode 100644 index 75cadec897..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/hql/CriteriaHQLAlignmentTest.java +++ /dev/null @@ -1,394 +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 . - */ -package org.hibernate.test.hql; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Collections; -import jakarta.persistence.PersistenceException; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.criterion.Projections; -import org.hibernate.dialect.Oracle8iDialect; -import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.exception.SQLGrammarException; -import org.hibernate.hql.internal.ast.QueryTranslatorImpl; -import org.hibernate.hql.internal.ast.tree.SelectClause; -import org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory; -import org.hibernate.hql.spi.QueryTranslator; -import org.hibernate.hql.spi.QueryTranslatorFactory; -import org.hibernate.type.BigDecimalType; -import org.hibernate.type.BigIntegerType; -import org.hibernate.type.DoubleType; -import org.hibernate.type.LongType; - -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.TestForIssue; -import org.junit.After; -import org.junit.Before; -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; - -/** - * Tests cases for ensuring alignment between HQL and Criteria behavior. - * - * @author Max Rydahl Andersen - */ -public class CriteriaHQLAlignmentTest extends QueryTranslatorTestCase { - private boolean initialVersion2SqlFlagValue; - - @Before - public void setVersion2SqlFlag() { - initialVersion2SqlFlagValue = SelectClause.VERSION2_SQL; - SelectClause.VERSION2_SQL = true; - } - - @After - public void resetVersion2SqlFlag() { - SelectClause.VERSION2_SQL = initialVersion2SqlFlagValue; - } - - @Override - public String[] getMappings() { - return new String[] { - "hql/Animal.hbm.xml", - }; - } - - @Override - public boolean createSchema() { - return true; // needed for the Criteria return type test - } - - @Override - public boolean rebuildSessionFactoryOnError() { - return true; - } - - @Test - public void testHQLAggregationReturnType() { - // EJB3: COUNT returns Long - QueryTranslatorImpl translator = createNewQueryTranslator( "select count(*) from Human h" ); - assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); - assertEquals( "incorrect return type", LongType.INSTANCE, translator.getReturnTypes()[0] ); - - translator = createNewQueryTranslator( "select count(h.heightInches) from Human h" ); - assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); - assertEquals( "incorrect return type", LongType.INSTANCE, translator.getReturnTypes()[0] ); - - // MAX, MIN return the type of the state-field to which they are applied. - translator = createNewQueryTranslator( "select max(h.heightInches) from Human h" ); - assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); - assertEquals( "incorrect return type", DoubleType.INSTANCE, translator.getReturnTypes()[0] ); - - translator = createNewQueryTranslator( "select max(h.id) from Human h" ); - assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); - assertEquals( "incorrect return type", LongType.INSTANCE, translator.getReturnTypes()[0] ); - - // AVG returns Double. - translator = createNewQueryTranslator( "select avg(h.heightInches) from Human h" ); - assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); - assertEquals( "incorrect return type", DoubleType.INSTANCE, translator.getReturnTypes()[0] ); - - translator = createNewQueryTranslator( "select avg(h.id) from Human h" ); - assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); - assertEquals( "incorrect return type", DoubleType.INSTANCE, translator.getReturnTypes()[0] ); - - translator = createNewQueryTranslator( "select avg(h.bigIntegerValue) from Human h" ); - assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); - assertEquals( "incorrect return type", DoubleType.INSTANCE, translator.getReturnTypes()[0] ); - - // SUM returns Long when applied to state-fields of integral types (other than BigInteger); - translator = createNewQueryTranslator( "select sum(h.id) from Human h" ); - assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); - assertEquals( "incorrect return type", LongType.INSTANCE, translator.getReturnTypes()[0] ); - - translator = createNewQueryTranslator( "select sum(h.intValue) from Human h" ); - assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); - assertEquals( "incorrect return type", LongType.INSTANCE, translator.getReturnTypes()[0] ); - - // SUM returns Double when applied to state-fields of floating point types; - translator = createNewQueryTranslator( "select sum(h.heightInches) from Human h" ); - assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); - assertEquals( "incorrect return type", DoubleType.INSTANCE, translator.getReturnTypes()[0] ); - - translator = createNewQueryTranslator( "select sum(h.floatValue) from Human h" ); - assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); - assertEquals( "incorrect return type", DoubleType.INSTANCE, translator.getReturnTypes()[0] ); - - // SUM returns BigInteger when applied to state-fields of type BigInteger - translator = createNewQueryTranslator( "select sum(h.bigIntegerValue) from Human h" ); - assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); - assertEquals( "incorrect return type", BigIntegerType.INSTANCE, translator.getReturnTypes()[0] ); - - // SUM and BigDecimal when applied to state-fields of type BigDecimal. - translator = createNewQueryTranslator( "select sum(h.bigDecimalValue) from Human h" ); - assertEquals( "incorrect return type count", 1, translator.getReturnTypes().length ); - assertEquals( "incorrect return type", BigDecimalType.INSTANCE, translator.getReturnTypes()[0] ); - - // special case to test classicquery special case handling of count(*) - String hql = "select count(*) from Human h"; - QueryTranslatorFactory classic = new ClassicQueryTranslatorFactory(); - QueryTranslator oldQueryTranslator = classic.createQueryTranslator( hql, hql, Collections.EMPTY_MAP, - sessionFactory(), null ); - oldQueryTranslator.compile( Collections.EMPTY_MAP, true); - assertEquals( "incorrect return type count", 1, oldQueryTranslator.getReturnTypes().length ); - assertEquals( "incorrect return type", LongType.INSTANCE, oldQueryTranslator.getReturnTypes()[0] ); - - } - - @Test - @TestForIssue( jiraKey = "HHH-1724" ) - public void testCriteriaAggregationReturnType() { - Session s = openSession(); - s.beginTransaction(); - Human human = new Human(); - human.setBigIntegerValue( new BigInteger("42") ); - human.setBigDecimalValue( new BigDecimal(45) ); - s.save(human); - s.flush(); - s.clear(); - // EJB3: COUNT returns Long - Long longValue = (Long) s.createCriteria( Human.class ).setProjection( Projections.rowCount()).uniqueResult(); - assertEquals(longValue, new Long(1)); - longValue = (Long) s.createCriteria( Human.class ).setProjection( Projections.count("heightInches")).uniqueResult(); - assertEquals(longValue, new Long(1)); - - // MAX, MIN return the type of the state-field to which they are applied. - Double dblValue = (Double) s.createCriteria( Human.class ).setProjection( Projections.max( "heightInches" )).uniqueResult(); - assertNotNull(dblValue); - - longValue = (Long) s.createCriteria( Human.class ).setProjection( Projections.max( "id" )).uniqueResult(); - assertNotNull(longValue); - - // AVG returns Double. - dblValue = (Double) s.createCriteria( Human.class ).setProjection( Projections.avg( "heightInches" )).uniqueResult(); - assertNotNull(dblValue); - - dblValue = (Double) s.createCriteria( Human.class ).setProjection( Projections.avg( "id" )).uniqueResult(); - assertNotNull(dblValue); - - dblValue = (Double) s.createCriteria( Human.class ).setProjection( Projections.avg( "bigIntegerValue" )).uniqueResult(); - assertNotNull(dblValue); - - // SUM returns Long when applied to state-fields of integral types (other than BigInteger); - longValue = (Long) s.createCriteria( Human.class ).setProjection( Projections.sum( "id" )).uniqueResult(); - assertNotNull(longValue); - - longValue = (Long) s.createCriteria( Human.class ).setProjection( Projections.sum( "intValue" )).uniqueResult(); - assertNotNull(longValue); - - // SUM returns Double when applied to state-fields of floating point types; - dblValue = (Double) s.createCriteria( Human.class ).setProjection( Projections.sum( "heightInches" )).uniqueResult(); - assertNotNull(dblValue); - - dblValue = (Double) s.createCriteria( Human.class ).setProjection( Projections.sum( "floatValue" )).uniqueResult(); - assertNotNull(dblValue); - - // SUM returns BigInteger when applied to state-fields of type BigInteger - BigInteger bigIValue = (BigInteger) s.createCriteria( Human.class ).setProjection( Projections.sum( "bigIntegerValue" )).uniqueResult(); - assertNotNull(bigIValue); - - // SUM and BigDecimal when applied to state-fields of type BigDecimal. - BigDecimal bigDValue = (BigDecimal) s.createCriteria( Human.class ).setProjection( Projections.sum( "bigDecimalValue" )).uniqueResult(); - assertNotNull(bigDValue); - - s.delete( human ); - s.flush(); - s.getTransaction().commit(); - s.close(); - } - - @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 testCountReturnValues() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Human human1 = new Human(); - human1.setName( new Name( "John", 'Q', "Public" ) ); - human1.setNickName( "Johnny" ); - s.save(human1); - Human human2 = new Human(); - human2.setName( new Name( "John", 'A', "Doe" ) ); - human2.setNickName( "Johnny" ); - s.save( human2 ); - Human human3 = new Human(); - human3.setName( new Name( "John", 'A', "Doe" ) ); - human3.setNickName( "Jack" ); - s.save( human3 ); - Human human4 = new Human(); - human4.setName( new Name( "John", 'A', "Doe" ) ); - s.save( human4 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - - Long count = ( Long ) s.createQuery( "select count( * ) from Human" ).uniqueResult(); - assertEquals( 4, count.longValue() ); - s.clear(); - count = ( Long ) s.createCriteria( Human.class ) - .setProjection( Projections.rowCount() ) - .uniqueResult(); - assertEquals( 4, count.longValue() ); - s.clear(); - - count = ( Long ) s.createQuery( "select count( nickName ) from Human" ).uniqueResult(); - assertEquals( 3, count.longValue() ); - s.clear(); - count = ( Long ) s.createCriteria( Human.class ) - .setProjection( Projections.count( "nickName" ) ) - .uniqueResult(); - assertEquals( 3, count.longValue() ); - s.clear(); - - count = ( Long ) s.createQuery( "select count( distinct nickName ) from Human" ).uniqueResult(); - assertEquals( 2, count.longValue() ); - s.clear(); - count = ( Long ) s.createCriteria( Human.class ) - .setProjection( Projections.count( "nickName" ).setDistinct() ) - .uniqueResult(); - assertEquals( 2, count.longValue() ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - try { - count = ( Long ) s.createQuery( "select count( distinct name ) from Human" ).uniqueResult(); - if ( ! getDialect().supportsTupleDistinctCounts() ) { - fail( "expected SQLGrammarException" ); - } - assertEquals( 2, count.longValue() ); - } - catch ( SQLGrammarException ex ) { - if ( ! getDialect().supportsTupleDistinctCounts() ) { - // expected - } - else { - throw ex; - } - } - catch (PersistenceException e) { - SQLGrammarException cause = assertTyping( SQLGrammarException.class, e.getCause() ); - if ( ! getDialect().supportsTupleCounts() ) { - // expected - } - else { - throw e; - } - } - finally { - t.rollback(); - s.close(); - } - - s = openSession(); - t = s.beginTransaction(); - try { - count = ( Long ) s.createCriteria( Human.class ) - .setProjection( Projections.count( "name" ).setDistinct() ) - .uniqueResult(); - if ( ! getDialect().supportsTupleDistinctCounts() ) { - fail( "expected SQLGrammarException" ); - } - assertEquals( 2, count.longValue() ); - } - catch ( SQLGrammarException ex ) { - if ( ! getDialect().supportsTupleDistinctCounts() ) { - // expected - } - else { - throw ex; - } - } - finally { - t.rollback(); - s.close(); - } - - s = openSession(); - t = s.beginTransaction(); - count = ( Long ) s.createQuery( "select count( distinct name.first ) from Human" ).uniqueResult(); - assertEquals( 1, count.longValue() ); - s.clear(); - count = ( Long ) s.createCriteria( Human.class ) - .setProjection( Projections.count( "name.first" ).setDistinct() ) - .uniqueResult(); - assertEquals( 1, count.longValue() ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - try { - count = ( Long ) s.createQuery( "select count( name ) from Human" ).uniqueResult(); - if ( ! getDialect().supportsTupleCounts() ) { - fail( "expected SQLGrammarException" ); - } - assertEquals( 1, count.longValue() ); - } - catch ( SQLGrammarException ex ) { - if ( ! getDialect().supportsTupleCounts() ) { - // expected - } - else { - throw ex; - } - } - catch (PersistenceException e) { - SQLGrammarException cause = assertTyping( SQLGrammarException.class, e.getCause() ); - if ( ! getDialect().supportsTupleCounts() ) { - // expected - } - else { - throw e; - } - } - finally { - t.rollback(); - s.close(); - } - - s = openSession(); - t = s.beginTransaction(); - try { - count = ( Long ) s.createCriteria( Human.class ) - .setProjection( Projections.count( "name" ) ) - .uniqueResult(); - if ( ! getDialect().supportsTupleCounts() ) { - fail( "expected SQLGrammarException" ); - } - assertEquals( 1, count.longValue() ); - } - catch ( SQLGrammarException ex ) { - if ( ! getDialect().supportsTupleCounts() ) { - // expected - } - else { - throw ex; - } - } - finally { - t.rollback(); - s.close(); - } - - s = openSession(); - t = s.beginTransaction(); - s.createQuery( "delete from Human" ).executeUpdate(); - t.commit(); - s.close(); - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/idprops/CriteriaIdPropertyReferencesTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/idprops/CriteriaIdPropertyReferencesTest.java deleted file mode 100644 index 7e3261fff1..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/idprops/CriteriaIdPropertyReferencesTest.java +++ /dev/null @@ -1,134 +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 . - */ -package org.hibernate.test.idprops; - -import jakarta.persistence.criteria.CriteriaBuilder; -import jakarta.persistence.criteria.CriteriaQuery; -import jakarta.persistence.criteria.Root; - -import org.junit.Test; - -import org.hibernate.query.Query; -import org.hibernate.Session; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; - -import static org.junit.Assert.assertEquals; - -/** - * @author Steve Ebersole - */ -public class CriteriaIdPropertyReferencesTest extends BaseCoreFunctionalTestCase { - @Override - public String[] getMappings() { - return new String[] { "idprops/Mapping.hbm.xml" }; - } - - - @Test - public void testCriteriaIdPropertyReferences() { - Session s = openSession(); - s.beginTransaction(); - Person p = new Person( new Long(1), "steve", 123 ); - s.save( p ); - Order o = new Order( new Long(1), p ); - LineItem l = new LineItem( o, "my-product", 2 ); - l.setId( "456" ); - s.save( o ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - - Criteria crit = s.createCriteria( Person.class ); - crit.setProjection( Projections.rowCount() ); - crit.add( Restrictions.eq( "id", new Integer(123) ) ); - long count = extractCount( crit ); - assertEquals( "Person by id prop (non-identifier)", 1, count ); - - crit = s.createCriteria( Person.class ); - crit.setProjection( Projections.rowCount() ); - crit.add( Restrictions.eq( "pk", new Long(1) ) ); - count = extractCount( crit ); - assertEquals( "Person by pk prop (identifier)", 1, count ); - - crit = s.createCriteria( Order.class ); - crit.setProjection( Projections.rowCount() ); - crit.add( Restrictions.eq( "number", new Long(1) ) ); - count = extractCount( crit ); - assertEquals( "Order by number prop (named identifier)", 1, count ); - - crit = s.createCriteria( Order.class ); - crit.setProjection( Projections.rowCount() ); - crit.add( Restrictions.eq( "id", new Long(1) ) ); - count = extractCount( crit ); - assertEquals( "Order by id prop (virtual identifier)", 1, count ); - - crit = s.createCriteria( LineItem.class ); - crit.setProjection( Projections.rowCount() ); - crit.add( Restrictions.eq( "id", "456" ) ); - count = extractCount( crit ); - assertEquals( "LineItem by id prop (non-identifier", 1, count ); - - if ( getDialect().supportsRowValueConstructorSyntax() ) { - crit = s.createCriteria( LineItem.class ); - crit.setProjection( Projections.rowCount() ); - crit.add( Restrictions.eq( "pk", new LineItemPK( o, "my-product" ) ) ); - count = extractCount( crit ); - assertEquals( "LineItem by pk prop (named composite identifier)", 1, count ); - } - - crit = s.createCriteria( Order.class ); - crit.setProjection( Projections.rowCount() ); - crit.createAlias( "orderee", "p" ).add( Restrictions.eq( "p.id", new Integer(1) ) ); - count = extractCount( crit ); - assertEquals( 0, count ); - - crit = s.createCriteria( Order.class ); - crit.setProjection( Projections.rowCount() ); - crit.createAlias( "orderee", "p" ).add( Restrictions.eq( "p.pk", new Long(1) ) ); - count = extractCount( crit ); - assertEquals( 1, count ); - - crit = s.createCriteria( Order.class ); - crit.setProjection( Projections.rowCount() ); - crit.createAlias( "orderee", "p" ).add( Restrictions.eq( "p.id", new Integer(123) ) ); - count = extractCount( crit ); - assertEquals( 1, count ); - - crit = s.createCriteria( LineItem.class ); - crit.setProjection( Projections.rowCount() ); - crit.add( Restrictions.eq( "pk.order.id", new Long(1) ) ); - count = extractCount( crit ); - assertEquals( 1, count ); - - crit = s.createCriteria( LineItem.class ); - crit.setProjection( Projections.rowCount() ); - crit.add( Restrictions.eq( "pk.order.number", new Long(1) ) ); - count = extractCount( crit ); - assertEquals( 1, count ); - - s.delete( o ); - s.delete( p ); - s.getTransaction().commit(); - s.close(); - } - - private long extractCount(Session s, String hql) { - return extractCount( s.createQuery( hql ) ); - } - - private long extractCount(Query query) { - return ( (Long) query.list().get( 0 ) ).longValue(); - } - - private long extractCount(Session s, CriteriaQuery crit) { - Query query = s.createQuery( crit ); - return ( (Long) query.list().get( 0 ) ).longValue(); - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/jpa/naturalId/ImmutableNaturalIdUsingCacheTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/jpa/naturalId/ImmutableNaturalIdUsingCacheTest.java deleted file mode 100644 index e230d274f7..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/jpa/naturalId/ImmutableNaturalIdUsingCacheTest.java +++ /dev/null @@ -1,193 +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.naturalid; - -import org.hibernate.Session; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; - -import org.hibernate.test.jpa.AbstractJPATest; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -/** - * @author Andrea Boriero - */ -public class ImmutableNaturalIdUsingCacheTest extends AbstractJPATest { - public String[] getMappings() { - return new String[] { "jpa/naturalid/User.hbm.xml" }; - } - - @Override - public void configure(Configuration cfg) { - super.configure( cfg ); - cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, "true" ); - cfg.setProperty( Environment.USE_QUERY_CACHE, "true" ); - cfg.setProperty( Environment.GENERATE_STATISTICS, "true" ); - } - - @Test - public void testNaturalIdCache() { - inTransaction( - s -> { - User u = new User( "steve", "superSecret" ); - s.persist( u ); - } - ); - - - sessionFactory().getStatistics().clear(); - - inTransaction( - s -> { - User u = ( User ) s.createCriteria( User.class ) - .add( Restrictions.naturalId().set( "userName", "steve" ) ) - .setCacheable( true ) - .uniqueResult(); - assertNotNull( u ); - } - ); - - assertEquals( 1, sessionFactory().getStatistics().getNaturalIdQueryExecutionCount() ); - assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() ); - assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCachePutCount() );//1: no stats since hbm.xml can't enable NaturalId caching - - inTransaction( - s -> { - User v = new User( "gavin", "supsup" ); - s.persist( v ); - } - ); - - sessionFactory().getStatistics().clear(); - - inTransaction( - s -> { - User u = ( User ) s.createCriteria( User.class ) - .add( Restrictions.naturalId().set( "userName", "steve" ) ) - .setCacheable( true ) - .uniqueResult(); - assertNotNull( u ); - assertEquals( 1, sessionFactory().getStatistics().getNaturalIdQueryExecutionCount() );//0: incorrect stats since hbm.xml can't enable NaturalId caching - assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() );//0: no stats since hbm.xml can't enable NaturalId caching - u = ( User ) s.createCriteria( User.class ) - .add( Restrictions.naturalId().set( "userName", "steve" ) ) - .setCacheable( true ) - .uniqueResult(); - assertNotNull( u ); - assertEquals( 1, sessionFactory().getStatistics().getNaturalIdQueryExecutionCount() );//0: incorrect stats since hbm.xml can't enable NaturalId caching - assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() );//0: no stats since hbm.xml can't enable NaturalId caching - - } - ); - - inTransaction( - s -> s.createQuery( "delete User" ).executeUpdate() - ); - } - - @Test - public void testNaturalIdDeleteUsingCache() { - Session s = openSession(); - s.beginTransaction(); - User u = new User( "steve", "superSecret" ); - s.persist( u ); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getStatistics().clear(); - - s = openSession(); - s.beginTransaction(); - u = ( User ) s.createCriteria( User.class ) - .add( Restrictions.naturalId().set( "userName", "steve" ) ) - .setCacheable( true ) - .uniqueResult(); - assertNotNull( u ); - s.getTransaction().commit(); - s.close(); - - assertEquals( 1, sessionFactory().getStatistics().getNaturalIdQueryExecutionCount() ); - assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() ); - assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCachePutCount() );//0: no stats since hbm.xml can't enable NaturalId caching - - sessionFactory().getStatistics().clear(); - - s = openSession(); - s.beginTransaction(); - u = ( User ) s.createCriteria( User.class ) - .add( Restrictions.naturalId().set( "userName", "steve" ) ) - .setCacheable( true ) - .uniqueResult(); - assertNotNull( u ); - assertEquals( 1, sessionFactory().getStatistics().getNaturalIdQueryExecutionCount() );//0: incorrect stats since hbm.xml can't enable NaturalId caching - assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() );//1: incorrect stats since hbm.xml can't enable NaturalId caching - - s.delete( u ); - - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - u = ( User ) s.createCriteria( User.class ) - .add( Restrictions.naturalId().set( "userName", "steve" ) ) - .setCacheable( true ) - .uniqueResult(); - assertNull( u ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testNaturalIdRecreateUsingCache() { - testNaturalIdDeleteUsingCache(); - - Session s = openSession(); - s.beginTransaction(); - User u = new User( "steve", "superSecret" ); - s.persist( u ); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getStatistics().clear(); - - s = openSession(); - s.beginTransaction(); - u = ( User ) s.createCriteria( User.class ) - .add( Restrictions.naturalId().set( "userName", "steve" ) ) - .setCacheable( true ) - .uniqueResult(); - assertNotNull( u ); - - assertEquals( 1, sessionFactory().getStatistics().getNaturalIdQueryExecutionCount() ); - assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() ); - assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCachePutCount() );//1: no stats since hbm.xml can't enable NaturalId caching - - sessionFactory().getStatistics().clear(); - s.getTransaction().commit(); - s.close(); - s = openSession(); - s.beginTransaction(); - u = ( User ) s.createCriteria( User.class ) - .add( Restrictions.naturalId().set( "userName", "steve" ) ) - .setCacheable( true ) - .uniqueResult(); - assertNotNull( u ); - assertEquals( 1, sessionFactory().getStatistics().getNaturalIdQueryExecutionCount() );//0: incorrect stats since hbm.xml can't enable NaturalId caching - assertEquals( 0, sessionFactory().getStatistics().getNaturalIdCacheHitCount() );//1: incorrect stats since hbm.xml can't enable NaturalId caching - - s.delete( u ); - - s.getTransaction().commit(); - s.close(); - } - -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/ABCProxyTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/ABCProxyTest.java deleted file mode 100644 index da2e03feee..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/ABCProxyTest.java +++ /dev/null @@ -1,311 +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 . - */ -package org.hibernate.orm.test.legacy; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Test; - -import org.hibernate.Hibernate; -import org.hibernate.LockMode; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.dialect.HSQLDialect; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - - -public class ABCProxyTest extends LegacyTestCase { - @Override - public String[] getMappings() { - return new String[] { "legacy/ABCProxy.hbm.xml" }; - } - - @Test - public void testDiscriminatorFiltering() throws Exception { - if ( ( getDialect() instanceof HSQLDialect ) ) return; - Session s = openSession(); - Transaction t = s.beginTransaction(); - s.createQuery("from C1 c1 left join c1.c2s c2").list(); - s.createCriteria(C1.class).createCriteria("c2s").list(); - t.commit(); - s.close(); - } - - @Test - public void testNarrow() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - s.createQuery("from E e join e.reverse as b where b.count=1").list(); - s.createQuery("from E e join e.as as b where b.count=1").list(); - t.commit(); - s.close(); - } - - @Test - public void testSharedColumn() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - C1 c1 = new C1(); - C2 c2 = new C2(); - c1.setC2(c2); - c2.setC1(c1); - s.save(c1); s.save(c2); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - List list = s.createQuery( "from B" ).list(); - assertTrue( list.size()==2 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c1 = (C1) s.createQuery("from C1").uniqueResult(); - c2 = (C2) s.createQuery("from C2").uniqueResult(); - assertTrue( c1.getC2()==c2 ); - assertTrue( c2.getC1()==c1 ); - assertTrue( c1.getC2s().contains(c2) ); - assertTrue( c2.getC1s().contains(c1) ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c1 = (C1) s.get( A.class, c1.getId() ); - c2 = (C2) s.get( A.class, c2.getId() ); - assertTrue( c1.getC2()==c2 ); - assertTrue( c2.getC1()==c1 ); - assertTrue( c1.getC2s().contains(c2) ); - assertTrue( c2.getC1s().contains(c1) ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - s.delete(c1); s.delete(c2); - t.commit(); - s.close(); - - } - - @Test - public void testSubclassing() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - C1 c1 = new C1(); - D d = new D(); - d.setAmount(213.34f); - c1.setAddress("foo bar"); - c1.setCount(23432); - c1.setName("c1"); - c1.setD(d); - s.save(c1); - d.setId( c1.getId() ); - s.save(d); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - A c1a = (A) s.load( A.class, c1.getId() ); - assertFalse( Hibernate.isInitialized(c1a) ); - assertTrue( c1a.getName().equals("c1") ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - B c1b = (B) s.load( B.class, c1.getId() ); - assertTrue( - (c1b.getCount()==23432) && - c1b.getName().equals("c1") - ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c1 = (C1) s.load( C1.class, c1.getId() ); - assertTrue( - c1.getAddress().equals("foo bar") && - (c1.getCount()==23432) && - c1.getName().equals("c1") && - c1.getD().getAmount()>213.3f - ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c1a = (A) s.load( A.class, c1.getId() ); - assertTrue( c1a.getName().equals("c1") ); - c1 = (C1) s.load( C1.class, c1.getId() ); - assertTrue( - c1.getAddress().equals("foo bar") && - (c1.getCount()==23432) && - c1.getName().equals("c1") && - c1.getD().getAmount()>213.3f - ); - c1b = (B) s.load( B.class, c1.getId() ); - assertTrue( - (c1b.getCount()==23432) && - c1b.getName().equals("c1") - ); - assertTrue( c1a.getName().equals("c1") ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c1a = (A) s.load( A.class, c1.getId() ); - assertTrue( c1a.getName().equals("c1") ); - c1 = (C1) s.load( C1.class, c1.getId(), LockMode.UPGRADE ); - assertTrue( - c1.getAddress().equals("foo bar") && - (c1.getCount()==23432) && - c1.getName().equals("c1") && - c1.getD().getAmount()>213.3f - ); - c1b = (B) s.load( B.class, c1.getId(), LockMode.UPGRADE ); - assertTrue( - (c1b.getCount()==23432) && - c1b.getName().equals("c1") - ); - assertTrue( c1a.getName().equals("c1") ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c1a = (A) s.load( A.class, c1.getId() ); - c1 = (C1) s.load( C1.class, c1.getId() ); - c1b = (B) s.load( B.class, c1.getId() ); - assertTrue( c1a.getName().equals("c1") ); - assertTrue( - c1.getAddress().equals("foo bar") && - (c1.getCount()==23432) && - c1.getName().equals("c1") && - c1.getD().getAmount()>213.3f - ); - assertTrue( - (c1b.getCount()==23432) && - c1b.getName().equals("c1") - ); - for ( Object a : s.createQuery( "from A" ).list() ) { - s.delete( a ); - } - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - s.save( new B() ); - s.save( new A() ); - assertTrue( s.createQuery( "from B" ).list().size()==1 ); - assertTrue( s.createQuery( "from A" ).list().size()==2 ); - for ( Object a : s.createQuery( "from A" ).list() ) { - s.delete( a ); - } - t.commit(); - s.close(); - } - - @Test - public void testSubclassMap() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - B b = new B(); - s.save(b); - Map map = new HashMap(); - map.put("3", new Integer(1) ); - b.setMap(map); - s.flush(); - s.delete(b); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - map = new HashMap(); - map.put("3", new Integer(1) ); - b = new B(); - b.setMap(map); - s.save(b); - s.flush(); - s.delete(b); - t.commit(); - s.close(); - } - - @Test - public void testOneToOne() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - A a = new A(); - E d1 = new E(); - C1 c = new C1(); - E d2 = new E(); - a.setForward(d1); - d1.setReverse(a); - c.setForward(d2); - d2.setReverse(c); - Serializable aid = s.save(a); - Serializable d2id = s.save(d2); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - List l = s.createQuery( "from E e, A a where e.reverse = a.forward and a = ?" ) - .setEntity( 0, a ) - .list(); - assertTrue( l.size()==1 ); - l = s.createQuery( "from E e join fetch e.reverse" ).list(); - assertTrue( l.size()==2 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - l = s.createQuery( "from E e" ).list(); - assertTrue( l.size()==2 ); - E e = (E) l.get(0); - assertTrue( e==e.getReverse().getForward() ); - e = (E) l.get(1); - assertTrue( e==e.getReverse().getForward() ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - a = (A) s.load(A.class, aid); - d2 = (E) s.load(E.class, d2id); - assertTrue( a==a.getForward().getReverse() ); - assertTrue( d2==d2.getReverse().getForward() ); - s.delete(a); - s.delete( a.getForward() ); - s.delete(d2); - s.delete( d2.getReverse() ); - t.commit(); - - s = openSession(); - t = s.beginTransaction(); - l = s.createQuery( "from E e" ).list(); - assertTrue( l.size()==0 ); - t.commit(); - s.close(); - } - - -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/ComponentNotNullTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/ComponentNotNullTest.java deleted file mode 100644 index 663b3c4405..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/ComponentNotNullTest.java +++ /dev/null @@ -1,208 +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 . - */ -package org.hibernate.orm.test.legacy; -import java.util.ArrayList; - -import org.junit.Test; - -import org.hibernate.PropertyValueException; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; - -import static org.junit.Assert.fail; - -/** - * Test some cases of not-null properties inside components. - * - * @author Emmanuel Bernard - */ -public class ComponentNotNullTest extends LegacyTestCase { - @Override - public String[] getMappings() { - return new String[] { - "legacy/ComponentNotNullRoot.hbm.xml", - "legacy/One.hbm.xml", - "legacy/Many.hbm.xml", - "legacy/Simple.hbm.xml" }; - } - - @Override - public void configure(Configuration cfg) { - super.configure( cfg ); - cfg.setProperty( Environment.CHECK_NULLABILITY, "true" ); - } - - @Test - public void testComponentNotNull() throws Exception { - - //everything not null - // - Session s = openSession(); - Transaction t = s.beginTransaction(); - ComponentNotNullRoot root = new ComponentNotNullRoot(); - ComponentNotNull nullable = new ComponentNotNull(); - ComponentNotNull supercomp = new ComponentNotNull(); - ComponentNotNull subcomp = new ComponentNotNull(); - - root.setNullable(nullable); - subcomp.setProp1Subcomp("test"); - supercomp.setSubcomp(subcomp); - root.setSupercomp(supercomp); - s.save(root); - t.commit(); - s.close(); - - //null prop of a subcomp - // - s = openSession(); - t = s.beginTransaction(); - - root = new ComponentNotNullRoot(); - nullable = new ComponentNotNull(); - supercomp = new ComponentNotNull(); - subcomp = new ComponentNotNull(); - - root.setNullable(nullable); - // do not set property - //subcomp.setProp1Subcomp("test"); - supercomp.setSubcomp(subcomp); - root.setSupercomp(supercomp); - - - try { - s.save(root); - t.commit(); - fail("Inserting not-null null property should fail"); - } catch (PropertyValueException e) { - //succeed - } - t.rollback(); - s.close(); - - //null component having not-null column - // - s = openSession(); - t = s.beginTransaction(); - - root = new ComponentNotNullRoot(); - nullable = new ComponentNotNull(); - supercomp = new ComponentNotNull(); - subcomp = new ComponentNotNull(); - - root.setNullable(nullable); - // do not set supercomp for root - //subcomp.setProp1Subcomp("test"); - //supercomp.setSubcomp(subcomp); - //root.setSupercomp(supercomp); - - - try { - s.save(root); - t.commit(); - fail("Inserting not-null null property should fail"); - } catch (PropertyValueException e) { - //succeed - } - t.rollback(); - s.close(); - } - - @Test - public void testCompositeElement() throws Exception { - //composite-element nullable - Session s = openSession(); - Transaction t = s.beginTransaction(); - ComponentNotNullRoot root = new ComponentNotNullRoot(); - ComponentNotNull nullable = new ComponentNotNull(); - ComponentNotNull supercomp = new ComponentNotNull(); - ComponentNotNull subcomp = new ComponentNotNull(); - - root.setNullable(nullable); - subcomp.setProp1Subcomp("test"); - supercomp.setSubcomp(subcomp); - root.setSupercomp(supercomp); - - root.setComponents(new ArrayList()); - ComponentNotNullRoot.ContainerInnerClass cc = - new ComponentNotNullRoot.ContainerInnerClass(); - root.getComponents().add(cc); - - try { - s.save(root); - t.commit(); - fail("Inserting not-null many-to-one should fail"); - } catch (PropertyValueException e) { - //success - } - t.rollback(); - s.close(); - - //null nested component having not-null column - // - s = openSession(); - t = s.beginTransaction(); - - root = new ComponentNotNullRoot(); - nullable = new ComponentNotNull(); - supercomp = new ComponentNotNull(); - subcomp = new ComponentNotNull(); - - root.setNullable(nullable); - subcomp.setProp1Subcomp("test"); - supercomp.setSubcomp(subcomp); - root.setSupercomp(supercomp); - - root.setComponentsImplicit(new ArrayList()); - ComponentNotNullRoot.ContainerInnerClass nestedCc = - new ComponentNotNullRoot.ContainerInnerClass(); - cc = - new ComponentNotNullRoot.ContainerInnerClass(); - cc.setNested(nestedCc); - root.getComponentsImplicit().add(cc); - - try { - s.save(root); - t.commit(); - fail("Inserting not-null null property should fail"); - } catch (PropertyValueException e) { - //succeed - } - t.rollback(); - s.close(); - - //nested component having not-null column - // - s = openSession(); - t = s.beginTransaction(); - - root = new ComponentNotNullRoot(); - nullable = new ComponentNotNull(); - supercomp = new ComponentNotNull(); - subcomp = new ComponentNotNull(); - - root.setNullable(nullable); - subcomp.setProp1Subcomp("test"); - supercomp.setSubcomp(subcomp); - root.setSupercomp(supercomp); - - root.setComponentsImplicit(new ArrayList()); - nestedCc = - new ComponentNotNullRoot.ContainerInnerClass(); - cc = - new ComponentNotNullRoot.ContainerInnerClass(); - cc.setNested(nestedCc); - nestedCc.setNestedproperty("test"); - root.getComponentsImplicit().add(cc); - - s.save(root); - t.commit(); - s.close(); - } - -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/CustomSQLTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/CustomSQLTest.java deleted file mode 100644 index bb6a49f709..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/CustomSQLTest.java +++ /dev/null @@ -1,191 +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 . - */ - -//$Id: CustomSQLTest.java 10977 2006-12-12 23:28:04Z steve.ebersole@jboss.com $ -package org.hibernate.orm.test.legacy; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import org.hibernate.HibernateException; -import org.hibernate.Session; -import org.hibernate.dialect.Dialect; -import org.hibernate.dialect.CockroachDialect; -import org.hibernate.dialect.PostgreSQL81Dialect; -import org.hibernate.dialect.PostgreSQLDialect; - -import org.hibernate.testing.DialectCheck; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.SkipForDialect; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; - -/** - * @author MAX - * - */ -public class CustomSQLTest extends LegacyTestCase { - @Override - public String[] getMappings() { - return new String[] { "legacy/CustomSQL.hbm.xml" }; - } - - public static class NonIdentityGeneratorChecker implements DialectCheck { - @Override - public boolean isMatch(Dialect dialect) { - return !"identity".equals( getDialect().getNativeIdentifierGeneratorStrategy() ); - } - } - - @Test - @RequiresDialectFeature( NonIdentityGeneratorChecker.class ) - @SkipForDialect( value = {PostgreSQL81Dialect.class, PostgreSQLDialect.class, CockroachDialect.class}, jiraKey = "HHH-6704") - public void testInsert() throws HibernateException, SQLException { - Session s = openSession(); - s.beginTransaction(); - Role p = new Role(); - p.setName("Patient"); - s.save( p ); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictEntityRegion( Role.class ); - - s = openSession(); - s.beginTransaction(); - Role p2 = (Role) s.get(Role.class, Long.valueOf(p.getId())); - assertNotSame(p, p2); - assertEquals(p2.getId(),p.getId()); - assertTrue(p2.getName().equalsIgnoreCase(p.getName())); - s.delete(p2); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testJoinedSubclass() throws HibernateException, SQLException { - Session s = openSession(); - s.beginTransaction(); - Medication m = new Medication(); - m.setPrescribedDrug(new Drug()); - m.getPrescribedDrug().setName( "Morphine" ); - s.save( m.getPrescribedDrug() ); - s.save( m ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Medication m2 = (Medication) s.get(Medication.class, m.getId()); - assertNotSame(m, m2); - s.getTransaction().commit(); - s.close(); - } - -// @Test -// @RequiresDialectFeature( NonIdentityGeneratorChecker.class ) - public void testCollectionCUD() throws HibernateException, SQLException { - Role role = new Role(); - role.setName("Jim Flanders"); - Intervention iv = new Medication(); - iv.setDescription("JF medical intervention"); - role.getInterventions().add(iv); - - List sx = new ArrayList(); - sx.add("somewhere"); - sx.add("somehow"); - sx.add("whatever"); - role.setBunchOfStrings(sx); - - Session s = openSession(); - s.beginTransaction(); - s.save(role); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Role r = (Role) s.get(Role.class, Long.valueOf(role.getId())); - assertNotSame(role,r); - assertEquals(1,r.getInterventions().size()); - assertEquals(3, r.getBunchOfStrings().size()); - r.getBunchOfStrings().set(1, "replacement"); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - r = (Role) s.get(Role.class,new Long(role.getId())); - assertNotSame(role,r); - - assertEquals(r.getBunchOfStrings().get(1),"replacement"); - assertEquals(3, r.getBunchOfStrings().size()); - - r.getBunchOfStrings().set(1, "replacement"); - - r.getBunchOfStrings().remove(1); - s.flush(); - - r.getBunchOfStrings().clear(); - s.getTransaction().commit(); - s.close(); - } - -// @Test -// @RequiresDialectFeature( NonIdentityGeneratorChecker.class ) - public void testCRUD() throws HibernateException, SQLException { - Person p = new Person(); - p.setName("Max"); - p.setLastName("Andersen"); - p.setNationalID("110974XYZ"); - p.setAddress("P. P. Street 8"); - - Session s = openSession(); - s.beginTransaction(); - s.save(p); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictEntityRegion( Person.class ); - - s = openSession(); - s.beginTransaction(); - Person p2 = (Person) s.get(Person.class, p.getId()); - assertNotSame(p, p2); - assertEquals(p2.getId(),p.getId()); - assertEquals(p2.getLastName(),p.getLastName()); - s.flush(); - - List list = s.createQuery( "select p from Party as p" ).list(); - assertTrue(list.size() == 1); - - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - list = s.createQuery( "select p from Person as p where p.address = 'Lrkevnget 1'" ).list(); - assertTrue(list.size() == 0); - p.setAddress("Lrkevnget 1"); - s.update(p); - list = s.createQuery( "select p from Person as p where p.address = 'Lrkevnget 1'" ).list(); - assertTrue(list.size() == 1); - list = s.createQuery( "select p from Party as p where p.address = 'P. P. Street 8'" ).list(); - assertTrue(list.size() == 0); - - s.delete(p); - list = s.createQuery( "select p from Person as p" ).list(); - assertTrue(list.size() == 0); - - s.getTransaction().commit(); - s.close(); - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/FooBarTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/FooBarTest.java deleted file mode 100644 index 07425bd82c..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/FooBarTest.java +++ /dev/null @@ -1,5010 +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 . - */ -package org.hibernate.orm.test.legacy; - -import java.io.Serializable; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Time; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.SortedSet; -import java.util.TimeZone; -import java.util.TreeMap; -import java.util.TreeSet; - -import org.hibernate.FetchMode; -import org.hibernate.FlushMode; -import org.hibernate.Hibernate; -import org.hibernate.HibernateException; -import org.hibernate.LazyInitializationException; -import org.hibernate.LockMode; -import org.hibernate.ObjectNotFoundException; -import org.hibernate.query.Query; -import org.hibernate.QueryException; -import org.hibernate.ScrollableResults; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.TransactionException; -import org.hibernate.action.spi.BeforeTransactionCompletionProcess; -import org.hibernate.criterion.Example; -import org.hibernate.criterion.MatchMode; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.Restrictions; -import org.hibernate.dialect.AbstractHANADialect; -import org.hibernate.dialect.DB2Dialect; -import org.hibernate.dialect.DerbyDialect; -import org.hibernate.dialect.H2Dialect; -import org.hibernate.dialect.HSQLDialect; -import org.hibernate.dialect.InterbaseDialect; -import org.hibernate.dialect.MckoiDialect; -import org.hibernate.dialect.MySQLDialect; -import org.hibernate.dialect.CockroachDialect; -import org.hibernate.dialect.Oracle12cDialect; -import org.hibernate.dialect.Oracle8iDialect; -import org.hibernate.dialect.PointbaseDialect; -import org.hibernate.dialect.PostgreSQL81Dialect; -import org.hibernate.dialect.PostgreSQLDialect; -import org.hibernate.dialect.SAPDBDialect; -import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.dialect.SybaseDialect; -import org.hibernate.dialect.TeradataDialect; -import org.hibernate.dialect.TimesTenDialect; -import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; -import org.hibernate.engine.spi.SessionImplementor; -import org.hibernate.event.spi.EventSource; -import org.hibernate.internal.util.SerializationHelper; -import org.hibernate.internal.util.collections.JoinedIterator; -import org.hibernate.jdbc.AbstractReturningWork; -import org.hibernate.jdbc.AbstractWork; -import org.hibernate.proxy.HibernateProxy; -import org.hibernate.type.StandardBasicTypes; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialect; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.TestForIssue; -import org.hibernate.testing.env.ConnectionProviderBuilder; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -@RequiresDialectFeature(DialectChecks.SupportsNoColumnInsert.class) -public class FooBarTest extends LegacyTestCase { - - @Override - public String[] getMappings() { - return new String[] { - "legacy/FooBar.hbm.xml", - "legacy/Baz.hbm.xml", - "legacy/Qux.hbm.xml", - "legacy/Glarch.hbm.xml", - "legacy/Fum.hbm.xml", - "legacy/Fumm.hbm.xml", - "legacy/Fo.hbm.xml", - "legacy/One.hbm.xml", - "legacy/Many.hbm.xml", - "legacy/Immutable.hbm.xml", - "legacy/Fee.hbm.xml", - "legacy/Vetoer.hbm.xml", - "legacy/Holder.hbm.xml", - "legacy/Location.hbm.xml", - "legacy/Stuff.hbm.xml", - "legacy/Container.hbm.xml", - "legacy/Simple.hbm.xml", - "legacy/XY.hbm.xml" - }; - } - - @Test - public void testSaveOrUpdateCopyAny() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Bar bar = new Bar(); - One one = new One(); - bar.setObject(one); - s.save(bar); - GlarchProxy g = bar.getComponent().getGlarch(); - bar.getComponent().setGlarch(null); - s.delete(g); - s.flush(); - assertTrue( s.contains(one) ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Bar bar2 = (Bar) s.merge( bar ); - s.flush(); - s.delete(bar2); - s.flush(); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testRefreshProxy() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Glarch g = new Glarch(); - Serializable gid = s.save(g); - s.flush(); - s.clear(); - GlarchProxy gp = (GlarchProxy) s.load(Glarch.class, gid); - gp.getName(); //force init - s.refresh(gp); - s.delete(gp); - s.flush(); - s.getTransaction().commit(); - s.close(); - } - - @Test - @RequiresDialectFeature( - value = DialectChecks.SupportsCircularCascadeDeleteCheck.class, - comment = "db/dialect does not support circular cascade delete constraints" - ) - public void testOnCascadeDelete() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - baz.subs = new ArrayList(); - Baz sub = new Baz(); - sub.superBaz = baz; - baz.subs.add(sub); - s.save(baz); - s.flush(); - assertTrue( s.createQuery("from Baz").list().size()==2 ); - s.getTransaction().commit(); - s.beginTransaction(); - s.delete(baz); - s.getTransaction().commit(); - s.beginTransaction(); - assertTrue( s.createQuery("from Baz").list().size()==0 ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testRemoveFromIdbag() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - baz.setByteBag( new ArrayList() ); - byte[] bytes = { 12, 13 }; - baz.getByteBag().add( new byte[] { 10, 45 } ); - baz.getByteBag().add(bytes); - baz.getByteBag().add( new byte[] { 1, 11 } ); - baz.getByteBag().add( new byte[] { 12 } ); - s.save(baz); - s.flush(); - baz.getByteBag().remove(bytes); - s.flush(); - baz.getByteBag().add(bytes); - s.flush(); - s.delete(baz); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testLoad() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Qux q = new Qux(); - s.save(q); - BarProxy b = new Bar(); - s.save(b); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - q = (Qux) s.load(Qux.class, q.getKey() ); - b = (BarProxy) s.load( Foo.class, b.getKey() ); - b.getKey(); - assertFalse( Hibernate.isInitialized(b) ); - b.getBarString(); - assertTrue( Hibernate.isInitialized(b) ); - BarProxy b2 = (BarProxy) s.load( Bar.class, b.getKey() ); - Qux q2 = (Qux) s.load( Qux.class, q.getKey() ); - assertTrue( "loaded same object", q==q2 ); - assertTrue( "loaded same object", b==b2 ); - assertTrue( Math.round( b.getFormula() ) == b.getInt() / 2 ); - s.delete(q2); - s.delete( b2 ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testJoin() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Foo foo = new Foo(); - foo.setJoinedProp("foo"); - s.save( foo ); - s.flush(); - foo.setJoinedProp("bar"); - s.flush(); - String fid = foo.getKey(); - s.delete( foo ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Foo foo2 = new Foo(); - foo2.setJoinedProp("foo"); - s.save(foo2); - s.createQuery( "select foo.id from Foo foo where foo.joinedProp = 'foo'" ).list(); - assertNull( s.get(Foo.class, fid) ); - s.delete(foo2); - s.getTransaction().commit(); - s.close(); - - } - - @Test - public void testDereferenceLazyCollection() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - baz.setFooSet( new HashSet() ); - Foo foo = new Foo(); - baz.getFooSet().add(foo); - s.save(foo); - s.save(baz); - foo.setBytes( "foobar".getBytes() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - foo = (Foo) s.get( Foo.class, foo.getKey() ); - assertTrue( Hibernate.isInitialized( foo.getBytes() ) ); - assertTrue( foo.getBytes().length==6 ); - baz = (Baz) s.get( Baz.class, baz.getCode() ); - assertTrue( baz.getFooSet().size()==1 ); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictCollectionRegion("org.hibernate.test.legacy.Baz.fooSet"); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.get( Baz.class, baz.getCode() ); - assertFalse( Hibernate.isInitialized( baz.getFooSet() ) ); - baz.setFooSet(null); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - foo = (Foo) s.get( Foo.class, foo.getKey() ); - assertTrue( foo.getBytes().length==6 ); - baz = (Baz) s.get( Baz.class, baz.getCode() ); - assertFalse( Hibernate.isInitialized( baz.getFooSet() ) ); - assertTrue( baz.getFooSet().size()==0 ); - s.delete(baz); - s.delete(foo); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testMoveLazyCollection() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - Baz baz2 = new Baz(); - baz.setFooSet( new HashSet() ); - Foo foo = new Foo(); - baz.getFooSet().add(foo); - s.save(foo); - s.save(baz); - s.save(baz2); - foo.setBytes( "foobar".getBytes() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - foo = (Foo) s.get( Foo.class, foo.getKey() ); - assertTrue( Hibernate.isInitialized( foo.getBytes() ) ); - assertTrue( foo.getBytes().length==6 ); - baz = (Baz) s.get( Baz.class, baz.getCode() ); - assertTrue( baz.getFooSet().size()==1 ); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictCollectionRegion("org.hibernate.test.legacy.Baz.fooSet"); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.get( Baz.class, baz.getCode() ); - assertFalse( Hibernate.isInitialized( baz.getFooSet() ) ); - baz2 = (Baz) s.get( Baz.class, baz2.getCode() ); - baz2.setFooSet( baz.getFooSet() ); - baz.setFooSet(null); - assertFalse( Hibernate.isInitialized( baz2.getFooSet() ) ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - foo = (Foo) s.get( Foo.class, foo.getKey() ); - assertTrue( foo.getBytes().length==6 ); - baz = (Baz) s.get( Baz.class, baz.getCode() ); - baz2 = (Baz) s.get( Baz.class, baz2.getCode() ); - assertFalse( Hibernate.isInitialized( baz.getFooSet() ) ); - assertTrue( baz.getFooSet().size()==0 ); - assertTrue( Hibernate.isInitialized( baz2.getFooSet() ) ); //fooSet has batching enabled - assertTrue( baz2.getFooSet().size()==1 ); - s.delete(baz); - s.delete(baz2); - s.delete(foo); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testCriteriaCollection() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz bb = (Baz) s.createCriteria(Baz.class).uniqueResult(); - assertTrue( bb == null ); - Baz baz = new Baz(); - s.save( baz ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Baz b = (Baz) s.createCriteria(Baz.class).uniqueResult(); - assertTrue( Hibernate.isInitialized( b.getTopGlarchez() ) ); - assertTrue( b.getTopGlarchez().size() == 0 ); - s.delete( b ); - s.getTransaction().commit(); - s.close(); - } - - @Test - @SkipForDialect(value = CockroachDialect.class, comment = "https://github.com/cockroachdb/cockroach/issues/43007") - public void testQuery() throws Exception { - Session s = openSession(); - Transaction txn = s.beginTransaction(); - Foo foo = new Foo(); - s.save(foo); - Foo foo2 = new Foo(); - s.save(foo2); - foo.setFoo(foo2); - - List list = s.createQuery( "from Foo foo inner join fetch foo.foo" ).list(); - Foo foof = (Foo) list.get(0); - assertTrue( Hibernate.isInitialized( foof.getFoo() ) ); - - s.createQuery( "from Baz baz left outer join fetch baz.fooToGlarch" ).list(); - - list = s.createQuery( "select foo, bar from Foo foo left outer join foo.foo bar where foo = ?" ) - .setParameter( 0, foo, s.getTypeHelper().entity(Foo.class) ) - .list(); - Object[] row1 = (Object[]) list.get(0); - assertTrue( row1[0]==foo && row1[1]==foo2 ); - - s.createQuery( "select foo.foo.foo.string from Foo foo where foo.foo = 'bar'" ).list(); - s.createQuery( "select foo.foo.foo.foo.string from Foo foo where foo.foo = 'bar'" ).list(); - s.createQuery( "select foo from Foo foo where foo.foo.foo = 'bar'" ).list(); - s.createQuery( "select foo.foo.foo.foo.string from Foo foo where foo.foo.foo = 'bar'" ).list(); - s.createQuery( "select foo.foo.foo.string from Foo foo where foo.foo.foo.foo.string = 'bar'" ).list(); - if ( ! (getDialect() instanceof HSQLDialect) ) - s.createQuery( "select foo.string from Foo foo where foo.foo.foo.foo = foo.foo.foo" ).list(); - s.createQuery( "select foo.string from Foo foo where foo.foo.foo = 'bar' and foo.foo.foo.foo = 'baz'" ).list(); - s.createQuery( "select foo.string from Foo foo where foo.foo.foo.foo.string = 'a' and foo.foo.string = 'b'" ) - .list(); - - s.createQuery( "from Bar bar, foo in elements(bar.baz.fooArray)" ).list(); - - //s.find("from Baz as baz where baz.topComponents[baz].name = 'bazzz'"); - - if ( (getDialect() instanceof DB2Dialect) && !(getDialect() instanceof DerbyDialect) ) { - s.createQuery( "from Foo foo where lower( foo.foo.string ) = 'foo'" ).list(); - s.createQuery( "from Foo foo where lower( (foo.foo.string || 'foo') || 'bar' ) = 'foo'" ).list(); - s.createQuery( "from Foo foo where repeat( (foo.foo.string || 'foo') || 'bar', 2 ) = 'foo'" ).list(); - s.createQuery( - "from Bar foo where foo.foo.integer is not null and repeat( (foo.foo.string || 'foo') || 'bar', (5+5)/2 ) = 'foo'" - ).list(); - s.createQuery( - "from Bar foo where foo.foo.integer is not null or repeat( (foo.foo.string || 'foo') || 'bar', (5+5)/2 ) = 'foo'" - ).list(); - } - if (getDialect() instanceof SybaseDialect) { - s.createQuery( "select baz from Baz as baz join baz.fooArray foo group by baz order by sum(foo.float)" ) - .iterate(); - } - - s.createQuery( "from Foo as foo where foo.component.glarch.name is not null" ).list(); - s.createQuery( "from Foo as foo left outer join foo.component.glarch as glarch where glarch.name = 'foo'" ) - .list(); - - list = s.createQuery( "from Foo" ).list(); - assertTrue( list.size()==2 && list.get(0) instanceof FooProxy ); - list = s.createQuery( "from Foo foo left outer join foo.foo" ).list(); - assertTrue( list.size()==2 && ( (Object[]) list.get(0) )[0] instanceof FooProxy ); - - s.createQuery("from Bar, Bar").list(); - s.createQuery("from Foo, Bar").list(); - s.createQuery( "from Baz baz left join baz.fooToGlarch, Bar bar join bar.foo" ).list(); - s.createQuery( "from Baz baz left join baz.fooToGlarch join baz.fooSet" ).list(); - s.createQuery( "from Baz baz left join baz.fooToGlarch join fetch baz.fooSet foo left join fetch foo.foo" ) - .list(); - - list = s.createQuery( - "from Foo foo where foo.string='osama bin laden' and foo.boolean = true order by foo.string asc, foo.component.count desc" - ).list(); - assertTrue( "empty query", list.size()==0 ); - Iterator iter = s.createQuery( - "from Foo foo where foo.string='osama bin laden' order by foo.string asc, foo.component.count desc" - ).iterate(); - assertTrue( "empty iterator", !iter.hasNext() ); - - list = s.createQuery( "select foo.foo from Foo foo" ).list(); - assertTrue( "query", list.size()==1 ); - assertTrue( "returned object", list.get(0)==foo.getFoo() ); - foo.getFoo().setFoo(foo); - foo.setString("fizard"); - //The following test is disabled for databases with no subselects...also for Interbase (not sure why). - if ( - !(getDialect() instanceof MySQLDialect) && - !(getDialect() instanceof HSQLDialect) && - !(getDialect() instanceof MckoiDialect) && - !(getDialect() instanceof SAPDBDialect) && - !(getDialect() instanceof PointbaseDialect) && - !(getDialect() instanceof DerbyDialect) - ) { - // && !db.equals("weblogic") { - if ( !( getDialect() instanceof InterbaseDialect ) ) { - list = s.createQuery( "from Foo foo where ? = some elements(foo.component.importantDates)" ) - .setParameter( 0, foo.getTimestamp(), StandardBasicTypes.DATE ) - .list(); - assertTrue( "component query", list.size()==2 ); - } - if( !( getDialect() instanceof TimesTenDialect)) { - list = s.createQuery( "from Foo foo where size(foo.component.importantDates) = 3" ).list(); //WAS: 4 - assertTrue( "component query", list.size()==2 ); - list = s.createQuery( "from Foo foo where 0 = size(foo.component.importantDates)" ).list(); - assertTrue( "component query", list.size()==0 ); - } - list = s.createQuery( "from Foo foo where exists elements(foo.component.importantDates)" ).list(); - assertTrue( "component query", list.size()==2 ); - s.createQuery( "from Foo foo where not exists (from Bar bar where bar.id = foo.id)" ).list(); - - s.createQuery( - "select foo.foo from Foo foo where foo = some(select x from Foo x where x.long > foo.foo.long)" - ).list(); - s.createQuery( "select foo.foo from Foo foo where foo = some(from Foo x where (x.long > foo.foo.long))" ) - .list(); - if ( !( getDialect() instanceof TimesTenDialect)) { - s.createQuery( - "select foo.foo from Foo foo where foo.long = some( select max(x.long) from Foo x where (x.long > foo.foo.long) group by x.foo )" - ).list(); - } - s.createQuery( - "from Foo foo where foo = some(select x from Foo x where x.long > foo.foo.long) and foo.foo.string='baz'" - ).list(); - s.createQuery( - "from Foo foo where foo.foo.string='baz' and foo = some(select x from Foo x where x.long > foo.foo.long)" - ).list(); - s.createQuery( "from Foo foo where foo = some(select x from Foo x where x.long > foo.foo.long)" ).list(); - - s.createQuery( - "select foo.string, foo.date, foo.foo.string, foo.id from Foo foo, Baz baz where foo in elements(baz.fooArray) and foo.string like 'foo'" - ).iterate(); - } - list = s.createQuery( "from Foo foo where foo.component.count is null order by foo.component.count" ).list(); - assertTrue( "component query", list.size()==0 ); - list = s.createQuery( "from Foo foo where foo.component.name='foo'" ).list(); - assertTrue( "component query", list.size()==2 ); - list = s.createQuery( - "select distinct foo.component.name, foo.component.name from Foo foo where foo.component.name='foo'" - ).list(); - assertTrue( "component query", list.size()==1 ); - list = s.createQuery( "select distinct foo.component.name, foo.id from Foo foo where foo.component.name='foo'" ) - .list(); - assertTrue( "component query", list.size()==2 ); - list = s.createQuery( "select foo.foo from Foo foo" ).list(); - assertTrue( "query", list.size()==2 ); - list = s.createQuery( "from Foo foo where foo.id=?" ) - .setParameter( 0, foo.getKey(), StandardBasicTypes.STRING ) - .list(); - assertTrue( "id query", list.size()==1 ); - list = s.createQuery( "from Foo foo where foo.key=?" ) - .setParameter( 0, foo.getKey(), StandardBasicTypes.STRING ) - .list(); - assertTrue( "named id query", list.size()==1 ); - assertTrue( "id query", list.get(0)==foo ); - list = s.createQuery( "select foo.foo from Foo foo where foo.string='fizard'" ).list(); - assertTrue( "query", list.size()==1 ); - assertTrue( "returned object", list.get(0)==foo.getFoo() ); - list = s.createQuery( "from Foo foo where foo.component.subcomponent.name='bar'" ).list(); - assertTrue( "components of components", list.size()==2 ); - list = s.createQuery( "select foo.foo from Foo foo where foo.foo.id=?" ) - .setParameter( 0, foo.getFoo().getKey(), StandardBasicTypes.STRING ) - .list(); - assertTrue( "by id query", list.size()==1 ); - assertTrue( "by id returned object", list.get(0)==foo.getFoo() ); - - s.createQuery( "from Foo foo where foo.foo = ?" ).setParameter( 0, foo.getFoo(), s.getTypeHelper().entity(Foo.class) ).list(); - - assertTrue( !s.createQuery( "from Bar bar where bar.string='a string' or bar.string='a string'" ) - .iterate() - .hasNext() ); - - iter = s.createQuery( "select foo.component.name, elements(foo.component.importantDates) from Foo foo where foo.foo.id=?" ) - .setParameter( 0, foo.getFoo().getKey(), StandardBasicTypes.STRING ) - .iterate(); - int i=0; - while ( iter.hasNext() ) { - i++; - Object[] row = (Object[]) iter.next(); - assertTrue( row[0] instanceof String && ( row[1]==null || row[1] instanceof Date ) ); - } - assertTrue(i==3); //WAS: 4 - iter = s.createQuery( "select max( elements(foo.component.importantDates) ) from Foo foo group by foo.id" ) - .iterate(); - assertTrue( iter.next() instanceof Date ); - - list = s.createQuery( - "select foo.foo.foo.foo from Foo foo, Foo foo2 where" - + " foo = foo2.foo and not not ( not foo.string='fizard' )" - + " and foo2.string between 'a' and (foo.foo.string)" - + ( ( getDialect() instanceof HSQLDialect || getDialect() instanceof InterbaseDialect || getDialect() instanceof TimesTenDialect || getDialect() instanceof TeradataDialect) ? - " and ( foo2.string in ( 'fiz', 'blah') or 1=1 )" - : - " and ( foo2.string in ( 'fiz', 'blah', foo.foo.string, foo.string, foo2.string ) )" - ) - ).list(); - assertTrue( "complex query", list.size()==1 ); - assertTrue( "returned object", list.get(0)==foo ); - foo.setString("from BoogieDown -tinsel town =!@#$^&*())"); - list = s.createQuery( "from Foo foo where foo.string='from BoogieDown -tinsel town =!@#$^&*())'" ).list(); - assertTrue( "single quotes", list.size()==1 ); - list = s.createQuery( "from Foo foo where not foo.string='foo''bar'" ).list(); - assertTrue( "single quotes", list.size()==2 ); - list = s.createQuery( "from Foo foo where foo.component.glarch.next is null" ).list(); - assertTrue( "query association in component", list.size()==2 ); - Bar bar = new Bar(); - Baz baz = new Baz(); - baz.setDefaults(); - bar.setBaz(baz); - baz.setManyToAny( new ArrayList() ); - baz.getManyToAny().add(bar); - baz.getManyToAny().add(foo); - s.save(bar); - s.save(baz); - list = s.createQuery( - " from Bar bar where bar.baz.count=667 and bar.baz.count!=123 and not bar.baz.name='1-E-1'" - ).list(); - assertTrue( "query many-to-one", list.size()==1 ); - list = s.createQuery( " from Bar i where i.baz.name='Bazza'" ).list(); - assertTrue( "query many-to-one", list.size()==1 ); - - Iterator rs = s.createQuery( "select count(distinct foo.foo) from Foo foo" ).iterate(); - assertTrue( "count", ( (Long) rs.next() ).longValue()==2 ); - assertTrue( !rs.hasNext() ); - rs = s.createQuery( "select count(foo.foo.boolean) from Foo foo" ).iterate(); - assertTrue( "count", ( (Long) rs.next() ).longValue()==2 ); - assertTrue( !rs.hasNext() ); - rs = s.createQuery( "select count(*), foo.int from Foo foo group by foo.int" ).iterate(); - assertTrue( "count(*) group by", ( (Object[]) rs.next() )[0].equals( new Long(3) ) ); - assertTrue( !rs.hasNext() ); - rs = s.createQuery( "select sum(foo.foo.int) from Foo foo" ).iterate(); - assertTrue( "sum", ( (Long) rs.next() ).longValue()==4 ); - assertTrue( !rs.hasNext() ); - rs = s.createQuery( "select count(foo) from Foo foo where foo.id=?" ) - .setParameter( 0, foo.getKey(), StandardBasicTypes.STRING ) - .iterate(); - assertTrue( "id query count", ( (Long) rs.next() ).longValue()==1 ); - assertTrue( !rs.hasNext() ); - - s.createQuery( "from Foo foo where foo.boolean = ?" ) - .setParameter( 0, new Boolean(true), StandardBasicTypes.BOOLEAN ) - .list(); - - s.createQuery( "select new Foo(fo.x) from Fo fo" ).list(); - s.createQuery( "select new Foo(fo.integer) from Foo fo" ).list(); - - list = s.createQuery("select new Foo(fo.x) from Foo fo") - //.setComment("projection test") - .setCacheable(true) - .list(); - assertTrue(list.size()==3); - list = s.createQuery("select new Foo(fo.x) from Foo fo") - //.setComment("projection test 2") - .setCacheable(true) - .list(); - assertTrue(list.size()==3); - - rs = s.createQuery( "select new Foo(fo.x) from Foo fo" ).iterate(); - assertTrue( "projection iterate (results)", rs.hasNext() ); - assertTrue( "projection iterate (return check)", Foo.class.isAssignableFrom( rs.next().getClass() ) ); - - ScrollableResults sr = s.createQuery("select new Foo(fo.x) from Foo fo").scroll(); - assertTrue( "projection scroll (results)", sr.next() ); - assertTrue( "projection scroll (return check)", Foo.class.isAssignableFrom( sr.get(0).getClass() ) ); - - list = s.createQuery( "select foo.long, foo.component.name, foo, foo.foo from Foo foo" ).list(); - rs = list.iterator(); - int count=0; - while ( rs.hasNext() ) { - count++; - Object[] row = (Object[]) rs.next(); - assertTrue( row[0] instanceof Long ); - assertTrue( row[1] instanceof String ); - assertTrue( row[2] instanceof Foo ); - assertTrue( row[3] instanceof Foo ); - } - assertTrue(count!=0); - list = s.createQuery( "select avg(foo.float), max(foo.component.name), count(distinct foo.id) from Foo foo" ) - .list(); - rs = list.iterator(); - count=0; - while ( rs.hasNext() ) { - count++; - Object[] row = (Object[]) rs.next(); - assertTrue( row[0] instanceof Double ); - assertTrue( row[1] instanceof String ); - assertTrue( row[2] instanceof Long ); - } - assertTrue(count!=0); - list = s.createQuery( "select foo.long, foo.component, foo, foo.foo from Foo foo" ).list(); - rs = list.iterator(); - count=0; - while ( rs.hasNext() ) { - count++; - Object[] row = (Object[]) rs.next(); - assertTrue( row[0] instanceof Long ); - assertTrue( row[1] instanceof FooComponent ); - assertTrue( row[2] instanceof Foo ); - assertTrue( row[3] instanceof Foo ); - } - assertTrue(count!=0); - - s.save( new Holder("ice T") ); - s.save( new Holder("ice cube") ); - - assertTrue( s.createQuery( "from java.lang.Object as o" ).list().size()==15 ); - assertTrue( s.createQuery( "from Named" ).list().size()==7 ); - assertTrue( s.createQuery( "from Named n where n.name is not null" ).list().size()==4 ); - iter = s.createQuery( "from Named n" ).iterate(); - while ( iter.hasNext() ) { - assertTrue( iter.next() instanceof Named ); - } - - s.save( new Holder("bar") ); - iter = s.createQuery( "from Named n0, Named n1 where n0.name = n1.name" ).iterate(); - int cnt = 0; - while ( iter.hasNext() ) { - Object[] row = (Object[]) iter.next(); - if ( row[0]!=row[1] ) cnt++; - } - if ( !(getDialect() instanceof HSQLDialect) ) { - assertTrue(cnt==2); - assertTrue( s.createQuery( "from Named n0, Named n1 where n0.name = n1.name" ).list().size()==7 ); - } - - Query qu = s.createQuery("from Named n where n.name = :name"); - qu.getReturnTypes(); - qu.getNamedParameters(); - - iter = s.createQuery( "from java.lang.Object" ).iterate(); - int c = 0; - while ( iter.hasNext() ) { - iter.next(); - c++; - } - assertTrue(c==16); - - s.createQuery( "select baz.code, min(baz.count) from Baz baz group by baz.code" ).iterate(); - - iter = s.createQuery( "selecT baz from Baz baz where baz.stringDateMap['foo'] is not null or baz.stringDateMap['bar'] = ?" ) - .setParameter( 0, new Date(), StandardBasicTypes.DATE ) - .iterate(); - assertFalse( iter.hasNext() ); - list = s.createQuery( "select baz from Baz baz where baz.stringDateMap['now'] is not null" ).list(); - assertTrue( list.size()==1 ); - list = s.createQuery( - "select baz from Baz baz where baz.stringDateMap['now'] is not null and baz.stringDateMap['big bang'] < baz.stringDateMap['now']" - ).list(); - assertTrue( list.size()==1 ); - list = s.createQuery( "select index(date) from Baz baz join baz.stringDateMap date" ).list(); - System.out.println(list); - assertTrue( list.size()==2 ); - - s.createQuery( - "from Foo foo where foo.integer not between 1 and 5 and foo.string not in ('cde', 'abc') and foo.string is not null and foo.integer<=3" - ).list(); - - s.createQuery( "from Baz baz inner join baz.collectionComponent.nested.foos foo where foo.string is null" ) - .list(); - if ( !(getDialect() instanceof MySQLDialect) && !(getDialect() instanceof MckoiDialect) && !(getDialect() instanceof SAPDBDialect) && !(getDialect() instanceof PointbaseDialect) ) { - s.createQuery( - "from Baz baz inner join baz.fooSet where '1' in (from baz.fooSet foo where foo.string is not null)" - ).list(); - s.createQuery( - "from Baz baz where 'a' in elements(baz.collectionComponent.nested.foos) and 1.0 in elements(baz.collectionComponent.nested.floats)" - ).list(); - s.createQuery( - "from Baz baz where 'b' in elements(baz.collectionComponent.nested.foos) and 1.0 in elements(baz.collectionComponent.nested.floats)" - ).list(); - } - - s.createQuery( "from Foo foo join foo.foo where foo.foo in ('1','2','3')" ).list(); - if ( !(getDialect() instanceof HSQLDialect) ) - s.createQuery( "from Foo foo left join foo.foo where foo.foo in ('1','2','3')" ).list(); - s.createQuery( "select foo.foo from Foo foo where foo.foo in ('1','2','3')" ).list(); - s.createQuery( "select foo.foo.string from Foo foo where foo.foo in ('1','2','3')" ).list(); - s.createQuery( "select foo.foo.string from Foo foo where foo.foo.string in ('1','2','3')" ).list(); - s.createQuery( "select foo.foo.long from Foo foo where foo.foo.string in ('1','2','3')" ).list(); - s.createQuery( "select count(*) from Foo foo where foo.foo.string in ('1','2','3') or foo.foo.long in (1,2,3)" ) - .list(); - s.createQuery( "select count(*) from Foo foo where foo.foo.string in ('1','2','3') group by foo.foo.long" ) - .list(); - - s.createQuery( "from Foo foo1 left join foo1.foo foo2 left join foo2.foo where foo1.string is not null" ) - .list(); - s.createQuery( "from Foo foo1 left join foo1.foo.foo where foo1.string is not null" ).list(); - s.createQuery( "from Foo foo1 left join foo1.foo foo2 left join foo1.foo.foo foo3 where foo1.string is not null" ) - .list(); - - s.createQuery( "select foo.formula from Foo foo where foo.formula > 0" ).list(); - - int len = s.createQuery( "from Foo as foo join foo.foo as foo2 where foo2.id >'a' or foo2.id <'a'" ).list().size(); - assertTrue(len==2); - - for ( Object entity : s.createQuery( "from Holder" ).list() ) { - s.delete( entity ); - } - - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - baz = (Baz) s.createQuery("from Baz baz left outer join fetch baz.manyToAny").uniqueResult(); - assertTrue( Hibernate.isInitialized( baz.getManyToAny() ) ); - assertTrue( baz.getManyToAny().size()==2 ); - BarProxy barp = (BarProxy) baz.getManyToAny().get(0); - s.createQuery( "from Baz baz join baz.manyToAny" ).list(); - assertTrue( s.createQuery( "select baz from Baz baz join baz.manyToAny a where index(a) = 0" ).list().size()==1 ); - - FooProxy foop = (FooProxy) s.get( Foo.class, foo.getKey() ); - assertTrue( foop == baz.getManyToAny().get(1) ); - - barp.setBaz(baz); - assertTrue( - s.createQuery( "select bar from Bar bar where bar.baz.stringDateMap['now'] is not null" ).list().size()==1 ); - assertTrue( - s.createQuery( - "select bar from Bar bar join bar.baz b where b.stringDateMap['big bang'] < b.stringDateMap['now'] and b.stringDateMap['now'] is not null" - ).list() - .size()==1 ); - assertTrue( - s.createQuery( - "select bar from Bar bar where bar.baz.stringDateMap['big bang'] < bar.baz.stringDateMap['now'] and bar.baz.stringDateMap['now'] is not null" - ).list() - .size()==1 ); - - list = s.createQuery( "select foo.string, foo.component, foo.id from Bar foo" ).list(); - assertTrue ( ( (FooComponent) ( (Object[]) list.get(0) )[1] ).getName().equals("foo") ); - list = s.createQuery( "select elements(baz.components) from Baz baz" ).list(); - assertTrue( list.size()==2 ); - list = s.createQuery( "select bc.name from Baz baz join baz.components bc" ).list(); - assertTrue( list.size()==2 ); - //list = s.find("select bc from Baz baz join baz.components bc"); - - s.createQuery("from Foo foo where foo.integer < 10 order by foo.string").setMaxResults(12).list(); - - s.delete(barp); - s.delete(baz); - s.delete( foop.getFoo() ); - s.delete(foop); - txn.commit(); - s.close(); - } - - @Test - public void testCascadeDeleteDetached() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - List list = new ArrayList(); - list.add( new Fee() ); - baz.setFees( list ); - s.save( baz ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.get( Baz.class, baz.getCode() ); - s.getTransaction().commit(); - s.close(); - - assertFalse( Hibernate.isInitialized( baz.getFees() ) ); - - s = openSession(); - s.beginTransaction(); - s.delete( baz ); - s.flush(); - assertFalse( s.createQuery( "from Fee" ).iterate().hasNext() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = new Baz(); - list = new ArrayList(); - list.add( new Fee() ); - list.add( new Fee() ); - baz.setFees(list); - s.save( baz ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.get( Baz.class, baz.getCode() ); - Hibernate.initialize( baz.getFees() ); - s.getTransaction().commit(); - s.close(); - - assertTrue( baz.getFees().size() == 2 ); - - s = openSession(); - s.beginTransaction(); - s.delete(baz); - s.flush(); - assertFalse( s.createQuery( "from Fee" ).iterate().hasNext() ); - s.getTransaction().commit(); - s.close(); - - } - - @Test - public void testForeignKeys() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - Foo foo = new Foo(); - List bag = new ArrayList(); - bag.add(foo); - baz.setIdFooBag(bag); - baz.setFoo(foo); - s.save(baz); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.load( Baz.class, baz.getCode() ); - s.delete(baz); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testNonlazyCollection() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - s.save( baz ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.createCriteria(Baz.class) - //.setComment("criteria test") - .setFetchMode( "stringDateMap", FetchMode.JOIN ) - .uniqueResult(); - assertTrue( Hibernate.isInitialized( baz.getFooToGlarch() ) ); - assertTrue( Hibernate.isInitialized( baz.getFooComponentToFoo() ) ); - assertTrue( !Hibernate.isInitialized( baz.getStringSet() ) ); - assertTrue( Hibernate.isInitialized( baz.getStringDateMap() ) ); - s.delete(baz); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testReuseDeletedCollection() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - baz.setDefaults(); - s.save(baz); - s.flush(); - s.delete(baz); - Baz baz2 = new Baz(); - baz2.setStringArray( new String[] {"x-y-z"} ); - s.save(baz2); - s.getTransaction().commit(); - s.close(); - - baz2.setStringSet( baz.getStringSet() ); - baz2.setStringArray( baz.getStringArray() ); - baz2.setFooArray( baz.getFooArray() ); - - s = openSession(); - s.beginTransaction(); - s.update(baz2); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz2 = (Baz) s.load( Baz.class, baz2.getCode() ); - assertTrue( baz2.getStringArray().length==3 ); - assertTrue( baz2.getStringSet().size()==3 ); - s.delete(baz2); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testPropertyRef() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Holder h = new Holder(); - h.setName("foo"); - Holder h2 = new Holder(); - h2.setName("bar"); - h.setOtherHolder(h2); - Serializable hid = s.save(h); - Qux q = new Qux(); - q.setHolder(h2); - Serializable qid = s.save(q); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - h = (Holder) s.load(Holder.class, hid); - assertEquals( h.getName(), "foo"); - assertEquals( h.getOtherHolder().getName(), "bar"); - Object[] res = (Object[]) s.createQuery( "from Holder h join h.otherHolder oh where h.otherHolder.name = 'bar'" ) - .list() - .get(0); - assertTrue( res[0]==h ); - q = (Qux) s.get(Qux.class, qid); - assertTrue( q.getHolder() == h.getOtherHolder() ); - s.delete(h); - s.delete(q); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testQueryCollectionOfValues() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - baz.setDefaults(); - s.save(baz); - Glarch g = new Glarch(); - Serializable gid = s.save(g); - - if ( !(getDialect() instanceof MySQLDialect) && !(getDialect() instanceof HSQLDialect) /*&& !(dialect instanceof MckoiDialect)*/ && !(getDialect() instanceof SAPDBDialect) && !(getDialect() instanceof PointbaseDialect) && !(getDialect() instanceof TimesTenDialect) ) { - s.createFilter( baz.getFooArray(), "where size(this.bytes) > 0" ).list(); - s.createFilter( baz.getFooArray(), "where 0 in elements(this.bytes)" ).list(); - } - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.createQuery( "from Baz baz join baz.fooSet foo join foo.foo.foo foo2 where foo2.string = 'foo'" ).list(); - s.createQuery( "from Baz baz join baz.fooArray foo join foo.foo.foo foo2 where foo2.string = 'foo'" ).list(); - s.createQuery( "from Baz baz join baz.stringDateMap date where index(date) = 'foo'" ).list(); - s.createQuery( "from Baz baz join baz.topGlarchez g where index(g) = 'A'" ).list(); - s.createQuery( "select index(g) from Baz baz join baz.topGlarchez g" ).list(); - - assertTrue( s.createQuery( "from Baz baz left join baz.stringSet" ).list().size()==3 ); - baz = (Baz) s.createQuery( "from Baz baz join baz.stringSet str where str='foo'" ).list().get(0); - assertTrue( !Hibernate.isInitialized( baz.getStringSet() ) ); - baz = (Baz) s.createQuery( "from Baz baz left join fetch baz.stringSet" ).list().get(0); - assertTrue( Hibernate.isInitialized( baz.getStringSet() ) ); - assertTrue( s.createQuery( "from Baz baz join baz.stringSet string where string='foo'" ).list().size()==1 ); - assertTrue( s.createQuery( "from Baz baz inner join baz.components comp where comp.name='foo'" ).list().size()==1 ); - //List bss = s.find("select baz, ss from Baz baz inner join baz.stringSet ss"); - s.createQuery( "from Glarch g inner join g.fooComponents comp where comp.fee is not null" ).list(); - s.createQuery( "from Glarch g inner join g.fooComponents comp join comp.fee fee where fee.count > 0" ).list(); - s.createQuery( "from Glarch g inner join g.fooComponents comp where comp.fee.count is not null" ).list(); - - s.delete(baz); - s.delete( s.get(Glarch.class, gid) ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testBatchLoad() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - SortedSet stringSet = new TreeSet(); - stringSet.add("foo"); - stringSet.add("bar"); - Set fooSet = new HashSet(); - for (int i=0; i<3; i++) { - Foo foo = new Foo(); - s.save(foo); - fooSet.add(foo); - } - baz.setFooSet(fooSet); - baz.setStringSet(stringSet); - s.save(baz); - Baz baz2 = new Baz(); - fooSet = new HashSet(); - for (int i=0; i<2; i++) { - Foo foo = new Foo(); - s.save(foo); - fooSet.add(foo); - } - baz2.setFooSet(fooSet); - s.save(baz2); - Baz baz3 = new Baz(); - stringSet = new TreeSet(); - stringSet.add("foo"); - stringSet.add("baz"); - baz3.setStringSet(stringSet); - s.save(baz3); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.load( Baz.class, baz.getCode() ); - baz2 = (Baz) s.load( Baz.class, baz2.getCode() ); - baz3 = (Baz) s.load( Baz.class, baz3.getCode() ); - assertFalse( Hibernate.isInitialized(baz.getFooSet()) || Hibernate.isInitialized(baz2.getFooSet()) || Hibernate.isInitialized(baz3.getFooSet()) ); - assertFalse( Hibernate.isInitialized(baz.getStringSet()) || Hibernate.isInitialized(baz2.getStringSet()) || Hibernate.isInitialized(baz3.getStringSet()) ); - assertTrue( baz.getFooSet().size()==3 ); - assertTrue( Hibernate.isInitialized(baz.getFooSet()) && Hibernate.isInitialized(baz2.getFooSet()) && Hibernate.isInitialized(baz3.getFooSet())); - assertTrue( baz2.getFooSet().size()==2 ); - assertTrue( baz3.getStringSet().contains("baz") ); - assertTrue( Hibernate.isInitialized(baz.getStringSet()) && Hibernate.isInitialized(baz2.getStringSet()) && Hibernate.isInitialized(baz3.getStringSet())); - assertTrue( baz.getStringSet().size()==2 && baz2.getStringSet().size()==0 ); - s.delete(baz); - s.delete(baz2); - s.delete(baz3); - Iterator iter = new JoinedIterator( new Iterator[] { baz.getFooSet().iterator(), baz2.getFooSet().iterator() } ); - while ( iter.hasNext() ) s.delete( iter.next() ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testFetchInitializedCollection() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - Collection fooBag = new ArrayList(); - fooBag.add( new Foo() ); - fooBag.add( new Foo() ); - baz.setFooBag( fooBag ); - s.save(baz); - s.flush(); - fooBag = baz.getFooBag(); - s.createQuery( "from Baz baz left join fetch baz.fooBag" ).list(); - assertTrue( fooBag == baz.getFooBag() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.load( Baz.class, baz.getCode() ); - Object bag = baz.getFooBag(); - assertFalse( Hibernate.isInitialized( bag ) ); - s.createQuery( "from Baz baz left join fetch baz.fooBag" ).list(); - assertTrue( bag==baz.getFooBag() ); - assertTrue( baz.getFooBag().size() == 2 ); - s.delete(baz); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testLateCollectionAdd() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - List l = new ArrayList(); - baz.setStringList(l); - l.add( "foo" ); - Serializable id = s.save(baz); - l.add("bar"); - s.flush(); - l.add( "baz" ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.load(Baz.class, id); - assertTrue( baz.getStringList().size() == 3 && baz.getStringList().contains( "bar" ) ); - s.delete(baz); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testUpdate() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Foo foo = new Foo(); - s.save( foo ); - s.getTransaction().commit(); - s.close(); - - foo = (Foo) SerializationHelper.deserialize( SerializationHelper.serialize(foo) ); - - s = openSession(); - s.beginTransaction(); - FooProxy foo2 = (FooProxy) s.load( Foo.class, foo.getKey() ); - foo2.setString("dirty"); - foo2.setBoolean( new Boolean( false ) ); - foo2.setBytes( new byte[] {1, 2, 3} ); - foo2.setDate( null ); - foo2.setShort( new Short( "69" ) ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - foo2.setString( "dirty again" ); - s.update(foo2); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - foo2.setString( "dirty again 2" ); - s.update( foo2 ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Foo foo3 = new Foo(); - s.load( foo3, foo.getKey() ); - // There is an interbase bug that causes null integers to return as 0, also numeric precision is <= 15 - assertTrue( "update", foo2.equalsFoo(foo3) ); - s.delete( foo3 ); - doDelete( s, "from Glarch" ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testListRemove() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz b = new Baz(); - List stringList = new ArrayList(); - List feeList = new ArrayList(); - b.setFees(feeList); - b.setStringList(stringList); - feeList.add( new Fee() ); - feeList.add( new Fee() ); - feeList.add( new Fee() ); - feeList.add( new Fee() ); - stringList.add("foo"); - stringList.add("bar"); - stringList.add("baz"); - stringList.add("glarch"); - s.save(b); - s.flush(); - stringList.remove(1); - feeList.remove(1); - s.flush(); - s.evict(b); - s.refresh(b); - assertTrue( b.getFees().size()==3 ); - stringList = b.getStringList(); - assertTrue( - stringList.size()==3 && - "baz".equals( stringList.get(1) ) && - "foo".equals( stringList.get(0) ) - ); - s.delete(b); - doDelete( s, "from Fee" ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testFetchInitializedCollectionDupe() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - Collection fooBag = new ArrayList(); - fooBag.add( new Foo() ); - fooBag.add( new Foo() ); - baz.setFooBag(fooBag); - s.save( baz ); - s.flush(); - fooBag = baz.getFooBag(); - s.createQuery( "from Baz baz left join fetch baz.fooBag" ).list(); - assertTrue( Hibernate.isInitialized( fooBag ) ); - assertTrue( fooBag == baz.getFooBag() ); - assertTrue( baz.getFooBag().size() == 2 ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.load( Baz.class, baz.getCode() ); - Object bag = baz.getFooBag(); - assertFalse( Hibernate.isInitialized(bag) ); - s.createQuery( "from Baz baz left join fetch baz.fooBag" ).list(); - assertTrue( Hibernate.isInitialized( bag ) ); - assertTrue( bag==baz.getFooBag() ); - assertTrue( baz.getFooBag().size()==2 ); - s.delete(baz); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testSortables() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz b = new Baz(); - b.setName("name"); - SortedSet ss = new TreeSet(); - ss.add( new Sortable("foo") ); - ss.add( new Sortable("bar") ); - ss.add( new Sortable("baz") ); - b.setSortablez(ss); - s.save(b); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Criteria cr = s.createCriteria(Baz.class); - cr.setFetchMode( "topGlarchez", FetchMode.SELECT ); - List result = cr - .addOrder( Order.asc("name") ) - .list(); - assertTrue( result.size()==1 ); - b = (Baz) result.get(0); - assertTrue( b.getSortablez().size()==3 ); - assertEquals( ( (Sortable) b.getSortablez().iterator().next() ).getName(), "bar" ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - result = s.createQuery("from Baz baz left join fetch baz.sortablez order by baz.name asc") - .list(); - b = (Baz) result.get(0); - assertTrue( b.getSortablez().size()==3 ); - assertEquals( ( (Sortable) b.getSortablez().iterator().next() ).getName(), "bar" ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - result = s.createQuery("from Baz baz order by baz.name asc") - .list(); - b = (Baz) result.get(0); - assertTrue( b.getSortablez().size()==3 ); - assertEquals( ( (Sortable) b.getSortablez().iterator().next() ).getName(), "bar" ); - s.delete(b); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testFetchList() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - s.save(baz); - Foo foo = new Foo(); - s.save(foo); - Foo foo2 = new Foo(); - s.save(foo2); - s.flush(); - List list = new ArrayList(); - for ( int i=0; i<5; i++ ) { - Fee fee = new Fee(); - list.add(fee); - } - baz.setFees(list); - list = s.createQuery( "from Foo foo, Baz baz left join fetch baz.fees" ).list(); - assertTrue( Hibernate.isInitialized( ( (Baz) ( (Object[]) list.get(0) )[1] ).getFees() ) ); - s.delete(foo); - s.delete(foo2); - s.delete(baz); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testBagOneToMany() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - List list = new ArrayList(); - baz.setBazez(list); - list.add( new Baz() ); - s.save(baz); - s.flush(); - list.add( new Baz() ); - s.flush(); - list.add( 0, new Baz() ); - s.flush(); - s.delete( list.remove(1) ); - s.flush(); - s.delete(baz); - s.getTransaction().commit(); - s.close(); - } - - @Test - @SkipForDialect( value = H2Dialect.class, comment = "Feature not supported: MVCC=TRUE && FOR UPDATE && JOIN") - public void testQueryLockMode() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Bar bar = new Bar(); - s.save(bar); - s.flush(); - bar.setString("changed"); - Baz baz = new Baz(); - baz.setFoo(bar); - s.save(baz); - Query q = s.createQuery("from Foo foo, Bar bar"); - if ( supportsLockingNullableSideOfJoin( getDialect() ) ) { - q.setLockMode("bar", LockMode.UPGRADE); - } - Object[] result = (Object[]) q.uniqueResult(); - Object b = result[0]; - assertTrue( s.getCurrentLockMode(b)==LockMode.WRITE && s.getCurrentLockMode( result[1] )==LockMode.WRITE ); - tx.commit(); - - tx = s.beginTransaction(); - assertTrue( s.getCurrentLockMode( b ) == LockMode.NONE ); - s.createQuery( "from Foo foo" ).list(); - assertTrue( s.getCurrentLockMode(b)==LockMode.NONE ); - q = s.createQuery("from Foo foo"); - q.setLockMode( "foo", LockMode.READ ); - q.list(); - assertTrue( s.getCurrentLockMode( b ) == LockMode.READ ); - s.evict( baz ); - tx.commit(); - - tx = s.beginTransaction(); - assertTrue( s.getCurrentLockMode(b)==LockMode.NONE ); - s.delete( s.load( Baz.class, baz.getCode() ) ); - assertTrue( s.getCurrentLockMode(b)==LockMode.NONE ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - q = s.createQuery("from Foo foo, Bar bar, Bar bar2"); - if ( supportsLockingNullableSideOfJoin( getDialect() ) ) { - q.setLockMode("bar", LockMode.UPGRADE); - } - q.setLockMode("bar2", LockMode.READ); - result = (Object[]) q.list().get(0); - if ( supportsLockingNullableSideOfJoin( getDialect() ) ) { - assertTrue( s.getCurrentLockMode( result[0] )==LockMode.UPGRADE && s.getCurrentLockMode( result[1] )==LockMode.UPGRADE ); - } - s.delete( result[0] ); - tx.commit(); - s.close(); - } - - @Test - public void testManyToManyBag() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - Serializable id = s.save(baz); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.load(Baz.class, id); - baz.getFooBag().add( new Foo() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.load(Baz.class, id); - assertTrue( !Hibernate.isInitialized( baz.getFooBag() ) ); - assertTrue( baz.getFooBag().size()==1 ); - if ( !(getDialect() instanceof HSQLDialect) ) assertTrue( Hibernate.isInitialized( baz.getFooBag().iterator().next() ) ); - s.delete(baz); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testIdBag() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - s.save(baz); - List l = new ArrayList(); - List l2 = new ArrayList(); - baz.setIdFooBag(l); - baz.setByteBag(l2); - l.add( new Foo() ); - l.add( new Bar() ); - byte[] bytes = "ffo".getBytes(); - l2.add(bytes); - l2.add( "foo".getBytes() ); - s.flush(); - l.add( new Foo() ); - l.add( new Bar() ); - l2.add( "bar".getBytes() ); - s.flush(); - s.delete( l.remove(3) ); - bytes[1]='o'; - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.load(Baz.class, baz.getCode()); - assertTrue( baz.getIdFooBag().size()==3 ); - assertTrue( baz.getByteBag().size()==3 ); - bytes = "foobar".getBytes(); - Iterator iter = baz.getIdFooBag().iterator(); - while ( iter.hasNext() ) s.delete( iter.next() ); - baz.setIdFooBag(null); - baz.getByteBag().add(bytes); - baz.getByteBag().add(bytes); - assertTrue( baz.getByteBag().size()==5 ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.load(Baz.class, baz.getCode()); - assertTrue( baz.getIdFooBag().size()==0 ); - assertTrue( baz.getByteBag().size()==5 ); - baz.getIdFooBag().add( new Foo() ); - iter = baz.getByteBag().iterator(); - iter.next(); - iter.remove(); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.load(Baz.class, baz.getCode()); - assertTrue( baz.getIdFooBag().size()==1 ); - assertTrue( baz.getByteBag().size()==4 ); - s.delete(baz); - s.getTransaction().commit(); - s.close(); - } - - private boolean isOuterJoinFetchingDisabled() { - return new Integer(0).equals( sessionFactory().getSettings().getMaximumFetchDepth() ); - } - - @Test - public void testForceOuterJoin() throws Exception { - if ( isOuterJoinFetchingDisabled() ) { - return; - } - - Session s = openSession(); - s.beginTransaction(); - Glarch g = new Glarch(); - FooComponent fc = new FooComponent(); - fc.setGlarch(g); - FooProxy f = new Foo(); - FooProxy f2 = new Foo(); - f.setComponent(fc); - f.setFoo(f2); - s.save(f2); - Serializable id = s.save(f); - Serializable gid = s.getIdentifier( f.getComponent().getGlarch() ); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictEntityRegion(Foo.class); - - s = openSession(); - s.beginTransaction(); - f = (FooProxy) s.load(Foo.class, id); - assertFalse( Hibernate.isInitialized(f) ); - assertTrue( Hibernate.isInitialized( f.getComponent().getGlarch() ) ); //outer-join="true" - assertFalse( Hibernate.isInitialized( f.getFoo() ) ); //outer-join="auto" - assertEquals( s.getIdentifier( f.getComponent().getGlarch() ), gid ); - s.delete(f); - s.delete( f.getFoo() ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testEmptyCollection() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Serializable id = s.save( new Baz() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Baz baz = (Baz) s.load(Baz.class, id); - Set foos = baz.getFooSet(); - assertTrue( foos.size() == 0 ); - Foo foo = new Foo(); - foos.add( foo ); - s.save(foo); - s.flush(); - s.delete(foo); - s.delete(baz); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testOneToOneGenerator() throws Exception { - Session s = openSession(); - s.beginTransaction(); - X x = new X(); - Y y = new Y(); - x.setY(y); - y.setTheX(x); - x.getXxs().add( new X.XX(x) ); - x.getXxs().add( new X.XX(x) ); - Serializable id = s.save(y); - assertEquals( id, s.save(x) ); - s.flush(); - assertTrue( s.contains(y) && s.contains(x) ); - s.getTransaction().commit(); - s.close(); - assertEquals( new Long(x.getId()), y.getId() ); - - s = openSession(); - s.beginTransaction(); - x = new X(); - y = new Y(); - x.setY(y); - y.setTheX(x); - x.getXxs().add( new X.XX(x) ); - s.save(y); - s.flush(); - assertTrue( s.contains(y) && s.contains(x) ); - s.getTransaction().commit(); - s.close(); - assertEquals( new Long(x.getId()), y.getId() ); - - s = openSession(); - s.beginTransaction(); - x = new X(); - y = new Y(); - x.setY(y); - y.setTheX(x); - x.getXxs().add( new X.XX(x) ); - x.getXxs().add( new X.XX(x) ); - id = s.save(x); - assertEquals( id, y.getId() ); - assertEquals( id, new Long( x.getId() ) ); - s.flush(); - assertTrue( s.contains(y) && s.contains(x) ); - doDelete( s, "from X x" ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testLimit() throws Exception { - Session s = openSession(); - Transaction txn = s.beginTransaction(); - for ( int i=0; i<10; i++ ) s.save( new Foo() ); - Iterator iter = s.createQuery("from Foo foo") - .setMaxResults(4) - .setFirstResult(2) - .iterate(); - int count=0; - while ( iter.hasNext() ) { - iter.next(); - count++; - } - assertEquals(4, count); - iter = s.createQuery("select foo from Foo foo") - .setMaxResults(2) - .setFirstResult(2) - .list() - .iterator(); - count=0; - while ( iter.hasNext() ) { - iter.next(); - count++; - } - assertTrue(count==2); - iter = s.createQuery("select foo from Foo foo") - .setMaxResults(3) - .list() - .iterator(); - count=0; - while ( iter.hasNext() ) { - iter.next(); - count++; - } - assertTrue(count==3); - assertEquals( 10, doDelete( s, "from Foo foo" ) ); - txn.commit(); - s.close(); - } - - @Test - public void testCustom() throws Exception { - GlarchProxy g = new Glarch(); - Multiplicity m = new Multiplicity(); - m.count = 12; - m.glarch = g; - g.setMultiple(m); - - Session s = openSession(); - s.beginTransaction(); - Serializable gid = s.save(g); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - //g = (Glarch) s.createQuery( "from Glarch g where g.multiple.count=12" ).list().get(0); - s.createQuery( "from Glarch g where g.multiple.count=12" ).list().get( 0 ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - g = (Glarch) s.createQuery( "from Glarch g where g.multiple.glarch=g and g.multiple.count=12" ).list().get(0); - assertTrue( g.getMultiple()!=null ); - assertEquals( g.getMultiple().count, 12 ); - assertSame(g.getMultiple().glarch, g); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - g = (GlarchProxy) s.load(Glarch.class, gid); - assertTrue( g.getMultiple() != null ); - assertEquals( g.getMultiple().count, 12 ); - assertSame( g.getMultiple().glarch, g ); - s.delete(g); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testSaveAddDelete() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - Set bars = new HashSet(); - baz.setCascadingBars( bars ); - s.save( baz ); - s.flush(); - baz.getCascadingBars().add( new Bar() ); - s.delete(baz); - s.flush(); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testNamedParams() throws Exception { - Bar bar = new Bar(); - Bar bar2 = new Bar(); - bar.setName("Bar"); - bar2.setName("Bar Two"); - bar.setX( 10 ); - bar2.setX( 1000 );Baz baz = new Baz(); - baz.setCascadingBars( new HashSet() ); - baz.getCascadingBars().add(bar); - bar.setBaz(baz); - - Session s = openSession(); - Transaction txn = s.beginTransaction(); - s.save( baz ); - s.save( bar2 ); - - List list = s.createQuery( - "from Bar bar left join bar.baz baz left join baz.cascadingBars b where bar.name like 'Bar %'" - ).list(); - Object row = list.iterator().next(); - assertTrue( row instanceof Object[] && ( (Object[]) row ).length==3 ); - - Query q = s.createQuery("select bar, b from Bar bar left join bar.baz baz left join baz.cascadingBars b where bar.name like 'Bar%'"); - list = q.list(); - if ( !(getDialect() instanceof SAPDBDialect) ) assertTrue( list.size()==2 ); - - q = s.createQuery("select bar, b from Bar bar left join bar.baz baz left join baz.cascadingBars b where ( bar.name in (:nameList) or bar.name in (:nameList) ) and bar.string = :stringVal"); - HashSet nameList = new HashSet(); - nameList.add( "bar" ); - nameList.add( "Bar" ); - nameList.add( "Bar Two" ); - q.setParameterList( "nameList", nameList ); - q.setParameter( "stringVal", "a string" ); - list = q.list(); - if ( !(getDialect() instanceof SAPDBDialect) ) assertTrue( list.size()==2 ); - - try { - q.setParameterList("nameList", (Collection)null); - fail("Should throw a QueryException when passing a null!"); - } - catch (IllegalArgumentException qe) { - //should happen - } - - q = s.createQuery("select bar, b from Bar bar inner join bar.baz baz inner join baz.cascadingBars b where bar.name like 'Bar%'"); - Object result = q.uniqueResult(); - assertTrue( result != null ); - q = s.createQuery("select bar, b from Bar bar left join bar.baz baz left join baz.cascadingBars b where bar.name like :name and b.name like :name"); - q.setString( "name", "Bar%" ); - list = q.list(); - assertTrue( list.size()==1 ); - - - // This test added for issue HB-297 - there is an named parameter in the Order By clause - q = s.createQuery("select bar from Bar bar order by ((bar.x - :valueX)*(bar.x - :valueX))"); - q.setInteger( "valueX", bar.getX() + 1 ); - list = q.list(); - assertTrue( ((Bar) list.get( 0 )).getX() == bar.getX() ); - q.setInteger( "valueX", bar2.getX() + 1 ); - list = q.list(); - assertTrue( ((Bar)list.get(0)).getX() == bar2.getX()); - - s.delete(baz); - s.delete(bar2); - txn.commit(); - s.close(); - } - - @Test - @RequiresDialectFeature( - value = DialectChecks.SupportsEmptyInListCheck.class, - comment = "Dialect does not support SQL empty in list [x in ()]" - ) - public void testEmptyInListQuery() { - Session s = openSession(); - s.beginTransaction(); - - Query q = s.createQuery( "select bar from Bar as bar where bar.name in (:nameList)" ); - q.setParameterList( "nameList", Collections.EMPTY_LIST ); - assertEquals( 0, q.list().size() ); - - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testParameterCheck() throws HibernateException { - Session s = openSession(); - try { - Query q = s.createQuery("select bar from Bar as bar where bar.x > :myX"); - q.list(); - fail("Should throw QueryException for missing myX"); - } - catch (QueryException iae) { - // should happen - } - finally { - s.close(); - } - - s = openSession(); - try { - Query q = s.createQuery("select bar from Bar as bar where bar.x > ?"); - q.list(); - fail("Should throw QueryException for missing ?"); - } - catch (QueryException iae) { - // should happen - } - finally { - s.close(); - } - - s = openSession(); - try { - Query q = s.createQuery("select bar from Bar as bar where bar.x > ? or bar.short = 1 or bar.string = 'ff ? bb'"); - q.setInteger(0, 1); - q.list(); - } - catch (QueryException iae) { - fail("Should not throw QueryException for missing ?"); - } - finally { - s.close(); - } - - s = openSession(); - try { - Query q = s.createQuery("select bar from Bar as bar where bar.string = ' ? ' or bar.string = '?'"); - q.list(); - } - catch (QueryException iae) { - fail("Should not throw QueryException for ? in quotes"); - } - finally { - s.close(); - } - - s = openSession(); - try { - Query q = s.createQuery("select bar from Bar as bar where bar.string = ? or bar.string = ? or bar.string = ?"); - q.setParameter(0, "bull"); - q.setParameter(2, "shit"); - q.list(); - fail("should throw exception telling me i have not set parameter 1"); - } - catch (QueryException iae) { - // should happen! - } - finally { - s.close(); - } - } - - @Test - public void testDyna() throws Exception { - Session s = openSession(); - s.beginTransaction(); - GlarchProxy g = new Glarch(); - g.setName("G"); - Serializable id = s.save(g); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - g = (GlarchProxy) s.load(Glarch.class, id); - assertTrue( g.getName().equals("G") ); - assertTrue( g.getDynaBean().get("foo").equals("foo") && g.getDynaBean().get("bar").equals( new Integer(66) ) ); - assertTrue( ! (g instanceof Glarch) ); - g.getDynaBean().put("foo", "bar"); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - g = (GlarchProxy) s.load(Glarch.class, id); - assertTrue( g.getDynaBean().get("foo").equals("bar") && g.getDynaBean().get("bar").equals( new Integer(66) ) ); - g.setDynaBean(null); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - g = (GlarchProxy) s.load(Glarch.class, id); - assertTrue( g.getDynaBean()==null ); - s.delete(g); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testFindByCriteria() throws Exception { - if ( getDialect() instanceof DB2Dialect ) { - return; - } - - Session s = openSession(); - Transaction txn = s.beginTransaction(); - Foo f = new Foo(); - s.save( f ); - s.flush(); - - List list = s.createCriteria(Foo.class) - .add( Restrictions.eq( "integer", f.getInteger() ) ) - .add( Restrictions.eqProperty("integer", "integer") ) - .add( Restrictions.like( "string", f.getString().toUpperCase(Locale.ROOT) ).ignoreCase() ) - .add( Restrictions.in( "boolean", f.getBoolean(), f.getBoolean() ) ) - .setFetchMode("foo", FetchMode.JOIN) - .setFetchMode("baz", FetchMode.SELECT) - .setFetchMode("abstracts", FetchMode.JOIN) - .list(); - assertTrue( list.size() == 1 && list.get( 0 ) == f ); - - list = s.createCriteria(Foo.class).add( - Restrictions.disjunction() - .add( Restrictions.eq( "integer", f.getInteger() ) ) - .add( Restrictions.like( "string", f.getString() ) ) - .add( Restrictions.eq( "boolean", f.getBoolean() ) ) - ) - .add( Restrictions.isNotNull("boolean") ) - .list(); - assertTrue( list.size() == 1 && list.get( 0 ) == f ); - - Foo example = new Foo(); - example.setString("a STRing"); - list = s.createCriteria(Foo.class).add( - Example.create(example) - .excludeZeroes() - .ignoreCase() - .excludeProperty("bool") - .excludeProperty("char") - .excludeProperty("yesno") - ) - .list(); - assertTrue( - "Example API without like did not work correctly, size was " + list.size(), - list.size() == 1 && list.get( 0 ) == f - ); - example.setString("rin"); - - list = s.createCriteria(Foo.class).add( - Example.create(example) - .excludeZeroes() - .enableLike(MatchMode.ANYWHERE) - .excludeProperty("bool") - .excludeProperty("char") - .excludeProperty("yesno") - ) - .list(); - assertTrue( "Example API without like did not work correctly, size was " + list.size(), list.size()==1 && list.get(0)==f ); - - list = s.createCriteria(Foo.class) - .add( Restrictions.or( - Restrictions.and( - Restrictions.eq( "integer", f.getInteger() ), - Restrictions.like( "string", f.getString() ) - ), - Restrictions.eq( "boolean", f.getBoolean() ) - ) ) - .list(); - assertTrue( list.size()==1 && list.get(0)==f ); - list = s.createCriteria(Foo.class) - .setMaxResults(5) - .addOrder( Order.asc("date") ) - .list(); - assertTrue( list.size()==1 && list.get(0)==f ); - list = s.createCriteria(Foo.class) - .setFirstResult(1) - .addOrder( Order.asc("date") ) - .addOrder( Order.desc("string") ) - .list(); - assertTrue( list.size() == 0 ); - list = s.createCriteria(Foo.class) - .setFetchMode( "component.importantDates", FetchMode.JOIN ) - .list(); - assertTrue( list.size() == 3 ); - - list = s.createCriteria(Foo.class) - .setFetchMode( "component.importantDates", FetchMode.JOIN ) - .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) - .list(); - assertTrue( list.size()==1 ); - - f.setFoo( new Foo() ); - s.save( f.getFoo() ); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - list = s.createCriteria(Foo.class) - .add( Restrictions.eq( "integer", f.getInteger() ) ) - .add( Restrictions.like( "string", f.getString() ) ) - .add( Restrictions.in( "boolean", f.getBoolean(), f.getBoolean() ) ) - .add( Restrictions.isNotNull("foo") ) - .setFetchMode( "foo", FetchMode.JOIN ) - .setFetchMode( "baz", FetchMode.SELECT ) - .setFetchMode( "component.glarch", FetchMode.SELECT ) - .setFetchMode( "foo.baz", FetchMode.SELECT ) - .setFetchMode( "foo.component.glarch", FetchMode.SELECT ) - .list(); - f = (Foo) list.get(0); - assertTrue( Hibernate.isInitialized( f.getFoo() ) ); - assertTrue( !Hibernate.isInitialized( f.getComponent().getGlarch() ) ); - - s.save( new Bar() ); - list = s.createCriteria(Bar.class) - .list(); - assertTrue( list.size() == 1 ); - assertTrue( s.createCriteria(Foo.class).list().size()==3 ); - s.delete( list.get( 0 ) ); - - s.delete( f.getFoo() ); - s.delete(f); - txn.commit(); - s.close(); - } - - @Test - public void testAfterDelete() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Foo foo = new Foo(); - s.save(foo); - s.flush(); - s.delete(foo); - s.save(foo); - s.delete(foo); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testCollectionWhere() throws Exception { - Foo foo1 = new Foo(); - Foo foo2 = new Foo(); - Baz baz = new Baz(); - Foo[] arr = new Foo[10]; - arr[0] = foo1; - arr[9] = foo2; - - Session s = openSession(); - s.beginTransaction(); - s.save( foo1 ); - s.save(foo2); - baz.setFooArray( arr ); - s.save( baz ); - s.getTransaction().commit(); - s.close(); - - final Session s2 = openSession(); - s2.beginTransaction(); - baz = (Baz) s2.load( Baz.class, baz.getCode() ); - assertTrue( baz.getFooArray().length == 1 ); - assertTrue( s2.createQuery( "from Baz baz join baz.fooArray foo" ).list().size()==1 ); - assertTrue( s2.createQuery( "from Foo foo" ).list().size()==2 ); - assertTrue( s2.createFilter( baz.getFooArray(), "" ).list().size() == 1 ); - //assertTrue( s.delete("from java.lang.Object o")==9 ); - doDelete( s2, "from Foo foo" ); - final String bazid = baz.getCode(); - s2.delete( baz ); - int rows = s2.doReturningWork( - new AbstractReturningWork() { - @Override - public Integer execute(Connection connection) throws SQLException { - Statement st = connection.createStatement(); - return st.executeUpdate( "delete from FOO_ARRAY where id_='" + bazid + "' and i>=8" ); - } - } - ); - assertTrue( rows == 1 ); - s2.getTransaction().commit(); - s2.close(); - } - - @Test - public void testComponentParent() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - BarProxy bar = new Bar(); - bar.setBarComponent( new FooComponent() ); - Baz baz = new Baz(); - baz.setComponents( new FooComponent[] { new FooComponent(), new FooComponent() } ); - s.save(bar); - s.save(baz); - t.commit(); - s.close(); - s = openSession(); - t = s.beginTransaction(); - bar = (BarProxy) s.load(Bar.class, bar.getKey()); - s.load(baz, baz.getCode()); - assertTrue( bar.getBarComponent().getParent()==bar ); - assertTrue( baz.getComponents()[0].getBaz()==baz && baz.getComponents()[1].getBaz()==baz ); - s.delete(baz); - s.delete(bar); - t.commit(); - s.close(); - } - - @Test - public void testCollectionCache() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - baz.setDefaults(); - s.save(baz); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.load( Baz.class, baz.getCode() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.load( Baz.class, baz.getCode() ); - s.delete(baz); - s.getTransaction().commit(); - s.close(); - } - - public void ntestAssociationId() throws Exception { - // IMPL NOTE : previously not being run due to the name - Session s = openSession(); - Transaction t = s.beginTransaction(); - Bar bar = new Bar(); - String id = (String) s.save(bar); - MoreStuff more = new MoreStuff(); - more.setName("More Stuff"); - more.setIntId(12); - more.setStringId("id"); - Stuff stuf = new Stuff(); - stuf.setMoreStuff(more); - more.setStuffs( new ArrayList() ); - more.getStuffs().add(stuf); - stuf.setFoo(bar); - stuf.setId(1234); - stuf.setProperty( TimeZone.getDefault() ); - s.save(more); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - List results = s.createQuery( - "from Stuff as s where s.foo.id = ? and s.id.id = ? and s.moreStuff.id.intId = ? and s.moreStuff.id.stringId = ?" - ) - .setParameter( 0, bar, s.getTypeHelper().entity(Foo.class) ) - .setParameter( 1, new Long(1234), StandardBasicTypes.LONG ) - .setParameter( 2, new Integer(12), StandardBasicTypes.INTEGER ) - .setParameter( 3, "id", StandardBasicTypes.STRING ) - .list(); - assertEquals( 1, results.size() ); - results = s.createQuery( "from Stuff as s where s.foo.id = ? and s.id.id = ? and s.moreStuff.name = ?" ) - .setParameter( 0, bar, s.getTypeHelper().entity(Foo.class) ) - .setParameter( 1, new Long(1234), StandardBasicTypes.LONG ) - .setParameter( 2, "More Stuff", StandardBasicTypes.STRING ) - .list(); - assertEquals( 1, results.size() ); - s.createQuery( "from Stuff as s where s.foo.string is not null" ).list(); - assertTrue( - s.createQuery( "from Stuff as s where s.foo > '0' order by s.foo" ).list().size()==1 - ); - //s.createCriteria(Stuff.class).createCriteria("id.foo").add( Expression.isNull("foo") ).list(); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - FooProxy foo = (FooProxy) s.load(Foo.class, id); - s.load(more, more); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Stuff stuff = new Stuff(); - stuff.setFoo(foo); - stuff.setId(1234); - stuff.setMoreStuff(more); - s.load(stuff, stuff); - assertTrue( stuff.getProperty().equals( TimeZone.getDefault() ) ); - assertTrue( stuff.getMoreStuff().getName().equals("More Stuff") ); - doDelete( s, "from MoreStuff" ); - doDelete( s, "from Foo foo" ); - t.commit(); - s.close(); - } - - @Test - public void testCascadeSave() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Baz baz = new Baz(); - List list = new ArrayList(); - list.add( new Fee() ); - list.add( new Fee() ); - baz.setFees( list ); - s.save(baz); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - baz = (Baz) s.load( Baz.class, baz.getCode() ); - assertTrue( baz.getFees().size() == 2 ); - s.delete(baz); - assertTrue( !s.createQuery( "from Fee fee" ).iterate().hasNext() ); - t.commit(); - s.close(); - } - - @Test - public void testCollectionsInSelect() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Foo[] foos = new Foo[] { null, new Foo() }; - s.save( foos[1] ); - Baz baz = new Baz(); - baz.setDefaults(); - baz.setFooArray(foos); - s.save(baz); - Baz baz2 = new Baz(); - baz2.setDefaults(); - s.save(baz2); - - Bar bar = new Bar(); - bar.setBaz(baz); - s.save(bar); - - List list = s.createQuery( "select new Result(foo.string, foo.long, foo.integer) from Foo foo" ).list(); - assertTrue( list.size()==2 && ( list.get(0) instanceof Result ) && ( list.get(1) instanceof Result ) ); - /*list = s.find("select new Result( baz.name, foo.long, count(elements(baz.fooArray)) ) from Baz baz join baz.fooArray foo group by baz.name, foo.long"); - assertTrue( list.size()==1 && ( list.get(0) instanceof Result ) ); - Result r = ((Result) list.get(0) ); - assertEquals( r.getName(), baz.getName() ); - assertEquals( r.getCount(), 1 ); - assertEquals( r.getAmount(), foos[1].getLong().longValue() );*/ - list = s.createQuery( - "select new Result( baz.name, max(foo.long), count(foo) ) from Baz baz join baz.fooArray foo group by baz.name" - ).list(); - assertTrue( list.size()==1 && ( list.get(0) instanceof Result ) ); - Result r = ((Result) list.get(0) ); - assertEquals( r.getName(), baz.getName() ); - assertEquals( r.getCount(), 1 ); - assertTrue( r.getAmount() > 696969696969696000l ); - - - //s.find("select max( elements(bar.baz.fooArray) ) from Bar as bar"); - //The following test is disabled for databases with no subselects...also for Interbase (not sure why). - if ( !(getDialect() instanceof MySQLDialect) && !(getDialect() instanceof HSQLDialect) /*&& !(dialect instanceof MckoiDialect)*/ && !(getDialect() instanceof SAPDBDialect) && !(getDialect() instanceof PointbaseDialect) ) { - s.createQuery( "select count(*) from Baz as baz where 1 in indices(baz.fooArray)" ).list(); - s.createQuery( "select count(*) from Bar as bar where 'abc' in elements(bar.baz.fooArray)" ).list(); - s.createQuery( "select count(*) from Bar as bar where 1 in indices(bar.baz.fooArray)" ).list(); - if ( !(getDialect() instanceof DB2Dialect) && - !( getDialect() instanceof Oracle8iDialect ) && - !( SybaseDialect.class.isAssignableFrom( getDialect().getClass() ) ) && - !( SQLServerDialect.class.isAssignableFrom( getDialect().getClass() ) ) && - !( getDialect() instanceof PostgreSQLDialect ) && !(getDialect() instanceof PostgreSQL81Dialect ) && - !(getDialect() instanceof CockroachDialect ) && - - !( getDialect() instanceof AbstractHANADialect) ) { - // SybaseAnywhereDialect supports implicit conversions from strings to ints - s.createQuery( - "select count(*) from Bar as bar, bar.component.glarch.proxyArray as g where g.id in indices(bar.baz.fooArray)" - ).list(); - s.createQuery( - "select max( elements(bar.baz.fooArray) ) from Bar as bar, bar.component.glarch.proxyArray as g where g.id in indices(bar.baz.fooArray)" - ).list(); - } - s.createQuery( - "select count(*) from Bar as bar where '1' in (from bar.component.glarch.proxyArray g where g.name='foo')" - ).list(); - s.createQuery( - "select count(*) from Bar as bar where '1' in (from bar.component.glarch.proxyArray g where g.name='foo')" - ).list(); - s.createQuery( - "select count(*) from Bar as bar left outer join bar.component.glarch.proxyArray as pg where '1' in (from bar.component.glarch.proxyArray)" - ).list(); - } - - list = s.createQuery( - "from Baz baz left join baz.fooToGlarch join fetch baz.fooArray foo left join fetch foo.foo" - ).list(); - assertTrue( list.size()==1 && ( (Object[]) list.get(0) ).length==2 ); - - s.createQuery( - "select baz.name from Bar bar inner join bar.baz baz inner join baz.fooSet foo where baz.name = bar.string" - ).list(); - s.createQuery( - "SELECT baz.name FROM Bar AS bar INNER JOIN bar.baz AS baz INNER JOIN baz.fooSet AS foo WHERE baz.name = bar.string" - ).list(); - - if ( !( getDialect() instanceof HSQLDialect ) ) s.createQuery( - "select baz.name from Bar bar join bar.baz baz left outer join baz.fooSet foo where baz.name = bar.string" - ).list(); - - s.createQuery( "select baz.name from Bar bar join bar.baz baz join baz.fooSet foo where baz.name = bar.string" ) - .list(); - s.createQuery( - "SELECT baz.name FROM Bar AS bar JOIN bar.baz AS baz JOIN baz.fooSet AS foo WHERE baz.name = bar.string" - ).list(); - - if ( !( getDialect() instanceof HSQLDialect ) ) { - s.createQuery( - "select baz.name from Bar bar left join bar.baz baz left join baz.fooSet foo where baz.name = bar.string" - ).list(); - s.createQuery( "select foo.string from Bar bar left join bar.baz.fooSet foo where bar.string = foo.string" ) - .list(); - } - - s.createQuery( - "select baz.name from Bar bar left join bar.baz baz left join baz.fooArray foo where baz.name = bar.string" - ).list(); - s.createQuery( "select foo.string from Bar bar left join bar.baz.fooArray foo where bar.string = foo.string" ) - .list(); - - s.createQuery( - "select bar.string, foo.string from Bar bar inner join bar.baz as baz inner join baz.fooSet as foo where baz.name = 'name'" - ).list(); - s.createQuery( "select foo from Bar bar inner join bar.baz as baz inner join baz.fooSet as foo" ).list(); - s.createQuery( "select foo from Bar bar inner join bar.baz.fooSet as foo" ).list(); - - s.createQuery( - "select bar.string, foo.string from Bar bar join bar.baz as baz join baz.fooSet as foo where baz.name = 'name'" - ).list(); - s.createQuery( "select foo from Bar bar join bar.baz as baz join baz.fooSet as foo" ).list(); - s.createQuery( "select foo from Bar bar join bar.baz.fooSet as foo" ).list(); - - assertTrue( s.createQuery( "from Bar bar join bar.baz.fooArray foo" ).list().size()==1 ); - - assertTrue( s.createQuery( "from Bar bar join bar.baz.fooSet foo" ).list().size()==0 ); - assertTrue( s.createQuery( "from Bar bar join bar.baz.fooArray foo" ).list().size()==1 ); - - s.delete(bar); - - if ( getDialect() instanceof DB2Dialect || getDialect() instanceof PostgreSQLDialect || getDialect() instanceof PostgreSQL81Dialect || getDialect() instanceof CockroachDialect - ) { - s.createQuery( "select one from One one join one.manies many group by one order by count(many)" ).iterate(); - s.createQuery( "select one from One one join one.manies many group by one having count(many) < 5" ) - .iterate(); - } - - s.createQuery( "from One one join one.manies many where one.id = 1 and many.id = 1" ).list(); - s.createQuery( "select one.id, elements(one.manies) from One one" ).iterate(); - s.createQuery( "select max( elements(one.manies) ) from One one" ).iterate(); - s.createQuery( "select one, elements(one.manies) from One one" ).list(); - Iterator iter = s.createQuery( "select elements(baz.fooArray) from Baz baz where baz.id=?" ) - .setParameter( 0, baz.getCode(), StandardBasicTypes.STRING ) - .iterate(); - assertTrue( iter.next()==foos[1] && !iter.hasNext() ); - list = s.createQuery( "select elements(baz.fooArray) from Baz baz where baz.id=?" ) - .setParameter( 0, baz.getCode(), StandardBasicTypes.STRING ) - .list(); - assertEquals( 1, list.size() ); - iter = s.createQuery( "select indices(baz.fooArray) from Baz baz where baz.id=?" ) - .setParameter( 0, baz.getCode(), StandardBasicTypes.STRING ) - .iterate(); - assertTrue( iter.next().equals( new Integer(1) ) && !iter.hasNext() ); - - iter = s.createQuery( "select size(baz.stringSet) from Baz baz where baz.id=?" ) - .setParameter( 0, baz.getCode(), StandardBasicTypes.STRING ) - .iterate(); - assertEquals( new Integer(3), iter.next() ); - - s.createQuery( "from Foo foo where foo.component.glarch.id is not null" ).list(); - - iter = s.createQuery( - "select baz, size(baz.stringSet), count( distinct elements(baz.stringSet) ), max( elements(baz.stringSet) ) from Baz baz group by baz" - ).iterate(); - while ( iter.hasNext() ) { - Object[] arr = (Object[]) iter.next(); - log.info(arr[0] + " " + arr[1] + " " + arr[2] + " " + arr[3]); - } - - s.delete(baz); - s.delete(baz2); - s.delete( foos[1] ); - t.commit(); - s.close(); - } - - @Test - public void testNewFlushing() throws Exception { - Session s = openSession(); - Transaction txn = s.beginTransaction(); - Baz baz = new Baz(); - baz.setDefaults(); - s.save(baz); - s.flush(); - baz.getStringArray()[0] = "a new value"; - Iterator iter = s.createQuery( "from Baz baz" ).iterate();//no flush - assertTrue( iter.next()==baz ); - iter = s.createQuery( "select elements(baz.stringArray) from Baz baz" ).iterate(); - boolean found = false; - while ( iter.hasNext() ) { - if ( iter.next().equals("a new value") ) found = true; - } - assertTrue( found ); - baz.setStringArray( null ); - s.createQuery( "from Baz baz" ).iterate(); //no flush - iter = s.createQuery( "select elements(baz.stringArray) from Baz baz" ).iterate(); - assertTrue( !iter.hasNext() ); - baz.getStringList().add( "1E1" ); - iter = s.createQuery( "from Foo foo" ).iterate();//no flush - assertTrue( !iter.hasNext() ); - iter = s.createQuery( "select elements(baz.stringList) from Baz baz" ).iterate(); - found = false; - while ( iter.hasNext() ) { - if ( iter.next().equals("1E1") ) found = true; - } - assertTrue( found ); - baz.getStringList().remove( "1E1" ); - iter = s.createQuery( "select elements(baz.stringArray) from Baz baz" ).iterate(); //no flush - iter = s.createQuery( "select elements(baz.stringList) from Baz baz" ).iterate(); - found = false; - while ( iter.hasNext() ) { - if ( iter.next().equals("1E1") ) found = true; - } - assertTrue(!found); - - List newList = new ArrayList(); - newList.add("value"); - baz.setStringList( newList ); - iter = s.createQuery( "from Foo foo" ).iterate();//no flush - baz.setStringList( null ); - iter = s.createQuery( "select elements(baz.stringList) from Baz baz" ).iterate(); - assertTrue( !iter.hasNext() ); - - baz.setStringList(newList); - iter = s.createQuery( "from Foo foo" ).iterate();//no flush - iter = s.createQuery( "select elements(baz.stringList) from Baz baz" ).iterate(); - assertTrue( iter.hasNext() ); - - s.delete( baz ); - txn.commit(); - s.close(); - } - - @Test - public void testPersistCollections() throws Exception { - Session s = openSession(); - Transaction txn = s.beginTransaction(); - assertEquals( 0l, s.createQuery( "select count(*) from Bar" ).iterate().next() ); - assertEquals( 0l, s.createQuery( "select count(*) from Bar b" ).iterate().next() ); - assertFalse( s.createQuery( "from Glarch g" ).iterate().hasNext() ); - - Baz baz = new Baz(); - s.save(baz); - baz.setDefaults(); - baz.setStringArray( new String[] { "stuff" } ); - Set bars = new HashSet(); - bars.add( new Bar() ); - baz.setCascadingBars(bars); - HashMap sgm = new HashMap(); - sgm.put( "a", new Glarch() ); - sgm.put( "b", new Glarch() ); - baz.setStringGlarchMap(sgm); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - assertEquals( 1L, ((Long) s.createQuery( "select count(*) from Bar" ).iterate().next()).longValue() ); - baz = (Baz) ( (Object[]) s.createQuery( "select baz, baz from Baz baz" ).list().get(0) )[1]; - assertTrue( baz.getCascadingBars().size()==1 ); - //System.out.println( s.print(baz) ); - Foo foo = new Foo(); - s.save(foo); - Foo foo2 = new Foo() ; - s.save(foo2); - baz.setFooArray( new Foo[] { foo, foo, null, foo2 } ); - baz.getFooSet().add(foo); - baz.getCustoms().add( new String[] { "new", "custom" } ); - baz.setStringArray(null); - baz.getStringList().set(0, "new value"); - baz.setStringSet( new TreeSet() ); - Time time = new java.sql.Time(12345); - baz.getTimeArray()[2] = time; - //System.out.println(time); - - assertTrue( baz.getStringGlarchMap().size()==1 ); - - //The following test is disabled databases with no subselects - if ( !(getDialect() instanceof MySQLDialect) && !(getDialect() instanceof HSQLDialect) && !(getDialect() instanceof PointbaseDialect) ) { - List list = s.createQuery( - "select foo from Foo foo, Baz baz where foo in elements(baz.fooArray) and 3 = some elements(baz.intArray) and 4 > all indices(baz.intArray)" - ).list(); - assertTrue( "collection.elements find", list.size()==2 ); - } - // SAPDB doesn't like distinct with binary type - // Oracle12cDialect stores binary types as blobs and do no support distinct on blobs - if ( !(getDialect() instanceof SAPDBDialect) && !(getDialect() instanceof Oracle12cDialect) ) { - List list = s.createQuery( "select distinct foo from Baz baz join baz.fooArray foo" ).list(); - assertTrue( "collection.elements find", list.size()==2 ); - } - - List list = s.createQuery( "select foo from Baz baz join baz.fooSet foo" ).list(); - assertTrue( "association.elements find", list.size()==1 ); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - assertEquals( 1, ((Long) s.createQuery( "select count(*) from Bar" ).iterate().next()).longValue() ); - baz = (Baz) s.createQuery( "select baz from Baz baz order by baz" ).list().get(0); - assertTrue( "collection of custom types - added element", baz.getCustoms().size()==4 && baz.getCustoms().get(0)!=null ); - assertTrue ( "component of component in collection", baz.getComponents()[1].getSubcomponent()!=null ); - assertTrue( baz.getComponents()[1].getBaz()==baz ); - assertTrue( "set of objects", ( (FooProxy) baz.getFooSet().iterator().next() ).getKey().equals( foo.getKey() )); - assertTrue( "collection removed", baz.getStringArray().length==0 ); - assertTrue( "changed element", baz.getStringList().get(0).equals("new value")); - assertTrue( "replaced set", baz.getStringSet().size()==0 ); - assertTrue( "array element change", baz.getTimeArray()[2]!=null ); - assertTrue( baz.getCascadingBars().size()==1 ); - //System.out.println( s.print(baz) ); - baz.getStringSet().add("two"); - baz.getStringSet().add("one"); - baz.getBag().add("three"); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - baz = (Baz) s.createQuery( "select baz from Baz baz order by baz" ).list().get(0); - assertTrue( baz.getStringSet().size()==2 ); - assertTrue( baz.getStringSet().first().equals("one") ); - assertTrue( baz.getStringSet().last().equals("two") ); - assertTrue( baz.getBag().size()==5 ); - baz.getStringSet().remove("two"); - baz.getBag().remove("duplicate"); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - assertEquals( 1, ((Long) s.createQuery( "select count(*) from Bar" ).iterate().next()).longValue() ); - baz = (Baz) s.load(Baz.class, baz.getCode()); - assertTrue( baz.getCascadingBars().size()==1 ); - Bar bar = new Bar(); - Bar bar2 = new Bar(); - s.save(bar); s.save(bar2); - baz.setTopFoos( new HashSet() ); - baz.getTopFoos().add(bar); - baz.getTopFoos().add(bar2); - assertTrue( baz.getCascadingBars().size()==1 ); - baz.setTopGlarchez( new TreeMap() ); - GlarchProxy g = new Glarch(); - s.save(g); - baz.getTopGlarchez().put( 'G', g ); - HashMap map = new HashMap(); - map.put(bar, g); - map.put(bar2, g); - baz.setFooToGlarch(map); - map = new HashMap(); - map.put( new FooComponent("name", 123, null, null), bar ); - map.put( new FooComponent("nameName", 12, null, null), bar ); - baz.setFooComponentToFoo(map); - map = new HashMap(); - map.put(bar, g); - baz.setGlarchToFoo(map); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - baz = (Baz) s.createQuery( "select baz from Baz baz order by baz" ).list().get(0); - assertTrue( baz.getCascadingBars().size()==1 ); - - Session s2 = openSession(); - Transaction txn2 = s2.beginTransaction(); - assertEquals( 3, ((Long) s2.createQuery( "select count(*) from Bar" ).iterate().next()).longValue() ); - Baz baz2 = (Baz) s2.createQuery( "select baz from Baz baz order by baz" ).list().get(0); - Object o = baz2.getFooComponentToFoo().get( new FooComponent("name", 123, null, null) ); - assertTrue( - o==baz2.getFooComponentToFoo().get( new FooComponent("nameName", 12, null, null) ) && o!=null - ); - txn2.commit(); - s2.close(); - - assertTrue( Hibernate.isInitialized( baz.getFooToGlarch() ) ); - assertTrue( baz.getTopFoos().size()==2 ); - assertTrue( baz.getTopGlarchez().size()==1 ); - assertTrue( baz.getTopFoos().iterator().next()!=null ); - assertTrue( baz.getStringSet().size()==1 ); - assertTrue( baz.getBag().size()==4 ); - assertTrue( baz.getFooToGlarch().size()==2 ); - assertTrue( baz.getFooComponentToFoo().size()==2 ); - assertTrue( baz.getGlarchToFoo().size()==1 ); - Iterator iter = baz.getFooToGlarch().keySet().iterator(); - for (int i=0; i<2; i++ ) assertTrue( iter.next() instanceof BarProxy ); - FooComponent fooComp = (FooComponent) baz.getFooComponentToFoo().keySet().iterator().next(); - assertTrue( - ( (fooComp.getCount()==123 && fooComp.getName().equals("name")) - || (fooComp.getCount()==12 && fooComp.getName().equals("nameName")) ) - && ( baz.getFooComponentToFoo().get(fooComp) instanceof BarProxy ) - ); - Glarch g2 = new Glarch(); - s.save(g2); - g = (GlarchProxy) baz.getTopGlarchez().get( 'G' ); - baz.getTopGlarchez().put( 'H', g ); - baz.getTopGlarchez().put( 'G', g2 ); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - baz = (Baz) s.load(Baz.class, baz.getCode()); - assertTrue( baz.getTopGlarchez().size()==2 ); - assertTrue( baz.getCascadingBars().size()==1 ); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - assertEquals( 3, ((Long) s.createQuery( "select count(*) from Bar" ).iterate().next()).longValue() ); - baz = (Baz) s.createQuery( "select baz from Baz baz order by baz" ).list().get(0); - assertTrue( baz.getTopGlarchez().size()==2 ); - assertTrue( baz.getCascadingBars().size()==1 ); - txn.commit(); - - final Session s3 = (Session) SerializationHelper.deserialize( SerializationHelper.serialize(s) ); - s.close(); - - txn2 = s3.beginTransaction(); - baz = (Baz) s3.load(Baz.class, baz.getCode()); - assertEquals( 3, ((Long) s3.createQuery( "select count(*) from Bar" ).iterate().next()).longValue() ); - s3.delete(baz); - s3.delete( baz.getTopGlarchez().get( 'G' ) ); - s3.delete( baz.getTopGlarchez().get( 'H' ) ); - int rows = s3.doReturningWork( - new AbstractReturningWork() { - @Override - public Integer execute(Connection connection) throws SQLException { - final String sql = "update " + getDialect().openQuote() + "glarchez" + getDialect().closeQuote() + " set baz_map_id=null where baz_map_index='a'"; - Statement st = connection.createStatement(); - return st.executeUpdate( sql ); - } - } - ); - assertTrue(rows==1); - assertEquals( 2, doDelete( s3, "from Bar bar" ) ); - FooProxy[] arr = baz.getFooArray(); - assertTrue( "new array of objects", arr.length==4 && arr[1].getKey().equals( foo.getKey() ) ); - for ( int i=1; i 0 ); - assertTrue( iter.scroll(-1) ); - f1 = iter.get(0); - iter.next(); - assertTrue( f1!=null && iter.get(0)==f2 ); - iter.getInteger(1); - - assertTrue( !iter.scroll(100) ); - assertTrue( iter.first() ); - assertTrue( iter.scroll(3) ); - f4 = iter.get(0); - assertTrue( f4!=null ); - assertTrue( !iter.next() ); - assertTrue( iter.first() ); - assertTrue( iter.get(0)==f1 ); - assertTrue( iter.last() ); - assertTrue( iter.get(0)==f4 ); - assertTrue( iter.previous() ); - int i = 0; - for ( Object entity : s.createQuery( "from Foo" ).list() ) { - i++; - s.delete( entity ); - } - assertEquals( 4, i ); - s.flush(); - assertTrue( s.createQuery( "from java.lang.Object" ).list().size()==0 ); - txn.commit(); - s.close(); - } - - @Test - public void testMultiColumnQueries() throws Exception { - Session s = openSession(); - Transaction txn = s.beginTransaction(); - Foo foo = new Foo(); - s.save( foo ); - Foo foo1 = new Foo(); - s.save(foo1); - foo.setFoo( foo1 ); - List l = s.createQuery( "select parent, child from Foo parent, Foo child where parent.foo = child" ).list(); - assertTrue( "multi-column find", l.size()==1 ); - - Iterator rs = null; - Object[] row = null; - //Derby does not support multiple DISTINCT aggregates - if ( !(getDialect() instanceof DerbyDialect) ) { - rs = s.createQuery( - "select count(distinct child.id), count(distinct parent.id) from Foo parent, Foo child where parent.foo = child" - ).iterate(); - - row = (Object[]) rs.next(); - assertTrue( "multi-column count", ((Long) row[0]).intValue() == 1 ); - assertTrue( "multi-column count", ((Long) row[1]).intValue() == 1 ); - assertTrue( !rs.hasNext() ); - } - rs = s.createQuery( - "select child.id, parent.id, child.long from Foo parent, Foo child where parent.foo = child" - ) - .iterate(); - row = (Object[]) rs.next(); - assertTrue( "multi-column id", row[0].equals( foo.getFoo().getKey() ) ); - assertTrue( "multi-column id", row[1].equals( foo.getKey() ) ); - assertTrue( "multi-column property", row[2].equals( foo.getFoo().getLong() ) ); - assertTrue( !rs.hasNext() ); - - rs = s.createQuery( - "select child.id, parent.id, child.long, child, parent.foo from Foo parent, Foo child where parent.foo = child" - ).iterate(); - row = (Object[]) rs.next(); - assertTrue( - foo.getFoo().getKey().equals( row[0] ) && - foo.getKey().equals( row[1] ) && - foo.getFoo().getLong().equals( row[2] ) && - row[3] == foo.getFoo() && - row[3]==row[4] - ); - assertTrue( !rs.hasNext() ); - - row = (Object[]) l.get(0); - assertTrue( "multi-column find", row[0]==foo && row[1]==foo.getFoo() ); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - Iterator iter = s.createQuery( - "select parent, child from Foo parent, Foo child where parent.foo = child and parent.string='a string'" - ).iterate(); - int deletions=0; - while ( iter.hasNext() ) { - Object[] pnc = (Object[]) iter.next(); - s.delete( pnc[0] ); - s.delete( pnc[1] ); - deletions++; - } - assertTrue("multi-column iterate", deletions==1); - txn.commit(); - s.close(); - } - - @Test - public void testDeleteTransient() throws Exception { - Fee fee = new Fee(); - Fee fee2 = new Fee(); - fee2.setAnotherFee(fee); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - s.save(fee); - s.save(fee2); - s.flush(); - fee.setCount(123); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - s.delete(fee); - s.delete(fee2); - //foo.setAnotherFee(null); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - assertTrue( s.createQuery( "from Fee fee" ).list().size()==0 ); - tx.commit(); - s.close(); - } - - @Test - public void testDeleteUpdatedTransient() throws Exception { - Fee fee = new Fee(); - Fee fee2 = new Fee(); - fee2.setAnotherFee(fee); - Session s = openSession(); - Transaction tx = s.beginTransaction(); - s.save(fee); - s.save(fee2); - s.flush(); - fee.setCount(123); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - s.update(fee); - //fee2.setAnotherFee(null); - s.update(fee2); - s.delete(fee); - s.delete(fee2); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - assertTrue( s.createQuery( "from Fee fee" ).list().size()==0 ); - tx.commit(); - s.close(); - } - - @Test - public void testUpdateOrder() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Fee fee1 = new Fee(); - s.save(fee1); - Fee fee2 = new Fee(); - fee1.setFee(fee2); - fee2.setFee(fee1); - fee2.setFees( new HashSet() ); - Fee fee3 = new Fee(); - fee3.setFee(fee1); - fee3.setAnotherFee(fee2); - fee2.setAnotherFee(fee3); - s.save(fee3); - s.save(fee2); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - fee1.setCount(10); - fee2.setCount(20); - fee3.setCount(30); - s.update(fee1); - s.update(fee2); - s.update(fee3); - s.flush(); - s.delete(fee1); - s.delete(fee2); - s.delete(fee3); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - assertTrue( s.createQuery( "from Fee fee" ).list().size()==0 ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testUpdateFromTransient() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Fee fee1 = new Fee(); - s.save(fee1); - Fee fee2 = new Fee(); - fee1.setFee(fee2); - fee2.setFee(fee1); - fee2.setFees( new HashSet() ); - Fee fee3 = new Fee(); - fee3.setFee(fee1); - fee3.setAnotherFee(fee2); - fee2.setAnotherFee(fee3); - s.save(fee3); - s.save(fee2); - s.getTransaction().commit(); - s.close(); - - fee1.setFi("changed"); - - s = openSession(); - s.beginTransaction(); - s.saveOrUpdate(fee1); - s.getTransaction().commit(); - s.close(); - - Qux q = new Qux("quxxy"); - q.setTheKey(0); - fee1.setQux(q); - - s = openSession(); - s.beginTransaction(); - s.saveOrUpdate(fee1); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - fee1 = (Fee) s.load( Fee.class, fee1.getKey() ); - assertTrue( "updated from transient", fee1.getFi().equals("changed") ); - assertTrue( "unsaved value", fee1.getQux()!=null ); - s.delete( fee1.getQux() ); - fee1.setQux(null); - s.getTransaction().commit(); - s.close(); - - fee2.setFi("CHANGED"); - fee2.getFees().add("an element"); - fee1.setFi("changed again"); - - s = openSession(); - s.beginTransaction(); - s.saveOrUpdate(fee2); - s.update( fee1 ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Fee fee = new Fee(); - s.load( fee, fee2.getKey() ); - fee1 = (Fee) s.load( Fee.class, fee1.getKey() ); - assertTrue( "updated from transient", fee1.getFi().equals("changed again") ); - assertTrue( "updated from transient", fee.getFi().equals("CHANGED") ); - assertTrue( "updated collection", fee.getFees().contains("an element") ); - s.getTransaction().commit(); - s.close(); - - fee.getFees().clear(); - fee.getFees().add("new element"); - fee1.setFee(null); - - s = openSession(); - s.beginTransaction(); - s.saveOrUpdate(fee); - s.saveOrUpdate(fee1); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.load( fee, fee.getKey() ); - assertTrue( "update", fee.getAnotherFee()!=null ); - assertTrue( "update", fee.getFee()!=null ); - assertTrue( "update", fee.getAnotherFee().getFee()==fee.getFee() ); - assertTrue( "updated collection", fee.getFees().contains("new element") ); - assertTrue( "updated collection", !fee.getFees().contains("an element") ); - s.getTransaction().commit(); - s.close(); - - fee.setQux( new Qux("quxy") ); - - s = openSession(); - s.beginTransaction(); - s.saveOrUpdate(fee); - s.getTransaction().commit(); - s.close(); - - fee.getQux().setStuff("xxx"); - - s = openSession(); - s.beginTransaction(); - s.saveOrUpdate(fee); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.load( fee, fee.getKey() ); - assertTrue( "cascade update", fee.getQux()!=null ); - assertTrue( "cascade update", fee.getQux().getStuff().equals("xxx") ); - assertTrue( "update", fee.getAnotherFee()!=null ); - assertTrue( "update", fee.getFee()!=null ); - assertTrue( "update", fee.getAnotherFee().getFee()==fee.getFee() ); - fee.getAnotherFee().setAnotherFee(null); - s.delete(fee); - doDelete( s, "from Fee fee" ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - assertTrue( s.createQuery( "from Fee fee" ).list().size()==0 ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testArraysOfTimes() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz() ; - s.save(baz); - baz.setDefaults(); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz.getTimeArray()[2] = new Date(123); - baz.getTimeArray()[3] = new java.sql.Time(1234); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.load( Baz.class, baz.getCode() ); - s.delete( baz ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testComponents() throws Exception { - Session s = openSession(); - Transaction txn = s.beginTransaction(); - Foo foo = new Foo(); -// foo.setComponent( new FooComponent("foo", 69, null, new FooComponent("bar", 96, null, null) ) ); - s.save(foo); - foo.getComponent().setName( "IFA" ); - txn.commit(); - s.close(); - - foo.setComponent( null ); - - s = openSession(); - txn = s.beginTransaction(); - s.load( foo, foo.getKey() ); - assertTrue( - "save components", - foo.getComponent().getName().equals("IFA") && - foo.getComponent().getSubcomponent().getName().equals("bar") - ); - assertTrue( "cascade save via component", foo.getComponent().getGlarch() != null ); - foo.getComponent().getSubcomponent().setName("baz"); - txn.commit(); - s.close(); - - foo.setComponent(null); - - s = openSession(); - txn = s.beginTransaction(); - s.load( foo, foo.getKey() ); - assertTrue( - "update components", - foo.getComponent().getName().equals("IFA") && - foo.getComponent().getSubcomponent().getName().equals("baz") - ); - s.delete(foo); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - foo = new Foo(); - s.save( foo ); - foo.setCustom( new String[] { "one", "two" } ); - assertTrue( s.createQuery( "from Foo foo where foo.custom.s1 = 'one'" ).list().get(0)==foo ); - s.delete( foo ); - txn.commit(); - s.close(); - } - - @Test - public void testNoForeignKeyViolations() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Glarch g1 = new Glarch(); - Glarch g2 = new Glarch(); - g1.setNext(g2); - g2.setNext(g1); - s.save(g1); - s.save(g2); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - List l = s.createQuery( "from Glarch g where g.next is not null" ).list(); - s.delete( l.get(0) ); - s.delete( l.get(1) ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testLazyCollections() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Qux q = new Qux(); - s.save(q); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - q = (Qux) s.load( Qux.class, q.getKey() ); - s.getTransaction().commit(); - s.close(); - - System.out.println("Two exceptions are supposed to occur:"); - boolean ok = false; - try { - q.getMoreFums().isEmpty(); - } - catch (LazyInitializationException e) { - ok = true; - } - assertTrue( "lazy collection with one-to-many", ok ); - - ok = false; - try { - q.getFums().isEmpty(); - } - catch (LazyInitializationException e) { - ok = true; - } - assertTrue( "lazy collection with many-to-many", ok ); - - s = openSession(); - s.beginTransaction(); - q = (Qux) s.load( Qux.class, q.getKey() ); - s.delete(q); - s.getTransaction().commit(); - s.close(); - } - - @Test - @TestForIssue(jiraKey = "HHH-7603") - public void testLazyCollectionsTouchedDuringPreCommit() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Qux q = new Qux(); - s.save( q ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - q = ( Qux ) s.load( Qux.class, q.getKey() ); - s.getTransaction().commit(); - - //clear the session - s.clear(); - - //now reload the proxy and delete it - s.beginTransaction(); - - final Qux qToDelete = ( Qux ) s.load( Qux.class, q.getKey() ); - - //register a pre commit process that will touch the collection and delete the entity - ( ( EventSource ) s ).getActionQueue().registerProcess( new BeforeTransactionCompletionProcess() { - @Override - public void doBeforeTransactionCompletion(SessionImplementor session) { - qToDelete.getFums().size(); - } - } ); - - s.delete( qToDelete ); - boolean ok = false; - try { - s.getTransaction().commit(); - } - catch (LazyInitializationException e) { - ok = true; - s.getTransaction().rollback(); - } - catch (TransactionException te) { - if(te.getCause() instanceof LazyInitializationException) { - ok = true; - } - s.getTransaction().rollback(); - } - finally { - s.close(); - } - assertTrue( "lazy collection should have blown in the before trans completion", ok ); - - s = openSession(); - s.beginTransaction(); - q = ( Qux ) s.load( Qux.class, q.getKey() ); - s.delete( q ); - s.getTransaction().commit(); - s.close(); - } - - @SkipForDialect(value = AbstractHANADialect.class, comment = "HANA currently requires specifying table name by 'FOR UPDATE of t1.c1' if there are more than one tables/views/subqueries in the FROM clause") - @SkipForDialect( value = H2Dialect.class, comment = "Feature not supported: MVCC=TRUE && FOR UPDATE && JOIN") - @Test - public void testNewSessionLifecycle() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Serializable fid = null; - try { - Foo f = new Foo(); - s.save(f); - fid = s.getIdentifier(f); - s.getTransaction().commit(); - } - catch (Exception e) { - s.getTransaction().rollback(); - throw e; - } - finally { - s.close(); - } - - s = openSession(); - s.beginTransaction(); - try { - Foo f = new Foo(); - s.delete(f); - s.getTransaction().commit(); - } - catch (Exception e) { - s.getTransaction().rollback(); - throw e; - } - finally { - s.close(); - } - - s = openSession(); - s.beginTransaction(); - try { - Foo f = (Foo) s.load(Foo.class, fid, LockMode.UPGRADE); - - s.delete(f); - s.flush(); - s.getTransaction().commit(); - } - catch (Exception e) { - s.getTransaction().rollback(); - throw e; - } - finally { - s.close(); - } - } - - @Test - public void testOrderBy() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Foo foo = new Foo(); - s.save(foo); - List list = s.createQuery( - "select foo from Foo foo, Fee fee where foo.dependent = fee order by foo.string desc, foo.component.count asc, fee.id" - ).list(); - assertTrue( "order by", list.size()==1 ); - Foo foo2 = new Foo(); - s.save(foo2); - foo.setFoo(foo2); - list = s.createQuery( - "select foo.foo, foo.dependent from Foo foo order by foo.foo.string desc, foo.component.count asc, foo.dependent.id" - ).list(); - assertTrue( "order by", list.size()==1 ); - list = s.createQuery( "select foo from Foo foo order by foo.dependent.id, foo.dependent.fi" ).list(); - assertTrue( "order by", list.size()==2 ); - s.delete(foo); - s.delete(foo2); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Many manyB = new Many(); - s.save(manyB); - One oneB = new One(); - s.save(oneB); - oneB.setValue("b"); - manyB.setOne(oneB); - Many manyA = new Many(); - s.save(manyA); - One oneA = new One(); - s.save(oneA); - oneA.setValue("a"); - manyA.setOne(oneA); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - List results = s.createQuery( "SELECT one FROM " + One.class.getName() + " one ORDER BY one.value ASC" ).list(); - assertEquals( 2, results.size() ); - assertEquals( "'a' isn't first element", "a", ( (One) results.get(0) ).getValue() ); - assertEquals( "'b' isn't second element", "b", ( (One) results.get(1) ).getValue() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - results = s.createQuery( "SELECT many.one FROM " + Many.class.getName() + " many ORDER BY many.one.value ASC, many.one.id" ) - .list(); - assertEquals( 2, results.size() ); - assertEquals( 2, results.size() ); - assertEquals( "'a' isn't first element", "a", ( (One) results.get(0) ).getValue() ); - assertEquals( "'b' isn't second element", "b", ( (One) results.get(1) ).getValue() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - oneA = (One)s.load(One.class, oneA.getKey()); - manyA = (Many)s.load(Many.class, manyA.getKey()); - oneB = (One)s.load(One.class, oneB.getKey()); - manyB = (Many)s.load(Many.class, manyB.getKey()); - s.delete(manyA); - s.delete(oneA); - s.delete(manyB); - s.delete(oneB); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testManyToOne() throws Exception { - Session s = openSession(); - s.beginTransaction(); - One one = new One(); - s.save(one); - one.setValue( "yada" ); - Many many = new Many(); - many.setOne( one ); - s.save( many ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - one = (One) s.load( One.class, one.getKey() ); - one.getManies().size(); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - many = (Many) s.load( Many.class, many.getKey() ); - assertTrue( "many-to-one assoc", many.getOne()!=null ); - s.delete( many.getOne() ); - s.delete(many); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testSaveDelete() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Foo f = new Foo(); - s.save(f); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.delete( s.load( Foo.class, f.getKey() ) ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testProxyArray() throws Exception { - Session s = openSession(); - s.beginTransaction(); - GlarchProxy g = new Glarch(); - Glarch g1 = new Glarch(); - Glarch g2 = new Glarch(); - g.setProxyArray( new GlarchProxy[] { g1, g2 } ); - Glarch g3 = new Glarch(); - s.save(g3); - g2.setProxyArray( new GlarchProxy[] {null, g3, g} ); - Set set = new HashSet(); - set.add(g1); - set.add(g2); - g.setProxySet(set); - s.save(g); - s.save(g1); - s.save(g2); - Serializable id = s.getIdentifier(g); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - g = (GlarchProxy) s.load(Glarch.class, id); - assertTrue( "array of proxies", g.getProxyArray().length==2 ); - assertTrue( "array of proxies", g.getProxyArray()[0]!=null ); - assertTrue("deferred load test",g.getProxyArray()[1].getProxyArray()[0]==null ); - assertTrue("deferred load test",g.getProxyArray()[1].getProxyArray()[2]==g ); - assertTrue( "set of proxies", g.getProxySet().size()==2 ); - Iterator iter = s.createQuery( "from Glarch g" ).iterate(); - while ( iter.hasNext() ) { - iter.next(); - iter.remove(); - } - s.getTransaction().commit(); - s.disconnect(); - SerializationHelper.deserialize( SerializationHelper.serialize(s) ); - s.close(); - } - - @Test - public void testCache() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Immutable im = new Immutable(); - s.save(im); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.load( im, im.getId() ); - s.getTransaction().commit(); - s.close(); - - final Session s2 = openSession(); - s2.beginTransaction(); - s2.load( im, im.getId() ); - assertEquals( - "cached object identity", - im, - s2.createQuery( "from Immutable im where im = ?" ).setParameter( - 0, im, s2.getTypeHelper().entity( Immutable.class ) - ).uniqueResult() - ); - s2.doWork( - new AbstractWork() { - @Override - public void execute(Connection connection) throws SQLException { - Statement st = connection.createStatement(); - st.executeUpdate( "delete from immut" ); - } - } - ); - s2.getTransaction().commit(); - s2.close(); - } - - @Test - public void testFindLoad() throws Exception { - Session s = openSession(); - s.beginTransaction(); - FooProxy foo = new Foo(); - s.save(foo); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - foo = (FooProxy) s.createQuery( "from Foo foo" ).list().get(0); - FooProxy foo2 = (FooProxy) s.load( Foo.class, foo.getKey() ); - assertTrue( "find returns same object as load", foo == foo2 ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - foo2 = (FooProxy) s.load( Foo.class, foo.getKey() ); - foo = (FooProxy) s.createQuery( "from Foo foo" ).list().get(0); - assertTrue( "find returns same object as load", foo == foo2 ); - doDelete( s, "from Foo foo" ); - s.getTransaction().commit(); - s.close(); - } - - @SkipForDialect(value = AbstractHANADialect.class, comment = "HANA currently requires specifying table name by 'FOR UPDATE of t1.c1' if there are more than one tables/views/subqueries in the FROM clause") - @SkipForDialect( value = H2Dialect.class, comment = "Feature not supported: MVCC=TRUE && FOR UPDATE && JOIN") - @Test - public void testRefresh() throws Exception { - final Session s = openSession(); - s.beginTransaction(); - Foo foo = new Foo(); - s.save( foo ); - s.flush(); - s.doWork( - new AbstractWork() { - @Override - public void execute(Connection connection) throws SQLException { - final String sql = "update " + getDialect().openQuote() + "foos" + getDialect().closeQuote() + " set long_ = -3"; - Statement st = connection.createStatement(); - st.executeUpdate( sql ); - } - } - ); - s.refresh(foo); - assertEquals( Long.valueOf( -3l ), foo.getLong() ); - // NOTE : this test used to test for LockMode.READ here, but that actually highlights a bug - // `foo` has just been inserted and then updated in this same Session - its lock mode - // therefore ought to be WRITE. See https://hibernate.atlassian.net/browse/HHH-12257 - assertEquals( LockMode.WRITE, s.getCurrentLockMode( foo ) ); - s.refresh(foo, LockMode.UPGRADE); - if ( getDialect().supportsOuterJoinForUpdate() ) { - assertEquals( LockMode.UPGRADE, s.getCurrentLockMode( foo ) ); - } - s.delete(foo); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testAutoFlush() throws Exception { - Session s = openSession(); - Transaction txn = s.beginTransaction(); - FooProxy foo = new Foo(); - s.save(foo); - assertTrue( "autoflush create", s.createQuery( "from Foo foo" ).list().size()==1 ); - foo.setChar( 'X' ); - assertTrue( "autoflush update", s.createQuery( "from Foo foo where foo.char='X'" ).list().size()==1 ); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - foo = (FooProxy) s.load( Foo.class, foo.getKey() ); - //s.update( new Foo(), foo.getKey() ); - //assertTrue( s.find("from Foo foo where not foo.char='X'").size()==1, "autoflush update" ); - if ( !(getDialect() instanceof MySQLDialect) && !(getDialect() instanceof HSQLDialect) && !(getDialect() instanceof PointbaseDialect) ) { - foo.setBytes( "osama".getBytes() ); - assertTrue( "autoflush collection update", - s.createQuery( "from Foo foo where 111 in elements(foo.bytes)" ).list().size()==1 ); - foo.getBytes()[0] = 69; - assertTrue( "autoflush collection update", - s.createQuery( "from Foo foo where 69 in elements(foo.bytes)" ).list() - .size()==1 ); - } - s.delete(foo); - assertTrue( "autoflush delete", s.createQuery( "from Foo foo" ).list().size()==0 ); - txn.commit(); - s.close(); - } - - @Test - public void testVeto() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Vetoer v = new Vetoer(); - s.save(v); - s.save(v); - s.getTransaction().commit(); - s.close(); - s = openSession(); - s.beginTransaction(); - s.update( v ); - s.update( v ); - s.delete( v ); - s.delete( v ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testSerializableType() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Vetoer v = new Vetoer(); - v.setStrings( new String[] {"foo", "bar", "baz"} ); - s.save( v ); Serializable id = s.save(v); - v.getStrings()[1] = "osama"; - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - v = (Vetoer) s.load(Vetoer.class, id); - assertTrue( "serializable type", v.getStrings()[1].equals( "osama" ) ); - s.delete(v); s.delete( v ); - s.flush(); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testAutoFlushCollections() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Baz baz = new Baz(); - baz.setDefaults(); - s.save(baz); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - baz = (Baz) s.load(Baz.class, baz.getCode()); - baz.getStringArray()[0] = "bark"; - Iterator i = s.createQuery( "select elements(baz.stringArray) from Baz baz" ).iterate(); - boolean found = false; - while ( i.hasNext() ) { - if ( "bark".equals( i.next() ) ) found = true; - } - assertTrue(found); - baz.setStringArray(null); - i = s.createQuery( "select distinct elements(baz.stringArray) from Baz baz" ).iterate(); - assertTrue( !i.hasNext() ); - baz.setStringArray( new String[] { "foo", "bar" } ); - i = s.createQuery( "select elements(baz.stringArray) from Baz baz" ).iterate(); - assertTrue( i.hasNext() ); - - Foo foo = new Foo(); - s.save(foo); - s.flush(); - baz.setFooArray( new Foo[] {foo} ); - - i = s.createQuery( "select foo from Baz baz join baz.fooArray foo" ).iterate(); - found = false; - while ( i.hasNext() ) { - if ( foo==i.next() ) found = true; - } - assertTrue(found); - - baz.getFooArray()[0] = null; - i = s.createQuery( "select foo from Baz baz join baz.fooArray foo" ).iterate(); - assertTrue( !i.hasNext() ); - baz.getFooArray()[0] = foo; - i = s.createQuery( "select elements(baz.fooArray) from Baz baz" ).iterate(); - assertTrue( i.hasNext() ); - - if ( !(getDialect() instanceof MySQLDialect) - && !(getDialect() instanceof HSQLDialect) - && !(getDialect() instanceof InterbaseDialect) - && !(getDialect() instanceof PointbaseDialect) - && !(getDialect() instanceof SAPDBDialect) ) { - baz.getFooArray()[0] = null; - i = s.createQuery( "from Baz baz where ? in elements(baz.fooArray)" ) - .setParameter( 0, foo, s.getTypeHelper().entity( Foo.class ) ) - .iterate(); - assertTrue( !i.hasNext() ); - baz.getFooArray()[0] = foo; - i = s.createQuery( "select foo from Foo foo where foo in (select elt from Baz baz join baz.fooArray elt)" ) - .iterate(); - assertTrue( i.hasNext() ); - } - s.delete(foo); - s.delete(baz); - tx.commit(); - s.close(); - } - - @Test - @RequiresDialect(value = H2Dialect.class, comment = "this is more like a unit test") - public void testUserProvidedConnection() throws Exception { - ConnectionProvider dcp = ConnectionProviderBuilder.buildConnectionProvider(); - Session s = sessionFactory().withOptions().connection( dcp.getConnection() ).openSession(); - Transaction tx = s.beginTransaction(); - s.createQuery( "from Fo" ).list(); - tx.commit(); - Connection c = s.disconnect(); - assertTrue( c != null ); - s.reconnect( c ); - tx = s.beginTransaction(); - s.createQuery( "from Fo" ).list(); - tx.commit(); - c.close(); - } - - @Test - public void testCachedCollection() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - baz.setDefaults(); - s.save(baz); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.load( Baz.class, baz.getCode() ); - ( (FooComponent) baz.getTopComponents().get(0) ).setCount(99); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - baz = (Baz) s.load( Baz.class, baz.getCode() ); - assertTrue( ((FooComponent) baz.getTopComponents().get( 0 )).getCount() == 99 ); - s.delete( baz ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testComplicatedQuery() throws Exception { - Session s = openSession(); - Transaction txn = s.beginTransaction(); - Foo foo = new Foo(); - Serializable id = s.save(foo); - assertTrue( id != null ); - Qux q = new Qux("q"); - foo.getDependent().setQux(q); - s.save( q ); - q.getFoo().setString( "foo2" ); - //s.flush(); - //s.connection().commit(); - assertTrue( - s.createQuery( "from Foo foo where foo.dependent.qux.foo.string = 'foo2'" ).iterate().hasNext() - ); - s.delete( foo ); - txn.commit(); - s.close(); - } - - @Test - public void testLoadAfterDelete() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Foo foo = new Foo(); - Serializable id = s.save(foo); - s.flush(); - s.delete(foo); - boolean err=false; - try { - s.load(Foo.class, id); - } - catch (ObjectNotFoundException ode) { - err=true; - } - assertTrue(err); - s.flush(); - err=false; - try { - ( (FooProxy) s.load(Foo.class, id) ).getBool(); - } - catch (ObjectNotFoundException onfe) { - err=true; - } - assertTrue(err); - id = FumTest.fumKey( "abc" ); //yuck!! - Fo fo = Fo.newFo( (FumCompositeID) id ); - s.save(fo); - s.flush(); - s.delete(fo); - err=false; - try { - s.load(Fo.class, id); - } - catch (ObjectNotFoundException ode) { - err=true; - } - assertTrue(err); - s.flush(); - err=false; - try { - s.load(Fo.class, id); - } - catch (ObjectNotFoundException onfe) { - err=true; - } - assertTrue(err); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testObjectType() throws Exception { - Session s = openSession(); - s.beginTransaction(); - GlarchProxy g = new Glarch(); - Foo foo = new Foo(); - g.setAny( foo ); - Serializable gid = s.save( g ); - s.save(foo); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - g = (GlarchProxy) s.load(Glarch.class, gid); - assertTrue( g.getAny()!=null && g.getAny() instanceof FooProxy ); - s.delete( g.getAny() ); - s.delete( g ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testAny() throws Exception { - Session s = openSession(); - s.beginTransaction(); - One one = new One(); - BarProxy foo = new Bar(); - foo.setObject(one); - Serializable fid = s.save(foo); - Serializable oid = one.getKey(); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - List results = s.createQuery( "from Bar bar where bar.object.id = ? and bar.object.class = ?" ) - .setParameter( 0, oid, StandardBasicTypes.LONG ) - .setParameter( 1, new Character('O'), StandardBasicTypes.CHARACTER ) - .list(); - assertEquals( 1, results.size() ); - results = s.createQuery( "select one from One one, Bar bar where bar.object.id = one.id and bar.object.class = 'O'" ) - .list(); - assertEquals( 1, results.size() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - foo = (BarProxy) s.load(Foo.class, fid); - assertTrue( foo.getObject()!=null && foo.getObject() instanceof One && s.getIdentifier( foo.getObject() ).equals(oid) ); - //s.delete( foo.getObject() ); - s.delete(foo); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testEmbeddedCompositeID() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Location l = new Location(); - l.setCountryCode("AU"); - l.setDescription("foo bar"); - l.setLocale( Locale.getDefault() ); - l.setStreetName("Brunswick Rd"); - l.setStreetNumber(300); - l.setCity("Melbourne"); - s.save(l); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.setFlushMode(FlushMode.MANUAL); - l = (Location) s.createQuery( "from Location l where l.countryCode = 'AU' and l.description='foo bar'" ) - .list() - .get(0); - assertTrue( l.getCountryCode().equals("AU") ); - assertTrue( l.getCity().equals("Melbourne") ); - assertTrue( l.getLocale().equals( Locale.getDefault() ) ); - assertTrue( s.createCriteria(Location.class).add( Restrictions.eq( "streetNumber", new Integer(300) ) ).list().size()==1 ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - l.setDescription("sick're"); - s.update(l); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - l = new Location(); - l.setCountryCode("AU"); - l.setDescription("foo bar"); - l.setLocale(Locale.ENGLISH); - l.setStreetName("Brunswick Rd"); - l.setStreetNumber(300); - l.setCity("Melbourne"); - assertTrue( l==s.load(Location.class, l) ); - assertTrue( l.getLocale().equals( Locale.getDefault() ) ); - s.delete(l); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testAutosaveChildren() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Baz baz = new Baz(); - Set bars = new HashSet(); - baz.setCascadingBars(bars); - s.save(baz); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - baz = (Baz) s.load( Baz.class, baz.getCode() ); - baz.getCascadingBars().add( new Bar() ); - baz.getCascadingBars().add( new Bar() ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - baz = (Baz) s.load( Baz.class, baz.getCode() ); - assertTrue( baz.getCascadingBars().size()==2 ); - assertTrue( baz.getCascadingBars().iterator().next()!=null ); - baz.getCascadingBars().clear(); //test all-delete-orphan; - s.flush(); - assertTrue( s.createQuery( "from Bar bar" ).list().size()==0 ); - s.delete(baz); - t.commit(); - s.close(); - } - - @Test - public void testOrphanDelete() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Baz baz = new Baz(); - Set bars = new HashSet(); - baz.setCascadingBars(bars); - bars.add( new Bar() ); - bars.add( new Bar() ); - bars.add( new Bar() ); - bars.add( new Bar() ); - s.save(baz); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - baz = (Baz) s.load( Baz.class, baz.getCode() ); - bars = baz.getCascadingBars(); - assertEquals( 4, bars.size() ); - bars.remove( bars.iterator().next() ); - assertEquals( 3, s.createQuery( "From Bar bar" ).list().size() ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - baz = (Baz) s.load( Baz.class, baz.getCode() ); - bars = baz.getCascadingBars(); - assertEquals( 3, bars.size() ); - bars.remove( bars.iterator().next() ); - s.delete(baz); - bars.remove( bars.iterator().next() ); - assertEquals( 0, s.createQuery( "From Bar bar" ).list().size() ); - t.commit(); - s.close(); - } - - @Test - public void testTransientOrphanDelete() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Baz baz = new Baz(); - Set bars = new HashSet(); - baz.setCascadingBars(bars); - bars.add( new Bar() ); - bars.add( new Bar() ); - bars.add( new Bar() ); - List foos = new ArrayList(); - foos.add( new Foo() ); - foos.add( new Foo() ); - baz.setFooBag(foos); - s.save(baz); - Iterator i = new JoinedIterator( new Iterator[] {foos.iterator(), bars.iterator()} ); - while ( i.hasNext() ) { - FooComponent cmp = ( (Foo) i.next() ).getComponent(); - s.delete( cmp.getGlarch() ); - cmp.setGlarch(null); - } - t.commit(); - s.close(); - - bars.remove( bars.iterator().next() ); - foos.remove(1); - s = openSession(); - t = s.beginTransaction(); - s.update(baz); - assertEquals( 2, s.createQuery( "From Bar bar" ).list().size() ); - assertEquals( 3, s.createQuery( "From Foo foo" ).list().size() ); - t.commit(); - s.close(); - - foos.remove(0); - s = openSession(); - t = s.beginTransaction(); - s.update(baz); - bars.remove( bars.iterator().next() ); - assertEquals( 1, s.createQuery( "From Foo foo" ).list().size() ); - s.delete(baz); - //s.flush(); - assertEquals( 0, s.createQuery( "From Foo foo" ).list().size() ); - t.commit(); - s.close(); - } - - @TestForIssue( jiraKey = "HHH-8662" ) - public void testProxiesInCollections() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Baz baz = new Baz(); - Bar bar = new Bar(); - Bar bar2 = new Bar(); - s.save(bar); - Serializable bar2id = s.save(bar2); - baz.setFooArray( new Foo[] { bar, bar2 } ); - HashSet set = new HashSet(); - bar = new Bar(); - s.save(bar); - set.add(bar); - baz.setFooSet(set); - set = new HashSet(); - set.add( new Bar() ); - set.add( new Bar() ); - baz.setCascadingBars(set); - ArrayList list = new ArrayList(); - list.add( new Foo() ); - baz.setFooBag(list); - Serializable id = s.save(baz); - Serializable bid = ( (Bar) baz.getCascadingBars().iterator().next() ).getKey(); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - BarProxy barprox = (BarProxy) s.load(Bar.class, bid); - BarProxy bar2prox = (BarProxy) s.load(Bar.class, bar2id); - assertTrue(bar2prox instanceof HibernateProxy); - assertTrue(barprox instanceof HibernateProxy); - baz = (Baz) s.load(Baz.class, id); - Iterator i = baz.getCascadingBars().iterator(); - BarProxy b1 = (BarProxy) i.next(); - BarProxy b2 = (BarProxy) i.next(); - assertTrue( ( b1==barprox && !(b2 instanceof HibernateProxy) ) || ( b2==barprox && !(b1 instanceof HibernateProxy) ) ); //one-to-many - // . - */ - -//$Id: FumTest.java 10977 2006-12-12 23:28:04Z steve.ebersole@jboss.com $ -package org.hibernate.orm.test.legacy; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.hibernate.FetchMode; -import org.hibernate.FlushMode; -import org.hibernate.Hibernate; -import org.hibernate.HibernateException; -import org.hibernate.LockMode; -import org.hibernate.query.Query; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; -import org.hibernate.criterion.MatchMode; -import org.hibernate.criterion.Restrictions; -import org.hibernate.dialect.AbstractHANADialect; -import org.hibernate.dialect.HSQLDialect; -import org.hibernate.dialect.MckoiDialect; -import org.hibernate.dialect.MySQLDialect; -import org.hibernate.dialect.PointbaseDialect; -import org.hibernate.dialect.SybaseASE15Dialect; -import org.hibernate.dialect.TimesTenDialect; -import org.hibernate.transform.Transformers; -import org.hibernate.type.EntityType; -import org.hibernate.type.StandardBasicTypes; -import org.hibernate.type.StringType; -import org.hibernate.type.Type; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.SkipForDialect; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -@RequiresDialectFeature(DialectChecks.SupportsNoColumnInsert.class) -public class FumTest extends LegacyTestCase { - private static short fumKeyShort = 1; - - @Override - protected boolean isCleanupTestDataRequired() { - return true; - } - - @Override - public String[] getMappings() { - return new String[] { - "legacy/FooBar.hbm.xml", - "legacy/Baz.hbm.xml", - "legacy/Qux.hbm.xml", - "legacy/Glarch.hbm.xml", - "legacy/Fum.hbm.xml", - "legacy/Fumm.hbm.xml", - "legacy/Fo.hbm.xml", - "legacy/One.hbm.xml", - "legacy/Many.hbm.xml", - "legacy/Immutable.hbm.xml", - "legacy/Fee.hbm.xml", - "legacy/Vetoer.hbm.xml", - "legacy/Holder.hbm.xml", - "legacy/Location.hbm.xml", - "legacy/Stuff.hbm.xml", - "legacy/Container.hbm.xml", - "legacy/Simple.hbm.xml", - "legacy/Middle.hbm.xml" - }; - } - - @Override - public void configure(Configuration cfg) { - super.configure(cfg); - Properties props = new Properties(); - props.put( Environment.ORDER_INSERTS, "true" ); - props.put( Environment.STATEMENT_BATCH_SIZE, "10" ); - cfg.addProperties( props ); - } - - @Test - public void testQuery() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - s.createQuery("from Fum fum where fum.fo.id.string = 'x'").list(); - t.commit(); - s.close(); - } - - @Test - public void testCriteriaCollection() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Fum fum = new Fum( fumKey("fum") ); - fum.setFum("a value"); - fum.getMapComponent().getFummap().put("self", fum); - fum.getMapComponent().getStringmap().put("string", "a staring"); - fum.getMapComponent().getStringmap().put("string2", "a notha staring"); - fum.getMapComponent().setCount(1); - s.save(fum); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Fum b = (Fum) s.createCriteria(Fum.class).add( - Restrictions.in("fum", new String[] { "a value", "no value" } ) - ) - .uniqueResult(); - assertTrue( Hibernate.isInitialized( b.getMapComponent().getStringmap() ) ); - assertTrue( b.getMapComponent().getFummap().size()==1 ); - assertTrue( b.getMapComponent().getStringmap().size()==2 ); - s.delete(b); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testCriteria() throws Exception { - Session s = openSession(); - Transaction txn = s.beginTransaction(); - Fum fum = new Fum( fumKey("fum") ); - fum.setFo( new Fum( fumKey("fo") ) ); - fum.setFum("fo fee fi"); - fum.getFo().setFum("stuff"); - Fum fr = new Fum( fumKey("fr") ); - fr.setFum("goo"); - Fum fr2 = new Fum( fumKey("fr2") ); - fr2.setFum("soo"); - fum.setFriends( new HashSet() ); - fum.getFriends().add(fr); - fum.getFriends().add(fr2); - s.save(fr); - s.save(fr2); - s.save( fum.getFo() ); - s.save(fum); - - Criteria base = s.createCriteria(Fum.class) - .add( Restrictions.like("fum", "f", MatchMode.START) ); - base.createCriteria("fo") - .add( Restrictions.isNotNull("fum") ); - base.createCriteria("friends") - .add( Restrictions.like("fum", "g%") ); - List list = base.list(); - assertTrue( list.size()==1 && list.get(0)==fum ); - - base = s.createCriteria(Fum.class) - .add( Restrictions.like("fum", "f%") ) - .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP); - base.createCriteria("fo", "fo") - .add( Restrictions.isNotNull("fum") ); - base.createCriteria("friends", "fum") - .add( Restrictions.like("fum", "g", MatchMode.START) ); - Map map = (Map) base.uniqueResult(); - - assertTrue( - map.get("this")==fum && - map.get("fo")==fum.getFo() && - fum.getFriends().contains( map.get("fum") ) && - map.size()==3 - ); - - base = s.createCriteria(Fum.class) - .add( Restrictions.like("fum", "f%") ) - .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP) - .setFetchMode( "friends", FetchMode.JOIN ); - base.createCriteria("fo", "fo") - .add( Restrictions.eq( "fum", fum.getFo().getFum() ) ); - map = (Map) base.list().get(0); - - assertTrue( - map.get("this")==fum && - map.get("fo")==fum.getFo() && - map.size()==2 - ); - - list = s.createCriteria(Fum.class) - .createAlias("friends", "fr") - .createAlias("fo", "fo") - .add( Restrictions.like("fum", "f%") ) - .add( Restrictions.isNotNull("fo") ) - .add( Restrictions.isNotNull("fo.fum") ) - .add( Restrictions.like("fr.fum", "g%") ) - .add( Restrictions.eqProperty("fr.id.short", "id.short") ) - .list(); - assertTrue( list.size()==1 && list.get(0)==fum ); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - base = s.createCriteria(Fum.class) - .add( Restrictions.like("fum", "f%") ); - base.createCriteria("fo") - .add( Restrictions.isNotNull("fum") ); - base.createCriteria("friends") - .add( Restrictions.like("fum", "g%") ); - fum = (Fum) base.list().get(0); - assertTrue( fum.getFriends().size()==2 ); - s.delete(fum); - s.delete( fum.getFo() ); - Iterator iter = fum.getFriends().iterator(); - while ( iter.hasNext() ) { - s.delete( iter.next() ); - } - txn.commit(); - s.close(); - } - - static public class ABean { - public Fum fum; - public Fum fo; - public Fum getFo() { - return fo; - } - public void setFo(Fum fo) { - this.fo = fo; - } - public Fum getFum() { - return fum; - } - public void setFum(Fum fum) { - this.fum = fum; - } - } - - @Test - public void testBeanResultTransformer() throws HibernateException, SQLException { - Session s = openSession(); - Transaction transaction = s.beginTransaction(); - Fum fum = new Fum( fumKey("fum") ); - fum.setFo( new Fum( fumKey("fo") ) ); - fum.setFum("fo fee fi"); - fum.getFo().setFum("stuff"); - Fum fr = new Fum( fumKey("fr") ); - fr.setFum("goo"); - Fum fr2 = new Fum( fumKey("fr2") ); - fr2.setFum("soo"); - fum.setFriends( new HashSet() ); - fum.getFriends().add(fr); - fum.getFriends().add(fr2); - s.save(fr); - s.save(fr2); - s.save( fum.getFo() ); - s.save(fum); - - Criteria test = s.createCriteria(Fum.class, "xam") - .createCriteria("fo", "fo") - .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP); - - Map fc = (Map) test.list().get(0); - assertNotNull(fc.get("xam")); - - Criteria base = s.createCriteria(Fum.class, "fum") - .add( Restrictions.like("fum", "f%") ) - .setResultTransformer(Transformers.aliasToBean(ABean.class)) - .setFetchMode("friends", FetchMode.JOIN); - base.createCriteria("fo", "fo") - .add( Restrictions.eq( "fum", fum.getFo().getFum() ) ); - ABean map = (ABean) base.list().get(0); - - assertTrue( - map.getFum()==fum && - map.getFo()==fum.getFo() ); - - s.delete(fr); - s.delete(fr2); - s.delete(fum); - s.delete(fum.getFo()); - s.flush(); - transaction.commit(); - s.close(); - } - - @Test - public void testListIdentifiers() throws Exception { - Session s = openSession(); - Transaction txn = s.beginTransaction(); - Fum fum = new Fum( fumKey("fum") ); - fum.setFum("fo fee fi"); - s.save(fum); - fum = new Fum( fumKey("fi") ); - fum.setFum("fee fi fo"); - s.save(fum); - List list = s.createQuery( "select fum.id from Fum as fum where not fum.fum='FRIEND'" ).list(); - assertTrue( "list identifiers", list.size()==2); - Iterator iter = s.createQuery( "select fum.id from Fum fum where not fum.fum='FRIEND'" ).iterate(); - int i=0; - while ( iter.hasNext() ) { - assertTrue( "iterate identifiers", iter.next() instanceof FumCompositeID); - i++; - } - assertTrue(i==2); - - s.delete( s.load(Fum.class, (Serializable) list.get(0) ) ); - s.delete( s.load(Fum.class, (Serializable) list.get(1) ) ); - txn.commit(); - s.close(); - } - - - public static FumCompositeID fumKey(String str) { - return fumKey(str,false); - } - - private static FumCompositeID fumKey(String str, boolean aCompositeQueryTest) { - FumCompositeID id = new FumCompositeID(); - id.setString( str ); - - if (aCompositeQueryTest) { - id.setShort( fumKeyShort++ ); - } - else { - id.setShort( (short) 12 ); - } - - return id; - } - - @Test - public void testCompositeID() throws Exception { - Session s = openSession(); - Transaction txn = s.beginTransaction(); - FumCompositeID fumKey = fumKey("fum"); - Fum fum = new Fum( fumKey ); - fum.setFum("fee fi fo"); - s.save(fum); - assertTrue( "load by composite key", fum==s.load( Fum.class, fumKey ) ); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - if ( getDialect() instanceof AbstractHANADialect ){ - // HANA currently requires specifying table name by 'FOR UPDATE of t1.c1' if there are more than one tables/views/subqueries in the FROM clause - fum = (Fum) s.load( Fum.class, fumKey ); - } else { - fum = (Fum) s.load( Fum.class, fumKey, LockMode.UPGRADE ); - } - - assertTrue( "load by composite key", fum!=null ); - - FumCompositeID fumKey2 = fumKey("fi"); - Fum fum2 = new Fum( fumKey2 ); - fum2.setFum("fee fo fi"); - fum.setFo(fum2); - s.save(fum2); - assertTrue( - "find composite keyed objects", - s.createQuery( "from Fum fum where not fum.fum='FRIEND'" ).list().size()==2 - ); - assertTrue( - "find composite keyed object", - s.createQuery( "select fum from Fum fum where fum.fum='fee fi fo'" ).list().get(0)==fum - ); - fum.setFo(null); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - Iterator iter = s.createQuery( "from Fum fum where not fum.fum='FRIEND'" ).iterate(); - int i = 0; - while ( iter.hasNext() ) { - fum = (Fum) iter.next(); - //iter.remove(); - s.delete(fum); - i++; - } - assertTrue( "iterate on composite key", i==2 ); - txn.commit(); - s.close(); - } - - @Test - public void testCompositeIDOneToOne() throws Exception { - Session s = openSession(); - Transaction txn = s.beginTransaction(); - FumCompositeID fumKey = fumKey("fum"); - Fum fum = new Fum( fumKey ); - fum.setFum("fee fi fo"); - //s.save(fum); - Fumm fumm = new Fumm(); - fumm.setFum(fum); - s.save(fumm); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - fumm = (Fumm) s.load( Fumm.class, fumKey ); - //s.delete( fumm.getFum() ); - s.delete(fumm); - txn.commit(); - s.close(); - } - - @Test - public void testCompositeIDQuery() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Fum fee = new Fum( fumKey("fee",true) ); - fee.setFum("fee"); - s.save(fee); - Fum fi = new Fum( fumKey("fi",true) ); - fi.setFum("fi"); - short fiShort = fi.getId().getShort(); - s.save(fi); - Fum fo = new Fum( fumKey("fo",true) ); - fo.setFum("fo"); - s.save(fo); - Fum fum = new Fum( fumKey("fum",true) ); - fum.setFum("fum"); - s.save(fum); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - // Try to find the Fum object "fo" that we inserted searching by the string in the id - List vList = s.createQuery( "from Fum fum where fum.id.string='fo'" ).list(); - assertTrue( "find by composite key query (find fo object)", vList.size() == 1 ); - fum = (Fum)vList.get(0); - assertTrue( "find by composite key query (check fo object)", fum.getId().getString().equals("fo") ); - - // Try to find the Fum object "fi" that we inserted - vList = s.createQuery( "from Fum fum where fum.id.short = ?" ) - .setParameter( 0, new Short(fiShort), StandardBasicTypes.SHORT ) - .list(); - assertEquals( "find by composite key query (find fi object)", 1, vList.size() ); - fi = (Fum)vList.get(0); - assertEquals( "find by composite key query (check fi object)", "fi", fi.getId().getString() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - assertTrue( - s.createQuery( "select fum.id.short, fum.id.string from Fum fum" ).iterate().hasNext() - ); - assertTrue( - s.createQuery( "select fum.id from Fum fum" ).iterate().hasNext() - ); - Query qu = s.createQuery("select fum.fum, fum , fum.fum from Fum fum"); - Type[] types = qu.getReturnTypes(); - assertTrue( types.length == 3 ); - for ( Type type : types ) { - assertTrue( type != null ); - } - assertTrue( types[0] instanceof StringType ); - assertTrue( types[1] instanceof EntityType ); - assertTrue( types[2] instanceof StringType ); - Iterator iter = qu.iterate(); - int j = 0; - while ( iter.hasNext() ) { - j++; - assertTrue( ( (Object[]) iter.next() )[1] instanceof Fum ); - } - assertTrue( "iterate on composite key", j==8 ); - - fum = (Fum) s.load( Fum.class, fum.getId() ); - s.createFilter( fum.getQuxArray(), "where this.foo is null" ).list(); - s.createFilter( fum.getQuxArray(), "where this.foo.id = ?" ) - .setParameter( 0, "fooid", StandardBasicTypes.STRING ) - .list(); - Query f = s.createFilter( fum.getQuxArray(), "where this.foo.id = :fooId" ); - f.setString("fooId", "abc"); - assertFalse( f.iterate().hasNext() ); - - iter = s.createQuery( "from Fum fum where not fum.fum='FRIEND'" ).iterate(); - int i = 0; - while ( iter.hasNext() ) { - fum = (Fum) iter.next(); - s.delete(fum); - i++; - } - assertTrue( "iterate on composite key", i==4 ); - s.flush(); - - s.createQuery( "from Fum fu, Fum fo where fu.fo.id.string = fo.id.string and fo.fum is not null" ).iterate(); - - s.createQuery( "from Fumm f1 inner join f1.fum f2" ).list(); - - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testCompositeIDCollections() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Fum fum1 = new Fum( fumKey("fum1") ); - Fum fum2 = new Fum( fumKey("fum2") ); - fum1.setFum("fee fo fi"); - fum2.setFum("fee fo fi"); - s.save(fum1); - s.save(fum2); - Qux q = new Qux(); - s.save(q); - Set set = new HashSet(); - List list = new ArrayList(); - set.add(fum1); set.add(fum2); - list.add(fum1); - q.setFums(set); - q.setMoreFums(list); - fum1.setQuxArray( new Qux[] {q} ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - q = (Qux) s.load( Qux.class, q.getKey() ); - assertTrue( "collection of fums", q.getFums().size()==2 ); - assertTrue( "collection of fums", q.getMoreFums().size()==1 ); - assertTrue( "unkeyed composite id collection", ( (Fum) q.getMoreFums().get(0) ).getQuxArray()[0]==q ); - Iterator iter = q.getFums().iterator(); - iter.hasNext(); - Fum f = (Fum) iter.next(); - s.delete(f); - iter.hasNext(); - f = (Fum) iter.next(); - s.delete(f); - s.delete(q); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testDeleteOwner() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Qux q = new Qux(); - s.save(q); - Fum f1 = new Fum( fumKey("f1") ); - Fum f2 = new Fum( fumKey("f2") ); - Set set = new HashSet(); - set.add(f1); - set.add(f2); - List list = new LinkedList(); - list.add(f1); - list.add(f2); - f1.setFum("f1"); - f2.setFum("f2"); - q.setFums(set); - q.setMoreFums(list); - s.save(f1); - s.save(f2); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - q = (Qux) s.load( Qux.class, q.getKey(), LockMode.UPGRADE ); - s.lock( q, LockMode.UPGRADE ); - s.delete(q); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - list = s.createQuery( "from Fum fum where not fum.fum='FRIEND'" ).list(); - assertTrue( "deleted owner", list.size()==2 ); - s.lock( list.get(0), LockMode.UPGRADE ); - s.lock( list.get(1), LockMode.UPGRADE ); - Iterator iter = list.iterator(); - while ( iter.hasNext() ) { - s.delete( iter.next() ); - } - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testCompositeIDs() throws Exception { - Session s = openSession(); - s.beginTransaction(); - FumCompositeID fumKey = fumKey("an instance of fo"); - Fo fo = Fo.newFo( fumKey ); - Properties props = new Properties(); - props.setProperty("foo", "bar"); - props.setProperty("bar", "foo"); - fo.setSerial(props); - fo.setBuf( "abcdefghij1`23%$*^*$*\n\t".getBytes() ); - s.save( fo ); - s.flush(); - props.setProperty("x", "y"); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - fo = (Fo) s.load( Fo.class, fumKey ); - props = (Properties) fo.getSerial(); - assertTrue( props.getProperty("foo").equals("bar") ); - //assertTrue( props.contains("x") ); - assertTrue( props.getProperty("x").equals("y") ); - assertTrue( fo.getBuf()[0]=='a' ); - fo.getBuf()[1]=(byte)126; - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - fo = (Fo) s.load( Fo.class, fumKey ); - assertTrue( fo.getBuf()[1]==126 ); - assertTrue( - s.createQuery( "from Fo fo where fo.id.string like 'an instance of fo'" ).iterate().next()==fo - ); - s.delete(fo); - s.flush(); - try { - s.save( Fo.newFo() ); - assertTrue(false); - } - catch (Exception e) { - //System.out.println( e.getMessage() ); - } - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testKeyManyToOne() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Inner sup = new Inner(); - InnerKey sid = new InnerKey(); - sup.setDudu("dudu"); - sid.setAkey("a"); - sid.setBkey("b"); - sup.setId(sid); - Middle m = new Middle(); - MiddleKey mid = new MiddleKey(); - mid.setOne("one"); - mid.setTwo("two"); - mid.setSup(sup); - m.setId(mid); - m.setBla("bla"); - Outer d = new Outer(); - OuterKey did = new OuterKey(); - did.setRoot(m); - did.setDetailId("detail"); - d.setId(did); - d.setBubu("bubu"); - s.save(sup); - s.save(m); - s.save(d); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Inner in = (Inner) s.createQuery( "from Inner" ).list().get(0); - assertTrue( in.getMiddles().size()==1 ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - assertTrue( s.createQuery( "from Inner _inner join _inner.middles middle" ).list().size()==1 ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - d = (Outer) s.load(Outer.class, did); - assertTrue( d.getId().getRoot().getId().getSup().getDudu().equals("dudu") ); - s.delete(d); - s.delete( d.getId().getRoot() ); - s.save( d.getId().getRoot() ); - s.save(d); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - d = (Outer) s.createQuery( "from Outer o where o.id.detailId = ?" ) - .setParameter( 0, d.getId().getDetailId(), StandardBasicTypes.STRING ) - .list() - .get(0); - s.createQuery( "from Outer o where o.id.root.id.sup.dudu is not null" ).list(); - s.createQuery( "from Outer o where o.id.root.id.sup.id.akey is not null" ).list(); - s.createQuery( "from Inner i where i.backOut.id.root.id.sup.id.akey = i.id.bkey" ).list(); - List l = s.createQuery( "select o.id.root.id.sup.dudu from Outer o where o.id.root.id.sup.dudu is not null" ) - .list(); - assertTrue(l.size()==1); - l = s.createQuery( "select o.id.root.id.sup.id.akey from Outer o where o.id.root.id.sup.id.akey is not null" ) - .list(); - assertTrue(l.size()==1); - s.createQuery( - "select i.backOut.id.root.id.sup.id.akey from Inner i where i.backOut.id.root.id.sup.id.akey = i.id.bkey" - ).list(); - s.createQuery( "from Outer o where o.id.root.bla = ''" ).list(); - s.createQuery( "from Outer o where o.id.root.id.one = ''" ).list(); - s.createQuery( "from Inner inn where inn.id.bkey is not null and inn.backOut.id.root.id.sup.id.akey > 'a'" ) - .list(); - s.createQuery( "from Outer as o left join o.id.root m left join m.id.sup where o.bubu is not null" ).list(); - s.createQuery( "from Outer as o left join o.id.root.id.sup s where o.bubu is not null" ).list(); - s.createQuery( "from Outer as o left join o.id.root m left join o.id.root.id.sup s where o.bubu is not null" ) - .list(); - s.delete(d); - s.delete( d.getId().getRoot() ); - s.delete( d.getId().getRoot().getId().getSup() ); - s.getTransaction().commit(); - s.close(); - } - - @Test - @SkipForDialect( value = SybaseASE15Dialect.class, jiraKey = "HHH-3690" ) - public void testCompositeKeyPathExpressions() throws Exception { - Session s = openSession(); - s.beginTransaction(); - s.createQuery( "select fum1.fo from Fum fum1 where fum1.fo.fum is not null" ).list(); - s.createQuery( "from Fum fum1 where fum1.fo.fum is not null order by fum1.fo.fum" ).list(); - if ( !(getDialect() instanceof MySQLDialect) && !(getDialect() instanceof HSQLDialect) && !(getDialect() instanceof MckoiDialect) && !(getDialect() instanceof PointbaseDialect) ) { - s.createQuery( "from Fum fum1 where exists elements(fum1.friends)" ).list(); - if(!(getDialect() instanceof TimesTenDialect)) { // can't execute because TimesTen can't do subqueries combined with aggreations - s.createQuery( "from Fum fum1 where size(fum1.friends) = 0" ).list(); - } - } - s.createQuery( "select elements(fum1.friends) from Fum fum1" ).list(); - s.createQuery( "from Fum fum1, fr in elements( fum1.friends )" ).list(); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testUnflushedSessionSerialization() throws Exception { - /////////////////////////////////////////////////////////////////////////// - // Test insertions across serializations - Session s = sessionFactory().openSession(); - s.setFlushMode(FlushMode.MANUAL); - s.beginTransaction(); - - Simple simple = new Simple( Long.valueOf(10) ); - simple.setAddress("123 Main St. Anytown USA"); - simple.setCount(1); - simple.setDate( new Date() ); - simple.setName("My UnflushedSessionSerialization Simple"); - simple.setPay( Float.valueOf(5000) ); - s.save( simple ); - - // Now, try to serialize session without flushing... - s.getTransaction().commit(); - Session s2 = spoofSerialization(s); - s.close(); - s = s2; - s.beginTransaction(); - - simple = (Simple) s.load( Simple.class, new Long(10) ); - Simple other = new Simple( Long.valueOf(11) ); - other.init(); - s.save( other ); - - simple.setOther(other); - s.flush(); - - s.getTransaction().commit(); - s.close(); - Simple check = simple; - - /////////////////////////////////////////////////////////////////////////// - // Test updates across serializations - s = sessionFactory().openSession(); - s.setFlushMode(FlushMode.MANUAL); - s.beginTransaction(); - - simple = (Simple) s.get( Simple.class, Long.valueOf(10) ); - assertEquals( "Not same parent instances", check.getName(), simple.getName() ); - assertEquals( "Not same child instances", check.getOther().getName(), other.getName() ); - - simple.setName("My updated name"); - - s.getTransaction().commit(); - s2 = spoofSerialization(s); - s.close(); - s = s2; - s.beginTransaction(); - s.flush(); - - s.getTransaction().commit(); - s.close(); - check = simple; - - /////////////////////////////////////////////////////////////////////////// - // Test deletions across serializations - s = sessionFactory().openSession(); - s.setFlushMode(FlushMode.MANUAL); - s.beginTransaction(); - - simple = (Simple) s.get( Simple.class, Long.valueOf( 10 ) ); - assertEquals( "Not same parent instances", check.getName(), simple.getName() ); - assertEquals( "Not same child instances", check.getOther().getName(), other.getName() ); - - // Now, lets delete across serialization... - s.delete(simple); - - s.getTransaction().commit(); - s2 = spoofSerialization(s); - s.close(); - s = s2; - s.beginTransaction(); - s.flush(); - - s.getTransaction().commit(); - s.close(); - - /////////////////////////////////////////////////////////////////////////// - // Test collection actions across serializations - s = sessionFactory().openSession(); - s.setFlushMode(FlushMode.MANUAL); - s.beginTransaction(); - - Fum fum = new Fum( fumKey("uss-fum") ); - fum.setFo( new Fum( fumKey("uss-fo") ) ); - fum.setFum("fo fee fi"); - fum.getFo().setFum("stuff"); - Fum fr = new Fum( fumKey("uss-fr") ); - fr.setFum("goo"); - Fum fr2 = new Fum( fumKey("uss-fr2") ); - fr2.setFum("soo"); - fum.setFriends( new HashSet() ); - fum.getFriends().add(fr); - fum.getFriends().add(fr2); - s.save(fr); - s.save(fr2); - s.save( fum.getFo() ); - s.save(fum); - - s.getTransaction().commit(); - s2 = spoofSerialization(s); - s.close(); - s = s2; - s.beginTransaction(); - s.flush(); - - s.getTransaction().commit(); - s.close(); - - s = sessionFactory().openSession(); - s.setFlushMode(FlushMode.MANUAL); - s.beginTransaction(); - fum = (Fum) s.load( Fum.class, fum.getId() ); - - assertEquals( "the Fum.friends did not get saved", 2, fum.getFriends().size() ); - - fum.setFriends(null); - s.getTransaction().commit(); - s2 = spoofSerialization(s); - s.close(); - - s = s2; - s.beginTransaction(); - s.flush(); - - s.getTransaction().commit(); - s.close(); - - s = sessionFactory().openSession(); - s.beginTransaction(); - s.setFlushMode(FlushMode.MANUAL); - fum = (Fum) s.load( Fum.class, fum.getId() ); - assertTrue("the Fum.friends is not empty", fum.getFriends() == null || fum.getFriends().size() == 0); - s.getTransaction().commit(); - s.close(); - } - - private Session spoofSerialization(Session session) throws IOException { - try { - // Serialize the incoming out to memory - ByteArrayOutputStream serBaOut = new ByteArrayOutputStream(); - ObjectOutputStream serOut = new ObjectOutputStream(serBaOut); - - serOut.writeObject(session); - - // Now, re-constitute the model from memory - ByteArrayInputStream serBaIn = - new ByteArrayInputStream(serBaOut.toByteArray()); - ObjectInputStream serIn = new ObjectInputStream(serBaIn); - - Session outgoing = (Session) serIn.readObject(); - - return outgoing; - } - catch (ClassNotFoundException cnfe) { - throw new IOException("Unable to locate class on reconstruction"); - } - } - -} - - - - - - - diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/IJ2Test.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/IJ2Test.java deleted file mode 100644 index bb5a3624ae..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/IJ2Test.java +++ /dev/null @@ -1,129 +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 . - */ -package org.hibernate.orm.test.legacy; -import java.io.Serializable; - -import org.junit.Test; - -import org.hibernate.LockMode; -import org.hibernate.Session; - -import static org.junit.Assert.assertTrue; - -/** - * @author Gavin King - */ -public class IJ2Test extends LegacyTestCase { - - public String[] getMappings() { - return new String[] { "legacy/IJ2.hbm.xml" }; - } - - @SuppressWarnings( {"UnusedAssignment"}) - @Test - public void testUnionSubclass() throws Exception { - Session s = sessionFactory().openSession(); - s.beginTransaction(); - I i = new I(); - i.setName( "i" ); - i.setType( 'a' ); - J j = new J(); - j.setName( "j" ); - j.setType( 'x' ); - j.setAmount( 1.0f ); - Serializable iid = s.save(i); - Serializable jid = s.save(j); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictEntityRegion( I.class ); - - s = sessionFactory().openSession(); - s.beginTransaction(); - j = (J) s.get(I.class, jid); - j = (J) s.get(J.class, jid); - i = (I) s.get(I.class, iid); - assertTrue( i.getClass()==I.class ); - j.setAmount( 0.5f ); - s.lock(i, LockMode.UPGRADE); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictEntityRegion( I.class ); - - s = sessionFactory().openSession(); - s.beginTransaction(); - j = (J) s.get(J.class, jid); - j = (J) s.get(I.class, jid); - i = (I) s.get(I.class, iid); - assertTrue( i.getClass()==I.class ); - j.setAmount( 0.5f ); - s.lock(i, LockMode.UPGRADE); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictEntityRegion( I.class ); - - s = sessionFactory().openSession(); - s.beginTransaction(); - assertTrue( s.createQuery( "from I" ).list().size()==2 ); - assertTrue( s.createQuery( "from J" ).list().size()==1 ); - assertTrue( s.createQuery( "from J j where j.amount > 0 and j.name is not null" ).list().size()==1 ); - assertTrue( s.createQuery( "from I i where i.class = org.hibernate.test.legacy.I" ).list().size()==1 ); - assertTrue( s.createQuery( "from I i where i.class = J" ).list().size()==1 ); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictEntityRegion( I.class ); - - s = sessionFactory().openSession(); - s.beginTransaction(); - j = (J) s.get(J.class, jid); - i = (I) s.get(I.class, iid); - K k = new K(); - Serializable kid = s.save(k); - i.setParent(k); - j.setParent(k); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictEntityRegion( I.class ); - - s = sessionFactory().openSession(); - s.beginTransaction(); - j = (J) s.get(J.class, jid); - i = (I) s.get(I.class, iid); - k = (K) s.get(K.class, kid); - System.out.println(k + "=" + i.getParent()); - assertTrue( i.getParent()==k ); - assertTrue( j.getParent()==k ); - assertTrue( k.getIs().size()==2 ); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictEntityRegion( I.class ); - - s = sessionFactory().openSession(); - s.beginTransaction(); - assertTrue( s.createQuery( "from K k inner join k.is i where i.name = 'j'" ).list().size()==1 ); - assertTrue( s.createQuery( "from K k inner join k.is i where i.name = 'i'" ).list().size()==1 ); - assertTrue( s.createQuery( "from K k left join fetch k.is" ).list().size()==2 ); - s.getTransaction().commit(); - s.close(); - - s = sessionFactory().openSession(); - s.beginTransaction(); - j = (J) s.get(J.class, jid); - i = (I) s.get(I.class, iid); - k = (K) s.get(K.class, kid); - s.delete(k); - s.delete(j); - s.delete(i); - s.getTransaction().commit(); - s.close(); - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/IJTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/IJTest.java deleted file mode 100644 index f3b67b07f9..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/IJTest.java +++ /dev/null @@ -1,86 +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 . - */ - -//$Id: IJTest.java 10977 2006-12-12 23:28:04Z steve.ebersole@jboss.com $ -package org.hibernate.orm.test.legacy; - -import java.io.Serializable; - -import org.hibernate.LockMode; -import org.hibernate.LockOptions; -import org.hibernate.Session; -import org.hibernate.dialect.HSQLDialect; - -import org.junit.Test; - -import static org.junit.Assert.assertTrue; - -/** - * @author Gavin King - */ -public class IJTest extends LegacyTestCase { - @Override - public String[] getMappings() { - return new String[] { "legacy/IJ.hbm.xml" }; - } - - @Test - public void testFormulaDiscriminator() throws Exception { - if ( getDialect() instanceof HSQLDialect ) return; - Session s = sessionFactory().openSession(); - s.beginTransaction(); - I i = new I(); - i.setName( "i" ); - i.setType( 'a' ); - J j = new J(); - j.setName( "j" ); - j.setType( 'x' ); - j.setAmount( 1.0f ); - Serializable iid = s.save(i); - Serializable jid = s.save(j); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictEntityRegion( I.class ); - - s = sessionFactory().openSession(); - s.beginTransaction(); - j = (J) s.get(I.class, jid); - i = (I) s.get(I.class, iid); - assertTrue( i.getClass() == I.class ); - j.setAmount( 0.5f ); - s.lock( i, LockMode.UPGRADE ); - s.getTransaction().commit(); - s.close(); - - s = sessionFactory().openSession(); - s.beginTransaction(); - j = (J) s.byId( I.class ).with( LockOptions.UPGRADE ).load( jid ); - i = (I) s.byId( I.class ).with( LockOptions.UPGRADE ).load( iid ); - s.getTransaction().commit(); - s.close(); - - s = sessionFactory().openSession(); - s.beginTransaction(); - assertTrue( s.createQuery( "from I" ).list().size()==2 ); - assertTrue( s.createQuery( "from J" ).list().size()==1 ); - assertTrue( s.createQuery( "from I i where i.class = 0" ).list().size()==1 ); - assertTrue( s.createQuery( "from I i where i.class = 1" ).list().size()==1 ); - s.getTransaction().commit(); - s.close(); - - s = sessionFactory().openSession(); - s.beginTransaction(); - j = (J) s.get(J.class, jid); - i = (I) s.get(I.class, iid); - s.delete(j); - s.delete(i); - s.getTransaction().commit(); - s.close(); - - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/LegacyTestCase.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/LegacyTestCase.java deleted file mode 100644 index e1c4c61022..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/LegacyTestCase.java +++ /dev/null @@ -1,115 +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 . - */ -package org.hibernate.orm.test.legacy; - -import java.util.List; - -import org.hibernate.query.Query; -import org.hibernate.Session; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; -import org.hibernate.dialect.DB2Dialect; -import org.hibernate.dialect.Dialect; -import org.hibernate.dialect.PostgreSQL81Dialect; -import org.hibernate.dialect.PostgreSQLDialect; -import org.hibernate.dialect.CockroachDialect; -import org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory; -import org.hibernate.internal.util.StringHelper; -import org.hibernate.type.Type; - -import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; -import org.junit.Before; - -/** - * @author Steve Ebersole - */ -public abstract class LegacyTestCase extends BaseCoreFunctionalTestCase { - public static final String USE_ANTLR_PARSER_PROP = "legacy.use_antlr_hql_parser"; - - private boolean useAntlrParser; - - @Before - public void checkAntlrParserSetting() { - useAntlrParser = Boolean.valueOf( extractFromSystem( USE_ANTLR_PARSER_PROP ) ); - } - - protected boolean supportsLockingNullableSideOfJoin(Dialect dialect) { - // db2 and pgsql do *NOT* - return ! ( DB2Dialect.class.isInstance( dialect ) || PostgreSQL81Dialect.class.isInstance( dialect ) || PostgreSQLDialect.class.isInstance( dialect ) || - CockroachDialect.class.isInstance( dialect )); - } - - protected static String extractFromSystem(String systemPropertyName) { - try { - return System.getProperty( systemPropertyName ); - } - catch( Throwable t ) { - return null; - } - } - - @Override - protected void cleanupTestData() throws Exception { - Session s = openSession(); - s.beginTransaction(); - List list = s.createQuery( "from java.lang.Object" ).list(); - for ( Object obj : list ) { - s.delete( obj ); - } - s.getTransaction().commit(); - s.close(); - } - - @Override - public void configure(Configuration cfg) { - super.configure( cfg ); - if ( !useAntlrParser ) { - cfg.setProperty( Environment.QUERY_TRANSLATOR, ClassicQueryTranslatorFactory.class.getName() ); - try { - String dialectTrueRepresentation = Dialect.getDialect().toBooleanValueString( true ); - // if this call succeeds, then the dialect is saying to represent true/false as int values... - Integer.parseInt( dialectTrueRepresentation ); - String subs = cfg.getProperties().getProperty( Environment.QUERY_SUBSTITUTIONS ); - if ( subs == null ) { - subs = ""; - } - if ( StringHelper.isEmpty( subs ) ) { - subs = "true=1, false=0"; - } - else { - subs += ", true=1, false=0"; - } - cfg.getProperties().setProperty( Environment.QUERY_SUBSTITUTIONS, subs ); -// cfg.setNamingStrategy( DefaultNamingStrategy.INSTANCE ); - } - catch( NumberFormatException nfe ) { - // the Integer#parseInt call failed... - } - } - cfg.setProperty( AvailableSettings.JDBC_TYLE_PARAMS_ZERO_BASE, "true" ); - } - - protected int doDelete(Session session, String queryString) { - return doDelete( session, session.createQuery( queryString ) ); - } - - protected int doDelete(Session session, String queryString, Object param, Type paramType) { - Query query = session.createQuery( queryString ) - .setParameter( 0, param, paramType ); - return doDelete( session, query ); - } - - protected int doDelete(Session session, Query selectQuery) { - int count = 0; - for ( Object o : selectQuery.list() ) { - session.delete( o ); - count++; - } - return count; - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/MapTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/MapTest.java deleted file mode 100644 index c8083662ff..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/MapTest.java +++ /dev/null @@ -1,169 +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 . - */ -package org.hibernate.orm.test.legacy; -import java.io.Serializable; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Test; - -import org.hibernate.EntityMode; -import org.hibernate.Session; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; -import org.hibernate.criterion.Example; -import org.hibernate.criterion.Restrictions; - -import static org.junit.Assert.assertTrue; - -public class MapTest extends LegacyTestCase { - @Override - public String[] getMappings() { - return new String[] { "legacy/Map.hbm.xml", "legacy/Commento.hbm.xml", "legacy/Marelo.hbm.xml" }; - } - - @Override - public void configure(Configuration cfg) { - super.configure( cfg ); - cfg.setProperty( Environment.DEFAULT_ENTITY_MODE, EntityMode.MAP.toString() ); - } - - @Test - public void testMap() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Map map = new HashMap(); - map.put("$type$", "TestMap"); - map.put( "name", "foo" ); - map.put( "address", "bar" ); - Map cmp = new HashMap(); - cmp.put( "a", new Integer( 1 ) ); - cmp.put( "b", new Float( 1.0 ) ); - map.put( "cmp", cmp ); - s.save( map ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - map = (Map) s.get( "TestMap", (Serializable) map.get("id") ); - assertTrue( map != null && "foo".equals( map.get( "name" ) ) ); - assertTrue( map.get( "$type$" ).equals( "TestMap" ) ); - - int size = s.createCriteria("TestMap").add( Example.create(map) ).list().size(); - assertTrue( size == 1 ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - List list = s.createQuery("from TestMap").list(); - map = (Map) list.get(0); - assertTrue( "foo".equals( map.get("name") ) ); - assertTrue( "bar".equals( map.get("address") ) ); - cmp = (Map) map.get("cmp"); - assertTrue( new Integer( 1 ).equals( cmp.get( "a" ) ) && new Float( 1.0 ).equals( cmp.get( "b" ) ) ); - assertTrue( null == map.get( "parent" ) ); - map.put( "name", "foobar" ); - map.put( "parent", map ); - List bag = (List) map.get("children"); - bag.add( map ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - list = s.createQuery("from TestMap tm where tm.address = 'bar'").list(); - map = (Map) list.get(0); - assertTrue( "foobar".equals( map.get("name") ) ); - assertTrue( "bar".equals( map.get("address") ) ); - assertTrue( map==map.get("parent") ); - bag = (List) map.get("children"); - assertTrue( bag.size()==1 ); - - size = s.createCriteria("TestMap") - .add( Restrictions.eq("address", "bar") ) - .createCriteria("parent") - .add( Restrictions.eq("name", "foobar") ) - .list() - .size(); - assertTrue( size == 1 ); - - // for MySQL :( - map.put( "parent", null ); - map.put( "children", null ); - s.flush(); - s.delete(map); - s.getTransaction().commit(); - s.close(); - - } - - @Test - public void testMapOneToOne() throws Exception { - Map child = new HashMap(); - Map parent = new HashMap(); - Session s = openSession(); - s.beginTransaction(); - child.put("parent", parent); - child.put("$type$", "ChildMap"); - parent.put("child", child); - parent.put("$type$", "ParentMap"); - s.save(parent); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Map cm = (Map) s.createQuery("from ChildMap cm where cm.parent is not null").uniqueResult(); - s.delete(cm); - s.delete( cm.get("parent") ); - s.getTransaction().commit(); - s.close(); - - child = new HashMap(); - parent = new HashMap(); - s = openSession(); - s.beginTransaction(); - child.put("parent", parent); - child.put("$type$", "ChildMap"); - parent.put("child", child); - parent.put("$type$", "ParentMap"); - s.save(child); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Map pm = (Map) s.createQuery("from ParentMap cm where cm.child is not null").uniqueResult(); - s.delete(pm); - s.delete( pm.get("child") ); - s.getTransaction().commit(); - s.close(); - - } - - @Test - public void testOneToOnePropertyRef() throws Exception { - Session s = openSession(); - s.beginTransaction(); - s.createQuery("from Commento c where c.marelo.mlmag = 0").list(); - s.createQuery("from Commento c where c.marelo.commento.mcompr is null").list(); - s.createQuery("from Commento c where c.marelo.mlink = 0").list(); - s.createQuery("from Commento c where c.marelo.commento = c").list(); - s.createQuery("from Commento c where c.marelo.id.mlmag = 0").list(); - s.createQuery("from Commento c where c.marelo.commento.id = c.id").list(); - s.createQuery("from Commento c where c.marelo.commento.mclink = c.mclink").list(); - s.createQuery("from Marelo m where m.commento.id > 0").list(); - s.createQuery("from Marelo m where m.commento.marelo.commento.marelo.mlmag is not null").list(); - s.getTransaction().commit(); - s.close(); - } - -} - diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/MultiTableTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/MultiTableTest.java deleted file mode 100644 index 73043daa16..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/MultiTableTest.java +++ /dev/null @@ -1,729 +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 . - */ - -//$Id: MultiTableTest.java 10977 2006-12-12 23:28:04Z steve.ebersole@jboss.com $ -package org.hibernate.orm.test.legacy; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.io.Serializable; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import org.hibernate.FetchMode; -import org.hibernate.LockMode; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.criterion.Restrictions; -import org.hibernate.dialect.AbstractHANADialect; -import org.hibernate.dialect.CockroachDialect; -import org.hibernate.dialect.H2Dialect; -import org.hibernate.dialect.MySQLDialect; -import org.hibernate.engine.spi.SessionImplementor; -import org.hibernate.jdbc.Work; -import org.hibernate.testing.SkipForDialect; -import org.junit.Test; - - -public class MultiTableTest extends LegacyTestCase { - @Override - protected boolean isCleanupTestDataRequired() { - return true; - } - @Override - public String[] getMappings() { - return new String[] { "legacy/Multi.hbm.xml", "legacy/MultiExtends.hbm.xml" }; - } - - @Test - public void testCriteria() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Lower l = new Lower(); - s.save(l); - assertTrue( l==s.createCriteria(Top.class).uniqueResult() ); - s.delete(l); - s.flush(); - Criteria c = s.createCriteria(Lower.class); - c.createCriteria("yetanother") - .add( Restrictions.isNotNull("id") ) - .createCriteria("another"); - c.createCriteria("another").add( Restrictions.isNotNull("id") ); - c.list(); - t.commit(); - s.close(); - } - - @Test - public void testFetchOneToMany() throws Exception { - Session s = openSession(); - s.beginTransaction(); - s.createCriteria(Po.class).setFetchMode("set", FetchMode.JOIN).list(); - s.createCriteria(Po.class).setFetchMode("list", FetchMode.JOIN).list(); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testNarrow() throws Exception { - Session s = openSession(); - s.beginTransaction(); - s.createQuery("from Po po, Lower low where low.mypo = po").list(); - s.createQuery("from Po po join po.set as sm where sm.amount > 0").list(); - s.createQuery("from Po po join po.top as low where low.foo = 'po'").list(); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testJoins() throws Exception { - Session s = openSession(); - s.beginTransaction(); - s.createQuery( "from Lower l join l.yetanother l2 where lower(l2.name) > 'a'" ).list(); - s.createQuery( "from Lower l where lower(l.yetanother.top.name) > 'a'" ).list(); - s.createQuery( "from SubMulti sm join sm.children smc where smc.name > 'a'" ).list(); - s.createQuery( "select s, ya from Lower s join s.yetanother ya" ).list(); - s.createQuery( "from Lower s1 join s1.bag s2" ).list(); - s.createQuery( "from Lower s1 left join s1.bag s2" ).list(); - s.createQuery( "select s, a from Lower s join s.another a" ).list(); - s.createQuery( "select s, a from Lower s left join s.another a" ).list(); - s.createQuery( "from Top s, Lower ls" ).list(); - s.createQuery( "from Lower ls join ls.set s where s.name > 'a'" ).list(); - s.createQuery( "from Po po join po.list sm where sm.name > 'a'" ).list(); - s.createQuery( "from Lower ls inner join ls.another s where s.name is not null" ).list(); - s.createQuery( "from Lower ls where ls.other.another.name is not null" ).list(); - s.createQuery( "from Multi m where m.derived like 'F%'" ).list(); - s.createQuery( "from SubMulti m where m.derived like 'F%'" ).list(); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testSubclassCollection() throws Exception { - //if ( getDialect() instanceof HSQLDialect ) return; //TODO: figure out why!? - Session s = openSession(); - s.beginTransaction(); - SubMulti sm = new SubMulti(); - SubMulti sm1 = new SubMulti(); - SubMulti sm2 = new SubMulti(); - ArrayList list = new ArrayList(); - ArrayList anotherList = new ArrayList(); - sm.setChildren(list); - sm.setMoreChildren(anotherList); - sm.setExtraProp("foo"); - list.add(sm1); - list.add(sm2); - anotherList.add(sm1); - anotherList.add(sm2); - sm1.setParent(sm); - sm2.setParent(sm); - Serializable id = s.save(sm); - s.save(sm1); - s.save(sm2); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictEntityRegion(SubMulti.class); - - final Session s2 = openSession(); - s2.beginTransaction(); - s2.doWork( - new Work() { - @Override - public void execute(Connection connection) throws SQLException { - final String sql = "select * from leafsubsubclass sm, nonleafsubclass m, rootclass s " + - "where sm.sid=m.sid and sm.sid=s.id1_ and sm.sid=1"; - Statement st = ((SessionImplementor)s2).getJdbcCoordinator().getStatementPreparer().createStatement(); - ((SessionImplementor)session).getJdbcCoordinator().getResultSetReturn().extract( st, sql ).next(); - } - } - ); - assertTrue( - s2.createQuery( - "select s from SubMulti as sm join sm.children as s where s.amount>-1 and s.name is null" - ).list().size()==2 ); - s2.createQuery( "select c from SubMulti sm join sm.children c" ).list(); - assertTrue( s2.createQuery( "select elements(sm.children) from SubMulti as sm" ).list().size()==2 ); - assertTrue( - s2.createQuery( - "select distinct sm from SubMulti as sm join sm.children as s where s.amount>-1 and s.name is null" - ).list().size()==1 ); - sm = (SubMulti) s2.load(SubMulti.class, id); - assertTrue( sm.getChildren().size()==2 ); - assertEquals( - s2.createFilter( sm.getMoreChildren(), "select count(*) where this.amount>-1 and this.name is null" ).list().get(0), - new Long(2) - ); - assertEquals( "FOO", sm.getDerived() ); - assertSame( - s2.createQuery( "select distinct s from SubMulti s where s.moreChildren[1].amount < 1.0" ).iterate().next(), - sm - ); - assertTrue( sm.getMoreChildren().size()==2 ); - s2.delete(sm); - Iterator iter = sm.getChildren().iterator(); - while ( iter.hasNext() ) { - s2.delete( iter.next() ); - } - s2.flush(); - s2.getTransaction().commit(); - s2.close(); - - } - - @Test - public void testCollectionOnly() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Mono m = new Mono(); - Long id = (Long) s.save(m); - t.commit(); - s.close(); - s = openSession(); - t = s.beginTransaction(); - s.update( m ); - s.flush(); - m.setAddress("foo bar"); - s.flush(); - s.delete(m); - t.commit(); - s.close(); - } - - @Test - public void testQueries() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Long id = ( Long ) s.save( new TrivialClass() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - TrivialClass tc = (TrivialClass) s.load(TrivialClass.class, id); - s.createQuery( "from TrivialClass s where s.id = 2" ).list(); - s.createQuery( "select t.count from Top t" ).list(); - s.createQuery( "from Lower s where s.another.name='name'" ).list(); - s.createQuery( "from Lower s where s.yetanother.name='name'" ).list(); - s.createQuery( "from Lower s where s.yetanother.name='name' and s.yetanother.foo is null" ).list(); - s.createQuery( "from Top s where s.count=1" ).list(); - s.createQuery( "select s.count from Top s, Lower ls where ls.another=s" ).list(); - s.createQuery( "select elements(ls.bag), elements(ls.set) from Lower ls" ).list(); - s.createQuery( "from Lower" ).iterate(); - s.createQuery( "from Top" ).iterate(); - s.delete(tc); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testConstraints() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - SubMulti sm = new SubMulti(); - sm.setAmount(66.5f); - s.save( sm ); - t.commit(); - s.close(); - - s = openSession(); -// doDelete( s, "from SubMulti" ); -// t = s.beginTransaction(); - t = s.beginTransaction(); - doDelete( s, "from SubMulti" ); - t.commit(); - s.close(); - } - - @Test - @SkipForDialect( value = CockroachDialect.class ) - public void testMultiTable() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Multi multi = new Multi(); - multi.setExtraProp("extra"); - multi.setName("name"); - Top simp = new Top(); - simp.setDate( new Date() ); - simp.setName("simp"); - - Serializable mid = s.save(multi); - Serializable sid = s.save(simp); - - SubMulti sm = new SubMulti(); - sm.setAmount(66.5f); - Serializable smid = s.save(sm); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - multi.setExtraProp( multi.getExtraProp() + "2" ); - //multi.setCount( multi.getCount() + 1 ); - multi.setName("new name"); - s.update( multi ); - simp.setName("new name"); - s.update( simp ); - sm.setAmount(456.7f); - s.update( sm ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - multi = (Multi) s.load(Multi.class, mid); - assertTrue( multi.getExtraProp().equals("extra2") ); - multi.setExtraProp( multi.getExtraProp() + "3" ); - //multi.setCount( multi.getCount() + 1 ); - assertTrue( multi.getName().equals("new name") ); - multi.setName("newer name"); - sm = (SubMulti) s.load(SubMulti.class, smid); - assertTrue( sm.getAmount()==456.7f ); - sm.setAmount(23423f); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - multi = (Multi) s.load(Top.class, mid); - simp = (Top) s.load(Top.class, sid); - assertTrue( ! (simp instanceof Multi) ); - assertTrue( multi.getExtraProp().equals("extra23") ); - //multi.setCount( multi.getCount() + 1 ); - assertTrue( multi.getName().equals("newer name") ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Iterator iter = s.createQuery( "select\n\nt from Top t where t.count>0" ).iterate(); - boolean foundSimp = false; - boolean foundMulti = false; - boolean foundSubMulti = false; - while ( iter.hasNext() ) { - Object o = iter.next(); - if ( ( o instanceof Top ) && !( o instanceof Multi) ) foundSimp = true; - if ( o instanceof Multi && !(o instanceof SubMulti) ) foundMulti = true; - if ( o instanceof SubMulti ) foundSubMulti = true; - } - assertTrue( foundSimp&&foundMulti&&foundSubMulti ); - s.createQuery( "from Multi m where m.count>0 and m.extraProp is not null" ).list(); - s.createQuery( "from Top m where m.count>0 and m.name is not null" ).list(); - s.createQuery( "from Lower m where m.other is not null" ).list(); - s.createQuery( "from Multi m where m.other.id = 1" ).list(); - s.createQuery( "from SubMulti m where m.amount > 0.0" ).list(); - - assertTrue( - s.createQuery( "from Multi" ).list().size()==2 - ); - assertTrue( - s.createQuery( "from Multi m where m.class = SubMulti" ).list().size()==1 - ); - assertTrue( - s.createQuery( "from Top m where m.class = Multi" ).list().size()==1 - ); - assertTrue( - s.createQuery( "from Top" ).list().size()==3 - ); - assertTrue( - s.createQuery( "from Lower" ).list().size()==0 - ); - assertTrue( - s.createQuery( "from SubMulti" ).list().size()==1 - ); - - s.createQuery( "from Lower ls join ls.bag s where s.id is not null" ).list(); - s.createQuery( "from Lower ls join ls.set s where s.id is not null" ).list(); - if ( !(getDialect() instanceof MySQLDialect) ) - s.createQuery( "from SubMulti sm where exists elements(sm.children)" ).list(); - - List l = s.createCriteria(Top.class).list(); - assertTrue( l.size()==3 ); - assertTrue( s.createCriteria(SubMulti.class).list().size()==1 ); - assertTrue( - s.createCriteria(SubMulti.class) - .add( Restrictions.lt("amount", new Float(0)) ) - .list() - .size()==0 - ); - assertTrue( - s.createCriteria(SubMulti.class) - .add( Restrictions.ge("amount", new Float(0)) ) - .list() - .size()==1 - ); - - t.commit(); - s.close(); - - // HANA currently requires specifying table name by 'FOR UPDATE of t1.c1' - // if there are more than one tables/views/subqueries in the FROM clause - // H2 - Feature not supported: MVCC=TRUE && FOR UPDATE && JOIN - if ( !( getDialect() instanceof AbstractHANADialect || getDialect() instanceof H2Dialect ) ) { - s = openSession(); - t = s.beginTransaction(); - multi = (Multi) s.load( Top.class, mid, LockMode.UPGRADE ); - simp = (Top) s.load( Top.class, sid ); - s.lock( simp, LockMode.UPGRADE_NOWAIT ); - t.commit(); - s.close(); - } - - s = openSession(); - t = s.beginTransaction(); - s.update(multi); - s.delete(multi); - assertEquals( 2, doDelete( s, "from Top" ) ); - t.commit(); - s.close(); - - } - - @Test - @SkipForDialect( value = CockroachDialect.class ) - public void testMultiTableGeneratedId() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Multi multi = new Multi(); - multi.setExtraProp("extra"); - //multi.setCount(666); - multi.setName("name"); - Top simp = new Top(); - simp.setDate( new Date() ); - simp.setName("simp"); - //simp.setCount(132); - Serializable multiId = s.save( multi ); - Serializable simpId = s.save( simp ); - SubMulti sm = new SubMulti(); - sm.setAmount(66.5f); - Serializable smId = s.save( sm ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - multi.setExtraProp( multi.getExtraProp() + "2" ); - //multi.setCount( multi.getCount() + 1 ); - multi.setName("new name"); - s.update( multi ); - simp.setName("new name"); - s.update( simp ); - sm.setAmount(456.7f); - s.update( sm ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - multi = (Multi) s.load( Multi.class, multiId ); - assertTrue( multi.getExtraProp().equals("extra2") ); - multi.setExtraProp( multi.getExtraProp() + "3" ); - //multi.setCount( multi.getCount() + 1 ); - assertTrue( multi.getName().equals("new name") ); - multi.setName("newer name"); - sm = (SubMulti) s.load( SubMulti.class, smId ); - assertTrue( sm.getAmount()==456.7f ); - sm.setAmount(23423f); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - multi = (Multi) s.load( Top.class, multiId ); - simp = (Top) s.load( Top.class, simpId ); - assertTrue( ! (simp instanceof Multi) ); - assertTrue( multi.getExtraProp().equals("extra23") ); - //multi.setCount( multi.getCount() + 1 ); - assertTrue( multi.getName().equals("newer name") ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Iterator iter = s.createQuery( "select\n\nt from Top t where t.count>0" ).iterate(); - boolean foundSimp = false; - boolean foundMulti = false; - boolean foundSubMulti = false; - while ( iter.hasNext() ) { - Object o = iter.next(); - if ( ( o instanceof Top ) && !( o instanceof Multi) ) foundSimp = true; - if ( o instanceof Multi && !(o instanceof SubMulti) ) foundMulti = true; - if ( o instanceof SubMulti ) foundSubMulti = true; - } - assertTrue( foundSimp&&foundMulti&&foundSubMulti ); - s.createQuery( "from Multi m where m.count>0 and m.extraProp is not null" ).list(); - s.createQuery( "from Top m where m.count>0 and m.name is not null" ).list(); - s.createQuery( "from Lower m where m.other is not null" ).list(); - s.createQuery( "from Multi m where m.other.id = 1" ).list(); - s.createQuery( "from SubMulti m where m.amount > 0.0" ).list(); - - assertTrue( - s.createQuery( "from Multi" ).list().size()==2 - ); - /*assertTrue( - s.find("from m in class Multi where m.class = Multi").size()==1 - );*/ - assertTrue( - s.createQuery( "from Top" ).list().size()==3 - ); - assertTrue( - s.createQuery( "from Lower" ).list().size()==0 - ); - assertTrue( - s.createQuery( "from SubMulti" ).list().size()==1 - ); - - s.createQuery( "from Lower ls join ls.bag s where s.id is not null" ).list(); - if ( !(getDialect() instanceof MySQLDialect) ) - s.createQuery( "from SubMulti sm where exists elements(sm.children)" ).list(); - - t.commit(); - s.close(); - - // HANA currently requires specifying table name by 'FOR UPDATE of t1.c1' - // if there are more than one tables/views/subqueries in the FROM clause - // H2 - Feature not supported: MVCC=TRUE && FOR UPDATE && JOIN - if ( !( getDialect() instanceof AbstractHANADialect || getDialect() instanceof H2Dialect ) ) { - s = openSession(); - t = s.beginTransaction(); - multi = (Multi) s.load( Top.class, multiId, LockMode.UPGRADE ); - simp = (Top) s.load( Top.class, simpId ); - s.lock( simp, LockMode.UPGRADE_NOWAIT ); - t.commit(); - s.close(); - } - - s = openSession(); - t = s.beginTransaction(); - s.update( multi ); - s.delete(multi); - assertEquals( 2, doDelete( s, "from Top" ) ); - t.commit(); - s.close(); - - } - - @Test - @SkipForDialect(value = CockroachDialect.class, comment = "https://github.com/cockroachdb/cockroach/issues/27871") - public void testMultiTableCollections() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - assertTrue( s.createQuery( "from Top" ).list().size()==0 ); - Multi multi = new Multi(); - multi.setExtraProp("extra"); - multi.setName("name"); - Top simp = new Top(); - simp.setDate( new Date() ); - simp.setName("simp"); - - s.save(multi); - s.save(simp); - - Lower ls = new Lower(); - ls.setOther(ls); - ls.setAnother(ls); - ls.setYetanother(ls); - ls.setName("Less Simple"); - Set set = new HashSet(); - ls.setSet(set); - set.add(multi); - set.add(simp); - Serializable id = s.save(ls); - t.commit(); - s.close(); - assertTrue( ls.getOther()==ls && ls.getAnother()==ls && ls.getYetanother()==ls ); - - s = openSession(); - t = s.beginTransaction(); - ls = (Lower) s.load(Lower.class, id); - assertTrue( ls.getOther()==ls && ls.getAnother()==ls && ls.getYetanother()==ls ); - assertTrue( ls.getSet().size()==2 ); - Iterator iter = ls.getSet().iterator(); - int foundMulti = 0; - int foundSimple = 0; - while ( iter.hasNext() ) { - Object o = iter.next(); - if ( o instanceof Top ) foundSimple++; - if ( o instanceof Multi ) foundMulti++; - } - assertTrue( foundSimple == 2 && foundMulti == 1 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - try { - // MySQL does not like deleting rows that refer to itself without first - // null'ing out the FK. Ugh... - ls = s.load( Lower.class, id ); - ls.setOther( null ); - ls.setAnother( null ); - ls.setYetanother( null ); - for ( Object o : ls.getSet() ) { - s.delete( o ); - } - ls.getSet().clear(); - s.flush(); - s.delete( ls ); - t.commit(); - } - catch (Exception e) { - t.rollback(); - throw e; - } - finally { - s.close(); - } - } - - @Test - @SkipForDialect(value = CockroachDialect.class, comment = "https://github.com/cockroachdb/cockroach/issues/27871") - public void testMultiTableManyToOne() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - assertTrue( s.createQuery( "from Top" ).list().size() == 0 ); - Multi multi = new Multi(); - multi.setExtraProp( "extra" ); - multi.setName("name"); - s.save(multi); - Lower ls = new Lower(); - ls.setOther(ls); - ls.setAnother(multi); - ls.setYetanother(ls); - ls.setName("Less Simple"); - Serializable id = s.save(ls); - t.commit(); - s.close(); - assertTrue( ls.getOther()==ls && ls.getAnother()==multi && ls.getYetanother()==ls ); - - s = openSession(); - t = s.beginTransaction(); - try { - // MySQL does not like deleting rows that refer to itself without first - // null'ing out the FK. Ugh... - ls = s.load( Lower.class, id ); - assertTrue( ls.getOther() == ls && ls.getYetanother() == ls ); - assertTrue( ls.getAnother().getName().equals( "name" ) && ls.getAnother() instanceof Multi ); - s.delete( ls.getAnother() ); - ls.setOther( null ); - ls.setAnother( null ); - ls.setYetanother( null ); - ls.getSet().clear(); - s.flush(); - s.delete( ls ); - t.commit(); - } - catch (Exception e) { - t.rollback(); - throw e; - } - finally { - s.close(); - } - } - - @Test - public void testMultiTableNativeId() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Multi multi = new Multi(); - multi.setExtraProp("extra"); - Long id = (Long) s.save(multi); - assertTrue( id!=null ); - s.delete(multi); - t.commit(); - s.close(); - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testCollection() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Multi multi1 = new Multi(); - multi1.setExtraProp("extra1"); - Multi multi2 = new Multi(); - multi2.setExtraProp("extra2"); - Po po = new Po(); - multi1.setPo(po); multi2.setPo(po); - po.setSet( new HashSet() ); - po.getSet().add(multi1); - po.getSet().add(multi2); - po.setList( new ArrayList() ); - //po.getList().add(null); - po.getList().add( new SubMulti() ); - Serializable id = s.save(po); - assertTrue( id!=null ); - t.commit(); - s.close(); - s = openSession(); - t = s.beginTransaction(); - po = (Po) s.load(Po.class, id); - assertTrue( po.getSet().size()==2 ); - assertTrue( po.getList().size()==1 ); - s.delete(po); - assertTrue( s.createQuery( "from Top" ).list().size()==0 ); - t.commit(); - s.close(); - } - - @Test - public void testOneToOne() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Lower ls = new Lower(); - Serializable id = s.save(ls); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.load(Lower.class, id); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.delete( s.load(Lower.class, id) ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testCollectionPointer() throws Exception { - Session sess = openSession(); - sess.beginTransaction(); - Lower ls = new Lower(); - List list = new ArrayList(); - ls.setBag(list); - Top s = new Top(); - Serializable id = sess.save(ls); - sess.save(s); - sess.flush(); - list.add(s); - sess.getTransaction().commit(); - sess.close(); - - sess = openSession(); - sess.beginTransaction(); - ls = (Lower) sess.load(Lower.class, id); - assertTrue( ls.getBag().size()==1 ); - doDelete( sess, "from java.lang.Object" ); - sess.getTransaction().commit(); - sess.close(); - } - -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/OneToOneCacheTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/OneToOneCacheTest.java deleted file mode 100644 index b345148600..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/OneToOneCacheTest.java +++ /dev/null @@ -1,119 +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 . - */ -package org.hibernate.orm.test.legacy; - -import java.io.Serializable; - -import org.hibernate.HibernateException; -import org.hibernate.Session; -import org.hibernate.Transaction; - -import org.junit.Test; - -import static org.junit.Assert.assertNotNull; - -/** - * Simple testcase to illustrate HB-992 - * - * @author Wolfgang Voelkl, michael - */ -public class OneToOneCacheTest extends LegacyTestCase { - private Serializable generatedId; - - @Override - public String[] getMappings() { - return new String[] { "legacy/Object2.hbm.xml", "legacy/MainObject.hbm.xml" }; - } - - @Test - public void testOneToOneCache() throws HibernateException { - - //create a new MainObject - createMainObject(); - // load the MainObject - readMainObject(); - - //create and add Ojbect2 - addObject2(); - - //here the newly created Object2 is written to the database - //but the MainObject does not know it yet - MainObject mainObject = readMainObject(); - - assertNotNull( mainObject.getObj2() ); - - // after evicting, it works. - sessionFactory().getCache().evictEntityRegion( MainObject.class ); - - mainObject = readMainObject(); - - assertNotNull( mainObject.getObj2() ); - - } - - /** - * creates a new MainObject - *

- * one hibernate transaction ! - */ - private void createMainObject() throws HibernateException { - Session session = openSession(); - Transaction tx = session.beginTransaction(); - - MainObject mo = new MainObject(); - mo.setDescription( "Main Test" ); - - generatedId = session.save( mo ); - - tx.commit(); - session.close(); - } - - /** - * loads the newly created MainObject - * and adds a new Object2 to it - *

- * one hibernate transaction - */ - private void addObject2() throws HibernateException { - Session session = openSession(); - Transaction tx = session.beginTransaction(); - - MainObject mo = - ( MainObject ) session.load( MainObject.class, generatedId ); - - Object2 toAdd = new Object2(); - toAdd.setDummy( "test" ); - - //toAdd should now be saved by cascade - mo.setObj2( toAdd ); - - tx.commit(); - session.close(); - } - - /** - * reads the newly created MainObject - * and its Object2 if it exists - *

- * one hibernate transaction - */ - private MainObject readMainObject() throws HibernateException { - Long returnId = null; - Session session = openSession(); - Transaction tx = session.beginTransaction(); - - Serializable id = generatedId; - - MainObject mo = ( MainObject ) session.get( MainObject.class, id ); - - tx.commit(); - session.close(); - - return mo; - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/ParentChildTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/ParentChildTest.java deleted file mode 100644 index 2f4b9dfc6b..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/ParentChildTest.java +++ /dev/null @@ -1,1269 +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 . - */ -package org.hibernate.orm.test.legacy; - -import java.io.Serializable; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.hibernate.testing.DialectChecks; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.SkipForDialect; -import org.junit.Test; - -import org.hibernate.FetchMode; -import org.hibernate.Hibernate; -import org.hibernate.HibernateException; -import org.hibernate.LockMode; -import org.hibernate.LockOptions; -import org.hibernate.ObjectNotFoundException; -import org.hibernate.ReplicationMode; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.criterion.Restrictions; -import org.hibernate.dialect.AbstractHANADialect; -import org.hibernate.dialect.H2Dialect; -import org.hibernate.dialect.HSQLDialect; -import org.hibernate.dialect.IngresDialect; -import org.hibernate.dialect.MySQLDialect; -import org.hibernate.dialect.TeradataDialect; -import org.hibernate.dialect.CockroachDialect; -import org.hibernate.engine.spi.EntityEntry; -import org.hibernate.internal.SessionImpl; -import org.hibernate.jdbc.AbstractWork; -import org.hibernate.proxy.HibernateProxy; -import org.hibernate.testing.FailureExpected; -import org.hibernate.type.StandardBasicTypes; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -@RequiresDialectFeature(DialectChecks.SupportsNoColumnInsert.class) -public class ParentChildTest extends LegacyTestCase { - @Override - public String[] getMappings() { - return new String[] { - "legacy/ParentChild.hbm.xml", - "legacy/FooBar.hbm.xml", - "legacy/Baz.hbm.xml", - "legacy/Qux.hbm.xml", - "legacy/Glarch.hbm.xml", - "legacy/Fum.hbm.xml", - "legacy/Fumm.hbm.xml", - "legacy/Fo.hbm.xml", - "legacy/One.hbm.xml", - "legacy/Many.hbm.xml", - "legacy/Immutable.hbm.xml", - "legacy/Fee.hbm.xml", - "legacy/Vetoer.hbm.xml", - "legacy/Holder.hbm.xml", - "legacy/Simple.hbm.xml", - "legacy/Container.hbm.xml", - "legacy/Circular.hbm.xml", - "legacy/Stuff.hbm.xml" - }; - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testReplicate() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Container baz = new Container(); - Contained f = new Contained(); - List list = new ArrayList(); - list.add(baz); - f.setBag(list); - List list2 = new ArrayList(); - list2.add(f); - baz.setBag(list2); - s.save(f); - s.save(baz); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.replicate(baz, ReplicationMode.OVERWRITE); - // HHH-2378 - SessionImpl x = (SessionImpl)s; - EntityEntry entry = x.getPersistenceContext().getEntry( baz ); - assertNull(entry.getVersion()); - // ~~~~~~~ - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.replicate(baz, ReplicationMode.IGNORE); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.delete(baz); - s.delete(f); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testQueryOneToOne() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Serializable id = s.save( new Parent() ); - assertTrue( s.createQuery( "from Parent p left join fetch p.child" ).list().size()==1 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Parent p = (Parent) s.createQuery("from Parent p left join fetch p.child").uniqueResult(); - assertTrue( p.getChild()==null ); - s.createQuery( "from Parent p join p.child c where c.x > 0" ).list(); - s.createQuery( "from Child c join c.parent p where p.x > 0" ).list(); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - s.delete( s.get(Parent.class, id) ); - t.commit(); - s.close(); - } - - @Test - @FailureExpected( jiraKey = "unknown" ) - public void testProxyReuse() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - FooProxy foo = new Foo(); - FooProxy foo2 = new Foo(); - Serializable id = s.save(foo); - Serializable id2 = s.save(foo2); - foo2.setInt( 1234567 ); - foo.setInt(1234); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - foo = (FooProxy) s.load(Foo.class, id); - foo2 = (FooProxy) s.load(Foo.class, id2); - assertFalse( Hibernate.isInitialized( foo ) ); - Hibernate.initialize( foo2 ); - Hibernate.initialize(foo); - assertTrue( foo.getComponent().getImportantDates().length==4 ); - assertTrue( foo2.getComponent().getImportantDates().length == 4 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - foo.setKey( "xyzid" ); - foo.setFloat( new Float( 1.2f ) ); - foo2.setKey( (String) id ); //intentionally id, not id2! - foo2.setFloat( new Float( 1.3f ) ); - foo2.getDependent().setKey( null ); - foo2.getComponent().getSubcomponent().getFee().setKey(null); - assertFalse( foo2.getKey().equals( id ) ); - s.save( foo ); - s.update( foo2 ); - assertEquals( foo2.getKey(), id ); - assertTrue( foo2.getInt() == 1234567 ); - assertEquals( foo.getKey(), "xyzid" ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - foo = (FooProxy) s.load(Foo.class, id); - assertTrue( foo.getInt() == 1234567 ); - assertTrue( foo.getComponent().getImportantDates().length==4 ); - String feekey = foo.getDependent().getKey(); - String fookey = foo.getKey(); - s.delete( foo ); - s.delete( s.get(Foo.class, id2) ); - s.delete( s.get(Foo.class, "xyzid") ); -// here is the issue (HHH-4092). After the deletes above there are 2 Fees and a Glarch unexpectedly hanging around - assertEquals( 2, doDelete( s, "from java.lang.Object" ) ); - t.commit(); - s.close(); - - //to account for new id rollback shit - foo.setKey(fookey); - foo.getDependent().setKey( feekey ); - foo.getComponent().setGlarch( null ); - foo.getComponent().setSubcomponent(null); - - s = openSession(); - t = s.beginTransaction(); - //foo.getComponent().setGlarch(null); //no id property! - s.replicate( foo, ReplicationMode.OVERWRITE ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Foo refoo = (Foo) s.get(Foo.class, id); - assertEquals( feekey, refoo.getDependent().getKey() ); - s.delete(refoo); - t.commit(); - s.close(); - } - - @Test - @SkipForDialect( value = H2Dialect.class, comment = "Feature not supported: MVCC=TRUE && FOR UPDATE && JOIN") - public void testComplexCriteria() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Baz baz = new Baz(); - s.save(baz); - baz.setDefaults(); - Map topGlarchez = new HashMap(); - baz.setTopGlarchez(topGlarchez); - Glarch g1 = new Glarch(); - g1.setName("g1"); - s.save(g1); - Glarch g2 = new Glarch(); - g2.setName("g2"); - s.save(g2); - g1.setProxyArray( new GlarchProxy[] {g2} ); - topGlarchez.put( new Character('1'),g1 ); - topGlarchez.put( new Character('2'), g2); - Foo foo1 = new Foo(); - Foo foo2 = new Foo(); - s.save(foo1); - s.save(foo2); - baz.getFooSet().add(foo1); - baz.getFooSet().add(foo2); - baz.setFooArray( new FooProxy[] { foo1 } ); - - LockMode lockMode = supportsLockingNullableSideOfJoin( getDialect() ) ? LockMode.UPGRADE : LockMode.READ; - - Criteria crit = s.createCriteria(Baz.class); - crit.createCriteria("topGlarchez") - .add( Restrictions.isNotNull("name") ) - .createCriteria("proxyArray") - .add( Restrictions.eqProperty("name", "name") ) - .add( Restrictions.eq("name", "g2") ) - .add( Restrictions.gt("x", new Integer(-666) ) ); - crit.createCriteria("fooSet") - .add( Restrictions.isNull("null") ) - .add( Restrictions.eq("string", "a string") ) - .add( Restrictions.lt("integer", new Integer(-665) ) ); - crit.createCriteria("fooArray") - // this is the bit causing the problems; creating the criteria on fooArray does not add it to FROM, - // and so restriction below leads to an invalid reference. - .add( Restrictions.eq("string", "a string") ) - .setLockMode(lockMode); - - List list = crit.list(); - assertTrue( list.size()==2 ); - - s.createCriteria(Glarch.class).setLockMode(LockMode.UPGRADE).list(); - s.createCriteria(Glarch.class).setLockMode(Criteria.ROOT_ALIAS, LockMode.UPGRADE).list(); - - g2.setName(null); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - - list = s.createCriteria(Baz.class).add( Restrictions.isEmpty("fooSet") ).list(); - assertEquals( list.size(), 0 ); - - list = s.createCriteria(Baz.class).add( Restrictions.isNotEmpty("fooSet") ).list(); - assertEquals( new HashSet(list).size(), 1 ); - - list = s.createCriteria(Baz.class).add( Restrictions.sizeEq("fooSet", 2) ).list(); - assertEquals( new HashSet(list).size(), 1 ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - - crit = s.createCriteria(Baz.class) - .setLockMode(lockMode); - crit.createCriteria("topGlarchez") - .add( Restrictions.gt( "x", new Integer(-666) ) ); - crit.createCriteria("fooSet") - .add( Restrictions.isNull("null") ); - list = crit.list(); - - assertTrue( list.size()==4 ); - baz = (Baz) crit.uniqueResult(); - assertTrue( Hibernate.isInitialized(baz.getTopGlarchez()) ); //cos it is nonlazy - assertTrue( !Hibernate.isInitialized(baz.getFooSet()) ); - - list = s.createCriteria(Baz.class) - .createCriteria("fooSet") - .createCriteria("foo") - .createCriteria("component.glarch") - .add( Restrictions.eq("name", "xxx") ) - .list(); - assertTrue( list.size()==0 ); - - list = s.createCriteria(Baz.class) - .createAlias("fooSet", "foo") - .createAlias("foo.foo", "foo2") - .setLockMode("foo2", lockMode) - .add( Restrictions.isNull("foo2.component.glarch") ) - .createCriteria("foo2.component.glarch") - .add( Restrictions.eq("name", "xxx") ) - .list(); - assertTrue( list.size()==0 ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - - crit = s.createCriteria(Baz.class); - crit.createCriteria("topGlarchez") - .add( Restrictions.isNotNull("name") ); - crit.createCriteria("fooSet") - .add( Restrictions.isNull("null") ); - - list = crit.list(); - assertTrue( list.size()==2 ); - baz = (Baz) crit.uniqueResult(); - assertTrue( Hibernate.isInitialized(baz.getTopGlarchez()) ); //cos it is nonlazy - assertTrue( !Hibernate.isInitialized(baz.getFooSet()) ); - - s.createCriteria(Child.class).setFetchMode("parent", FetchMode.JOIN).list(); - - doDelete( s, "from Glarch g" ); - s.delete( s.get(Foo.class, foo1.getKey() ) ); - s.delete( s.get(Foo.class, foo2.getKey() ) ); - s.delete(baz); - t.commit(); - s.close(); - } - - @Test - public void testArrayHQL() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Baz baz = new Baz(); - s.save(baz); - Foo foo1 = new Foo(); - s.save(foo1); - baz.setFooArray( new FooProxy[] { foo1 } ); - - s.flush(); - s.clear(); - - baz = ( Baz ) s.createQuery("from Baz b left join fetch b.fooArray").uniqueResult(); - assertEquals( 1, baz.getFooArray().length ); - - t.rollback(); - s.close(); - } - - @Test - public void testArrayCriteria() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Baz baz = new Baz(); - s.save(baz); - Foo foo1 = new Foo(); - s.save(foo1); - baz.setFooArray( new FooProxy[] { foo1 } ); - - s.flush(); - s.clear(); - - baz = ( Baz ) s.createCriteria(Baz.class).createCriteria( "fooArray" ).uniqueResult(); - assertEquals( 1, baz.getFooArray().length ); - - t.rollback(); - s.close(); - } - - @Test - public void testLazyManyToOneHQL() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Baz baz = new Baz(); - s.save(baz); - Foo foo1 = new Foo(); - s.save(foo1); - baz.setFoo( foo1 ); - - s.flush(); - s.clear(); - - baz = ( Baz ) s.createQuery("from Baz b").uniqueResult(); - assertFalse( Hibernate.isInitialized( baz.getFoo() ) ); - assertTrue( baz.getFoo() instanceof HibernateProxy ); - - t.rollback(); - s.close(); - } - - @Test - public void testLazyManyToOneCriteria() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Baz baz = new Baz(); - s.save(baz); - Foo foo1 = new Foo(); - s.save(foo1); - baz.setFoo( foo1 ); - - s.flush(); - s.clear(); - - baz = ( Baz ) s.createCriteria( Baz.class ).uniqueResult(); - assertTrue( Hibernate.isInitialized( baz.getFoo() ) ); - assertFalse( baz.getFoo() instanceof HibernateProxy ); - - t.rollback(); - s.close(); - } - - @Test - public void testLazyManyToOneGet() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Baz baz = new Baz(); - s.save(baz); - Foo foo1 = new Foo(); - s.save(foo1); - baz.setFoo( foo1 ); - - s.flush(); - s.clear(); - - baz = ( Baz ) s.get( Baz.class, baz.getCode() ); - assertTrue( Hibernate.isInitialized( baz.getFoo() ) ); - assertFalse( baz.getFoo() instanceof HibernateProxy ); - - t.rollback(); - s.close(); - } - - @Test - public void testClassWhere() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Baz baz = new Baz(); - baz.setParts( new ArrayList() ); - Part p1 = new Part(); - p1.setDescription("xyz"); - Part p2 = new Part(); - p2.setDescription("abc"); - baz.getParts().add(p1); - baz.getParts().add(p2); - s.save(baz); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - assertTrue( s.createCriteria(Part.class).list().size()==1 ); //there is a where condition on Part mapping - assertTrue( s.createCriteria(Part.class).add( Restrictions.eq( "id", p1.getId() ) ).list().size()==1 ); - assertTrue( s.createQuery("from Part").list().size()==1 ); - // only Part entities that satisfy the where condition on Part mapping should be included in the collection - assertTrue( s.createQuery("from Baz baz join baz.parts").list().size()==1 ); - baz = (Baz) s.createCriteria(Baz.class).uniqueResult(); - // only Part entities that satisfy the where condition on Part mapping should be included in the collection - assertTrue( s.createFilter( baz.getParts(), "" ).list().size()==1 ); - //assertTrue( baz.getParts().size()==1 ); - s.delete( s.get( Part.class, p1.getId() ) ); - // p2.description does not satisfy the condition on Part mapping, so it's not possible to retrieve it - // using Session#get; instead just delete using a native query - s.createNativeQuery( "delete from Part where id = :id" ).setParameter( "id", p2.getId() ).executeUpdate(); - s.delete(baz); - t.commit(); - s.close(); - } - - @Test - public void testClassWhereManyToMany() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Baz baz = new Baz(); - baz.setMoreParts( new ArrayList() ); - Part p1 = new Part(); - p1.setDescription("xyz"); - Part p2 = new Part(); - p2.setDescription("abc"); - baz.getMoreParts().add(p1); - baz.getMoreParts().add(p2); - s.save(baz); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - assertTrue( s.createCriteria(Part.class).list().size()==1 ); //there is a where condition on Part mapping - assertTrue( s.createCriteria(Part.class).add( Restrictions.eq( "id", p1.getId() ) ).list().size()==1 ); - assertTrue( s.createQuery("from Part").list().size()==1 ); - // only Part entities that satisfy the where condition on Part mapping should be included in the collection - assertTrue( s.createQuery("from Baz baz join baz.moreParts").list().size()==1 ); - baz = (Baz) s.createCriteria(Baz.class).uniqueResult(); - // only Part entities that satisfy the where condition on Part mapping should be included in the collection - assertTrue( s.createFilter( baz.getMoreParts(), "" ).list().size()==1 ); - //assertTrue( baz.getParts().size()==1 ); - s.delete( s.get( Part.class, p1.getId() )); - // p2.description does not satisfy the condition on Part mapping, so it's not possible to retrieve it - // using Session#get; instead just delete using a native query - s.createNativeQuery( "delete from baz_moreParts where baz = :baz AND part = :part" ) - .setParameter( "baz", baz.getCode() ) - .setParameter( "part", p2.getId() ) - .executeUpdate(); - s.createNativeQuery( "delete from Part where id = :id" ).setParameter( "id", p2.getId() ).executeUpdate(); - s.delete(baz); - t.commit(); - s.close(); - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testCollectionQuery() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Simple s1 = new Simple( Long.valueOf(1) ); - s1.setName("s"); - s1.setCount(0); - Simple s2 = new Simple( Long.valueOf(2) ); - s2.setCount(2); - Simple s3 = new Simple( Long.valueOf(3) ); - s3.setCount(3); - s.save( s1 ); - s.save( s2 ); - s.save( s3 ); - Container c = new Container(); - Contained cd = new Contained(); - List bag = new ArrayList(); - bag.add(cd); - c.setBag(bag); - List l = new ArrayList(); - l.add(s1); - l.add(s3); - l.add(s2); - c.setOneToMany(l); - l = new ArrayList(); - l.add(s1); - l.add(null); - l.add(s2); - c.setManyToMany(l); - s.save(c); - Container cx = new Container(); - s.save(cx); - Simple sx = new Simple( Long.valueOf(5) ); - sx.setCount(5); - sx.setName("s"); - s.save( sx ); - assertTrue( - s.createQuery( "select c from ContainerX c, Simple s where c.oneToMany[2] = s" ).list() - .size() == 1 - ); - assertTrue( - s.createQuery( "select c from ContainerX c, Simple s where c.manyToMany[2] = s" ).list() - .size() == 1 - ); - assertTrue( - s.createQuery( "select c from ContainerX c, Simple s where s = c.oneToMany[2]" ).list() - .size() == 1 - ); - assertTrue( - s.createQuery( "select c from ContainerX c, Simple s where s = c.manyToMany[2]" ).list() - .size() == 1 - ); - assertTrue( - s.createQuery( "select c from ContainerX c where c.oneToMany[0].name = 's'" ).list() - .size() == 1 - ); - assertTrue( - s.createQuery( "select c from ContainerX c where c.manyToMany[0].name = 's'" ).list() - .size() == 1 - ); - assertTrue( - s.createQuery( "select c from ContainerX c where 's' = c.oneToMany[2 - 2].name" ).list() - .size() == 1 - ); - assertTrue( - s.createQuery( "select c from ContainerX c where 's' = c.manyToMany[(3+1)/4-1].name" ).list() - .size() == 1 - ); - assertTrue( - s.createQuery( "select c from ContainerX c where c.oneToMany[ c.manyToMany[0].count ].name = 's'" ) - .list() - .size() == 1 - ); - assertTrue( - s.createQuery( "select c from ContainerX c where c.manyToMany[ c.oneToMany[0].count ].name = 's'" ) - .list() - .size() == 1 - ); - if ( ! ( getDialect() instanceof MySQLDialect ) && !(getDialect() instanceof org.hibernate.dialect.TimesTenDialect) ) { - assertTrue( - s.createQuery( "select c from ContainerX c where c.manyToMany[ maxindex(c.manyToMany) ].count = 2" ) - .list() - .size() == 1 - ); - } - assertTrue( s.contains(cd) ); - if ( !(getDialect() instanceof MySQLDialect) && !(getDialect() instanceof HSQLDialect) ) { - s.createFilter( c.getBag(), "where 0 in elements(this.bag)" ).list(); - s.createFilter( c.getBag(), "where 0 in elements(this.lazyBag)" ).list(); - } - s.createQuery( "select count(comp.name) from ContainerX c join c.components comp" ).list(); - s.delete(cd); - s.delete(c); - s.delete(s1); - s.delete(s2); - s.delete(s3); - s.delete(cx); - s.delete(sx); - t.commit(); - s.close(); - } - - @Test - public void testParentChild() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Parent p = new Parent(); - Child c = new Child(); - c.setParent(p); - p.setChild(c); - s.save(p); - s.save(c); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Child) s.load( Child.class, new Long( c.getId() ) ); - p = c.getParent(); - assertTrue( "1-1 parent", p!=null ); - c.setCount(32); - p.setCount(66); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Child) s.load( Child.class, new Long( c.getId() ) ); - p = c.getParent(); - assertTrue( "1-1 update", p.getCount()==66 ); - assertTrue( "1-1 update", c.getCount()==32 ); - assertTrue( - "1-1 query", - s.createQuery( "from Child c where c.parent.count=66" ).list().size()==1 - ); - assertTrue( - "1-1 query", - ( (Object[]) s.createQuery( "from Parent p join p.child c where p.count=66" ).list().get(0) ).length==2 - ); - s.createQuery( "select c, c.parent from Child c order by c.parent.count" ).list(); - s.createQuery( "select c, c.parent from Child c where c.parent.count=66 order by c.parent.count" ).list(); - s.createQuery( "select c, c.parent, c.parent.count from Child c order by c.parent.count" ).iterate(); - List result = s.createQuery( "FROM Parent AS p WHERE p.count = ?" ) - .setParameter( 0, new Integer(66), StandardBasicTypes.INTEGER ) - .list(); - assertEquals( "1-1 query", 1, result.size() ); - s.delete(c); s.delete(p); - t.commit(); - s.close(); - } - - @Test - public void testParentNullChild() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Parent p = new Parent(); - s.save(p); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - p = (Parent) s.load( Parent.class, new Long( p.getId() ) ); - assertTrue( p.getChild()==null ); - p.setCount(66); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - p = (Parent) s.load( Parent.class, new Long( p.getId() ) ); - assertTrue( "null 1-1 update", p.getCount()==66 ); - assertTrue( p.getChild()==null ); - s.delete(p); - t.commit(); - s.close(); - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testManyToMany() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Container c = new Container(); - c.setManyToMany( new ArrayList() ); - c.setBag( new ArrayList() ); - Simple s1 = new Simple( Long.valueOf(12) ); - Simple s2 = new Simple( Long.valueOf(-1) ); - s1.setCount(123); s2.setCount(654); - Contained c1 = new Contained(); - c1.setBag( new ArrayList() ); - c1.getBag().add(c); - c.getBag().add(c1); - c.getManyToMany().add(s1); - c.getManyToMany().add(s2); - Serializable cid = s.save(c); - s.save( s1 ); - s.save( s2 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Container) s.load(Container.class, cid); - assertTrue( c.getBag().size()==1 ); - assertTrue( c.getManyToMany().size()==2 ); - c1 = (Contained) c.getBag().iterator().next(); - assertTrue( c.getBag().size()==1 ); - c.getBag().remove(c1); - c1.getBag().remove(c); - assertTrue( c.getManyToMany().remove(0)!=null ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Container) s.load(Container.class, cid); - assertTrue( c.getBag().size()==0 ); - assertTrue( c.getManyToMany().size()==1 ); - c1 = (Contained) s.load( Contained.class, new Long(c1.getId()) ); - assertTrue( c1.getBag().size()==0 ); - assertEquals( 1, doDelete( s, "from ContainerX c" ) ); - assertEquals( 1, doDelete( s, "from Contained" ) ); - assertEquals( 2, doDelete( s, "from Simple" ) ); - t.commit(); - s.close(); - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testContainer() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Container c = new Container(); - Simple x = new Simple( Long.valueOf(1) ); - x.setCount(123); - Simple y = new Simple( Long.valueOf(0) ); - y.setCount(456); - s.save( x ); - s.save( y ); - List o2m = new ArrayList(); - o2m.add(x); o2m.add(null); o2m.add(y); - List m2m = new ArrayList(); - m2m.add(x); m2m.add(null); m2m.add(y); - c.setOneToMany(o2m); c.setManyToMany(m2m); - List comps = new ArrayList(); - Container.ContainerInnerClass ccic = new Container.ContainerInnerClass(); - ccic.setName("foo"); - ccic.setSimple(x); - comps.add(ccic); - comps.add(null); - ccic = new Container.ContainerInnerClass(); - ccic.setName("bar"); - ccic.setSimple(y); - comps.add(ccic); - HashSet compos = new HashSet(); - compos.add(ccic); - c.setComposites(compos); - c.setComponents(comps); - One one = new One(); - Many many = new Many(); - HashSet manies = new HashSet(); - manies.add(many); - one.setManies(manies); - many.setOne(one); - ccic.setMany(many); - ccic.setOne(one); - s.save(one); - s.save(many); - s.save(c); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Long count = (Long) s.createQuery("select count(*) from ContainerX as c join c.components as ce join ce.simple as s where ce.name='foo'").uniqueResult(); - assertTrue( count.intValue()==1 ); - List res = s.createQuery( - "select c, s from ContainerX as c join c.components as ce join ce.simple as s where ce.name='foo'" - ).list(); - assertTrue(res.size()==1); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Container) s.load( Container.class, new Long( c.getId() ) ); - System.out.println( c.getOneToMany() ); - System.out.println( c.getManyToMany() ); - System.out.println( c.getComponents() ); - System.out.println( c.getComposites() ); - ccic = (Container.ContainerInnerClass) c.getComponents().get(2); - assertTrue( ccic.getMany().getOne()==ccic.getOne() ); - assertTrue( c.getComponents().size()==3 ); - assertTrue( c.getComposites().size()==1 ); - assertTrue( c.getOneToMany().size()==3 ); - assertTrue( c.getManyToMany().size()==3 ); - assertTrue( c.getOneToMany().get(0)!=null ); - assertTrue( c.getOneToMany().get(2)!=null ); - for ( int i=0; i<3; i++ ) { - assertTrue( c.getManyToMany().get(i) == c.getOneToMany().get(i) ); - } - Object o1 = c.getOneToMany().get(0); - Object o2 = c.getOneToMany().remove(2); - c.getOneToMany().set(0, o2); - c.getOneToMany().set(1, o1); - o1 = c.getComponents().remove(2); - c.getComponents().set(0, o1); - c.getManyToMany().set( 0, c.getManyToMany().get(2) ); - Container.ContainerInnerClass ccic2 = new Container.ContainerInnerClass(); - ccic2.setName("foo"); - ccic2.setOne(one); - ccic2.setMany(many); - ccic2.setSimple( (Simple) s.load(Simple.class, new Long(0) ) ); - c.getComposites().add(ccic2); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Container) s.load( Container.class, new Long( c.getId() ) ); - System.out.println( c.getOneToMany() ); - System.out.println( c.getManyToMany() ); - System.out.println( c.getComponents() ); - System.out.println( c.getComposites() ); - assertTrue( c.getComponents().size()==1 ); //WAS: 2 - assertTrue( c.getComposites().size()==2 ); - assertTrue( c.getOneToMany().size()==2 ); - assertTrue( c.getManyToMany().size()==3 ); - assertTrue( c.getOneToMany().get(0)!=null ); - assertTrue( c.getOneToMany().get(1)!=null ); - ( (Container.ContainerInnerClass) c.getComponents().get(0) ).setName("a different name"); - ( (Container.ContainerInnerClass) c.getComposites().iterator().next() ).setName("once again"); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Container) s.load( Container.class, new Long( c.getId() ) ); - System.out.println( c.getOneToMany() ); - System.out.println( c.getManyToMany() ); - System.out.println( c.getComponents() ); - System.out.println( c.getComposites() ); - assertTrue( c.getComponents().size()==1 ); //WAS: 2 - assertTrue( c.getComposites().size()==2 ); - assertTrue( ( (Container.ContainerInnerClass) c.getComponents().get(0) ).getName().equals("a different name") ); - Iterator iter = c.getComposites().iterator(); - boolean found = false; - while ( iter.hasNext() ) { - if ( ( (Container.ContainerInnerClass) iter.next() ).getName().equals("once again") ) found = true; - } - assertTrue(found); - c.getOneToMany().clear(); - c.getManyToMany().clear(); - c.getComposites().clear(); - c.getComponents().clear(); - doDelete( s, "from Simple" ); - doDelete( s, "from Many" ); - doDelete( s, "from One" ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Container) s.load( Container.class, new Long( c.getId() ) ); - assertTrue( c.getComponents().size()==0 ); - assertTrue( c.getComposites().size()==0 ); - assertTrue( c.getOneToMany().size()==0 ); - assertTrue( c.getManyToMany().size()==0 ); - s.delete(c); - t.commit(); - s.close(); - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testCascadeCompositeElements() throws Exception { - Container c = new Container(); - List list = new ArrayList(); - c.setCascades(list); - Container.ContainerInnerClass cic = new Container.ContainerInnerClass(); - cic.setMany( new Many() ); - cic.setOne( new One() ); - list.add(cic); - Session s = openSession(); - s.beginTransaction(); - s.save(c); - s.getTransaction().commit(); - s.close(); - - s=openSession(); - s.beginTransaction(); - c = (Container) s.createQuery( "from ContainerX c" ).iterate().next(); - cic = (Container.ContainerInnerClass) c.getCascades().iterator().next(); - assertTrue( cic.getMany()!=null && cic.getOne()!=null ); - assertTrue( c.getCascades().size()==1 ); - s.delete(c); - s.getTransaction().commit(); - s.close(); - - c = new Container(); - s = openSession(); - s.beginTransaction(); - s.save(c); - list = new ArrayList(); - c.setCascades(list); - cic = new Container.ContainerInnerClass(); - cic.setMany( new Many() ); - cic.setOne( new One() ); - list.add(cic); - s.getTransaction().commit(); - s.close(); - - s=openSession(); - s.beginTransaction(); - c = (Container) s.createQuery( "from ContainerX c" ).iterate().next(); - cic = (Container.ContainerInnerClass) c.getCascades().iterator().next(); - assertTrue( cic.getMany()!=null && cic.getOne()!=null ); - assertTrue( c.getCascades().size()==1 ); - s.delete(c); - s.getTransaction().commit(); - s.close(); - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testBag() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Container c = new Container(); - Contained c1 = new Contained(); - Contained c2 = new Contained(); - c.setBag( new ArrayList() ); - c.getBag().add(c1); - c.getBag().add(c2); - c1.getBag().add(c); - c2.getBag().add(c); - s.save(c); - c.getBag().add(c2); - c2.getBag().add(c); - c.getLazyBag().add(c1); - c1.getLazyBag().add(c); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Container) s.createQuery( "from ContainerX c" ).list().get(0); - c.getLazyBag().size(); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Container) s.createQuery( "from ContainerX c" ).list().get(0); - Contained c3 = new Contained(); - //c.getBag().add(c3); - //c3.getBag().add(c); - c.getLazyBag().add(c3); - c3.getLazyBag().add(c); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Container) s.createQuery( "from ContainerX c" ).list().get(0); - Contained c4 = new Contained(); - c.getLazyBag().add(c4); - c4.getLazyBag().add(c); - assertTrue( c.getLazyBag().size()==3 ); //forces initialization - //s.save(c4); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Container) s.createQuery( "from ContainerX c" ).list().get(0); - Iterator i = c.getBag().iterator(); - int j=0; - while ( i.hasNext() ) { - assertTrue( i.next()!=null ); - j++; - } - assertTrue(j==3); - assertTrue( c.getLazyBag().size()==3 ); - s.delete(c); - c.getBag().remove(c2); - Iterator iter = c.getBag().iterator(); - j=0; - while ( iter.hasNext() ) { - j++; - s.delete( iter.next() ); - } - assertTrue(j==2); - s.delete( s.load(Contained.class, new Long( c4.getId() ) ) ); - s.delete( s.load(Contained.class, new Long( c3.getId() ) ) ); - t.commit(); - s.close(); - } - - @Test - public void testCircularCascade() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Circular c = new Circular(); - c.setClazz(Circular.class); - c.setOther( new Circular() ); - c.getOther().setOther( new Circular() ); - c.getOther().getOther().setOther(c); - c.setAnyEntity( c.getOther() ); - String id = (String) s.save(c); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - c = (Circular) s.load(Circular.class, id); - c.getOther().getOther().setClazz(Foo.class); - tx.commit(); - s.close(); - c.getOther().setClazz(Qux.class); - s = openSession(); - tx = s.beginTransaction(); - s.saveOrUpdate(c); - tx.commit(); - s.close(); - c.getOther().getOther().setClazz(Bar.class); - s = openSession(); - tx = s.beginTransaction(); - s.saveOrUpdate(c); - tx.commit(); - s.close(); - s = openSession(); - tx = s.beginTransaction(); - c = (Circular) s.load(Circular.class, id); - assertTrue( c.getOther().getOther().getClazz()==Bar.class); - assertTrue( c.getOther().getClazz()==Qux.class); - assertTrue( c.getOther().getOther().getOther()==c); - assertTrue( c.getAnyEntity()==c.getOther() ); - assertEquals( 3, doDelete( s, "from Universe" ) ); - tx.commit(); - s.close(); - } - - @Test - public void testDeleteEmpty() throws Exception { - Session s = openSession(); - s.beginTransaction(); - assertEquals( 0, doDelete( s, "from Simple" ) ); - assertEquals( 0, doDelete( s, "from Universe" ) ); - s.getTransaction().commit(); - s.close(); - } - - @Test - @SkipForDialect( value = CockroachDialect.class ) - public void testLocking() throws Exception { - Session s = openSession(); - Transaction tx = s.beginTransaction(); - Simple s1 = new Simple( Long.valueOf(1) ); - s1.setCount(1); - Simple s2 = new Simple( Long.valueOf(2) ); - s2.setCount(2); - Simple s3 = new Simple( Long.valueOf(3) ); - s3.setCount(3); - Simple s4 = new Simple( Long.valueOf(4) ); - s4.setCount(4); - Simple s5 = new Simple( Long.valueOf(5) ); - s5.setCount( 5 ); - s.save( s1 ); - s.save( s2 ); - s.save( s3 ); - s.save( s4 ); - s.save( s5 ); - assertTrue( s.getCurrentLockMode( s1 ) == LockMode.WRITE ); - tx.commit(); - s.close(); - - s = openSession(); - tx = s.beginTransaction(); - s1 = (Simple) s.load(Simple.class, new Long(1), LockMode.NONE); - assertTrue( s.getCurrentLockMode(s1)==LockMode.READ || s.getCurrentLockMode(s1)==LockMode.NONE ); //depends if cache is enabled - s2 = (Simple) s.load(Simple.class, new Long(2), LockMode.READ); - assertTrue( s.getCurrentLockMode(s2)==LockMode.READ ); - s3 = (Simple) s.load(Simple.class, new Long(3), LockMode.UPGRADE); - assertTrue( s.getCurrentLockMode(s3)==LockMode.UPGRADE ); - s4 = (Simple) s.byId( Simple.class ).with( new LockOptions( LockMode.UPGRADE_NOWAIT ) ).load( 4L ); - assertTrue( s.getCurrentLockMode(s4)==LockMode.UPGRADE_NOWAIT ); - s5 = (Simple) s.byId( Simple.class ).with( new LockOptions( LockMode.UPGRADE_SKIPLOCKED ) ).load( 5L ); - assertTrue( s.getCurrentLockMode(s5)==LockMode.UPGRADE_SKIPLOCKED ); - - s1 = (Simple) s.load(Simple.class, new Long(1), LockMode.UPGRADE); //upgrade - assertTrue( s.getCurrentLockMode(s1)==LockMode.UPGRADE ); - s2 = (Simple) s.load(Simple.class, new Long(2), LockMode.NONE); - assertTrue( s.getCurrentLockMode(s2)==LockMode.READ ); - s3 = (Simple) s.load(Simple.class, new Long(3), LockMode.READ); - assertTrue( s.getCurrentLockMode(s3)==LockMode.UPGRADE ); - s4 = (Simple) s.load(Simple.class, new Long(4), LockMode.UPGRADE); - assertTrue( s.getCurrentLockMode(s4)==LockMode.UPGRADE_NOWAIT ); - s5 = (Simple) s.load(Simple.class, new Long(5), LockMode.UPGRADE); - assertTrue( s.getCurrentLockMode(s5)==LockMode.UPGRADE_SKIPLOCKED ); - - s.lock(s2, LockMode.UPGRADE); //upgrade - assertTrue( s.getCurrentLockMode(s2)==LockMode.UPGRADE ); - s.lock(s3, LockMode.UPGRADE); - assertTrue( s.getCurrentLockMode(s3)==LockMode.UPGRADE ); - s.lock(s1, LockMode.UPGRADE_NOWAIT); - s.lock(s4, LockMode.NONE); - s.lock(s5, LockMode.UPGRADE_SKIPLOCKED); - assertTrue( s.getCurrentLockMode(s4)==LockMode.UPGRADE_NOWAIT ); - assertTrue( s.getCurrentLockMode(s5)==LockMode.UPGRADE_SKIPLOCKED ); - - tx.commit(); - tx = s.beginTransaction(); - - assertTrue( s.getCurrentLockMode(s3)==LockMode.NONE ); - assertTrue( s.getCurrentLockMode(s1)==LockMode.NONE ); - assertTrue( s.getCurrentLockMode(s2)==LockMode.NONE ); - assertTrue( s.getCurrentLockMode(s4)==LockMode.NONE ); - assertTrue( s.getCurrentLockMode(s5)==LockMode.NONE ); - - s.lock(s1, LockMode.READ); //upgrade - assertTrue( s.getCurrentLockMode(s1)==LockMode.READ ); - s.lock(s2, LockMode.UPGRADE); //upgrade - assertTrue( s.getCurrentLockMode(s2)==LockMode.UPGRADE ); - s.lock(s3, LockMode.UPGRADE_NOWAIT); //upgrade - assertTrue( s.getCurrentLockMode(s3)==LockMode.UPGRADE_NOWAIT ); - s.lock(s4, LockMode.NONE); - assertTrue( s.getCurrentLockMode(s4)==LockMode.NONE ); - - s4.setName("s4"); - s.flush(); - assertTrue( s.getCurrentLockMode(s4)==LockMode.WRITE ); - tx.commit(); - - tx = s.beginTransaction(); - - assertTrue( s.getCurrentLockMode(s3)==LockMode.NONE ); - assertTrue( s.getCurrentLockMode(s1)==LockMode.NONE ); - assertTrue( s.getCurrentLockMode(s2)==LockMode.NONE ); - assertTrue( s.getCurrentLockMode(s4)==LockMode.NONE ); - assertTrue( s.getCurrentLockMode(s5)==LockMode.NONE ); - - s.delete(s1); s.delete(s2); s.delete(s3); s.delete(s4); s.delete(s5); - tx.commit(); - s.close(); - } - - @Test - public void testObjectType() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Parent g = new Parent(); - Foo foo = new Foo(); - g.setAny(foo); - s.save(g); - s.save(foo); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - g = (Parent) s.load( Parent.class, new Long( g.getId() ) ); - assertTrue( g.getAny()!=null && g.getAny() instanceof FooProxy ); - s.delete( g.getAny() ); - s.delete(g); - s.getTransaction().commit(); - s.close(); - } - - @Test - @SkipForDialect(value = CockroachDialect.class, comment = "Uses READ_COMMITTED isolation") - public void testLoadAfterNonExists() throws HibernateException, SQLException { - Session session = openSession(); - if ( ( getDialect() instanceof MySQLDialect ) || ( getDialect() instanceof IngresDialect ) ) { - session.doWork( - new AbstractWork() { - @Override - public void execute(Connection connection) throws SQLException { - connection.setTransactionIsolation( Connection.TRANSACTION_READ_COMMITTED ); - } - } - ); - } - session.getTransaction().begin(); - - // First, prime the fixture session to think the entity does not exist - try { - session.load( Simple.class, new Long(-1) ); - fail(); - } - catch(ObjectNotFoundException onfe) { - if ( getDialect() instanceof TeradataDialect ){ - session.getTransaction().rollback(); - session.getTransaction().begin(); - } - // this is correct - } - - // Next, lets create that entity "under the covers" - Session anotherSession = sessionFactory().openSession(); - anotherSession.beginTransaction(); - Simple myNewSimple = new Simple( Long.valueOf(-1) ); - myNewSimple.setName("My under the radar Simple entity"); - myNewSimple.setAddress("SessionCacheTest.testLoadAfterNonExists"); - myNewSimple.setCount(1); - myNewSimple.setDate( new Date() ); - myNewSimple.setPay( Float.valueOf( 100000000 ) ); - anotherSession.save( myNewSimple ); - anotherSession.getTransaction().commit(); - anotherSession.close(); - - // Now, lets make sure the original session can see the created row... - session.clear(); - try { - Simple dummy = (Simple) session.get( Simple.class, Long.valueOf(-1) ); - assertNotNull("Unable to locate entity Simple with id = -1", dummy); - session.delete( dummy ); - } - catch(ObjectNotFoundException onfe) { - fail("Unable to locate entity Simple with id = -1"); - } - session.getTransaction().commit(); - session.close(); - } - -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/QueryByExampleTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/QueryByExampleTest.java deleted file mode 100644 index 29f8fff60b..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/QueryByExampleTest.java +++ /dev/null @@ -1,141 +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 . - */ -package org.hibernate.orm.test.legacy; -import java.util.List; - -import org.junit.Test; - -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.criterion.Example; -import org.hibernate.criterion.Restrictions; -import org.hibernate.dialect.SybaseASE15Dialect; -import org.hibernate.testing.SkipForDialect; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -/** - * Query by example test to allow nested components - * - * @author Emmanuel Bernard - */ -public class QueryByExampleTest extends LegacyTestCase { - @Override - public String[] getMappings() { - return new String[] { "legacy/Componentizable.hbm.xml" }; - } - - @Test - public void testSimpleQBE() throws Exception { - deleteData(); - initData(); - - Session s = openSession(); - - Transaction t = s.beginTransaction(); - Componentizable componentizable = getComponentizeable("hibernate", "open sourc%", "open source1"); - Criteria crit = s.createCriteria(Componentizable.class); - Example ex = Example.create(componentizable).enableLike(); - crit.add(ex); - List result = crit.list(); - assertNotNull(result); - assertEquals(1, result.size()); - - t.commit(); - s.close(); - } - - @Test - @SkipForDialect( value = SybaseASE15Dialect.class, jiraKey = "HHH-4580") - public void testJunctionNotExpressionQBE() throws Exception { - deleteData(); - initData(); - Session s = openSession(); - Transaction t = s.beginTransaction(); - Componentizable componentizable = getComponentizeable("hibernate", null, "ope%"); - Criteria crit = s.createCriteria(Componentizable.class); - Example ex = Example.create(componentizable).enableLike(); - - crit.add(Restrictions.or(Restrictions.not(ex), ex)); - - List result = crit.list(); - assertNotNull(result); - assertEquals(2, result.size()); - t.commit(); - s.close(); - - } - - @Test - public void testExcludingQBE() throws Exception { - deleteData(); - initData(); - Session s = openSession(); - Transaction t = s.beginTransaction(); - Componentizable getComponentizeable = getComponentizeable("hibernate", null, "ope%"); - Criteria crit = s.createCriteria(Componentizable.class); - Example ex = Example.create(getComponentizeable).enableLike() - .excludeProperty("component.subComponent"); - crit.add(ex); - List result = crit.list(); - assertNotNull(result); - assertEquals(3, result.size()); - - getComponentizeable = getComponentizeable("hibernate", "ORM tool", "fake stuff"); - crit = s.createCriteria(Componentizable.class); - ex = Example.create(getComponentizeable).enableLike() - .excludeProperty("component.subComponent.subName1"); - crit.add(ex); - result = crit.list(); - assertNotNull(result); - assertEquals(1, result.size()); - t.commit(); - s.close(); - - - } - - private void initData() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Componentizable getComponentizeable = getComponentizeable("hibernate", "ORM tool", "ORM tool1"); - s.saveOrUpdate(getComponentizeable); - getComponentizeable = getComponentizeable("hibernate", "open source", "open source1"); - s.saveOrUpdate(getComponentizeable); - getComponentizeable = getComponentizeable("hibernate", null, null); - s.saveOrUpdate(getComponentizeable); - t.commit(); - s.close(); - } - - private void deleteData() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - for ( Object entity : s.createQuery( "from Componentizable" ).list() ) { - s.delete( entity ); - } - t.commit(); - s.close(); - } - - private Componentizable getComponentizeable(String name, String subname, String subname1) { - Componentizable getComponentizeable = new Componentizable(); - if (name != null) { - Component component = new Component(); - component.setName(name); - if (subname != null || subname1 != null) { - SubComponent subComponent = new SubComponent(); - subComponent.setSubName(subname); - subComponent.setSubName1(subname1); - component.setSubComponent(subComponent); - } - getComponentizeable.setComponent(component); - } - return getComponentizeable; - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/RootDetailTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/RootDetailTest.java deleted file mode 100644 index c8f2b4f528..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/RootDetailTest.java +++ /dev/null @@ -1,1143 +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 . - */ -package org.hibernate.orm.test.legacy; - -import java.io.Serializable; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; - -import org.hibernate.Hibernate; -import org.hibernate.LockMode; -import org.hibernate.ObjectNotFoundException; -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.cfg.Configuration; -import org.hibernate.cfg.Environment; -import org.hibernate.criterion.Example; -import org.hibernate.criterion.Restrictions; -import org.hibernate.dialect.AbstractHANADialect; -import org.hibernate.dialect.HSQLDialect; -import org.hibernate.dialect.MySQLDialect; -import org.hibernate.dialect.SAPDBDialect; -import org.hibernate.dialect.TimesTenDialect; -import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess; -import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.jdbc.AbstractWork; - -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.SkipLog; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - - -public class RootDetailTest extends LegacyTestCase { - @Override - public String[] getMappings() { - return new String[] { - "legacy/RootDetail.hbm.xml", - "legacy/Custom.hbm.xml", - "legacy/Category.hbm.xml", - "legacy/Nameable.hbm.xml", - "legacy/SingleSeveral.hbm.xml", - "legacy/WZ.hbm.xml", - "legacy/UpDown.hbm.xml", - "legacy/Eye.hbm.xml" - }; - } - - @Override - public void configure(Configuration cfg) { - super.configure(cfg); - Properties props = new Properties(); - props.put( Environment.ORDER_INSERTS, "true" ); - props.put( Environment.STATEMENT_BATCH_SIZE, "10" ); - cfg.addProperties( props ); - } - - @Test - public void testOuterJoin() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Eye e = new Eye(); - e.setName("Eye Eye"); - Jay jay = new Jay(e); - e.setJay( jay ); - s.saveOrUpdate( e ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - e = (Eye) s.createCriteria(Eye.class).uniqueResult(); - assertTrue( Hibernate.isInitialized( e.getJay() ) ); - assertTrue( Hibernate.isInitialized( e.getJays() ) ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - jay = (Jay) s.createQuery("select new Jay(eye) from Eye eye").uniqueResult(); - assertTrue( "Eye Eye".equals( jay.getEye().getName() ) ); - s.delete( jay.getEye() ); - s.getTransaction().commit(); - s.close(); - } - - @Test - @SuppressWarnings( {"unchecked"}) - public void testCopy() throws Exception { - Category catWA = new Category(); - catWA.setName("HSQL workaround"); - Category cat = new Category(); - cat.setName("foo"); - Category subCatBar = new Category(); - subCatBar.setName("bar"); - Category subCatBaz = new Category(); - subCatBaz.setName("baz"); - cat.getSubcategories().add(subCatBar); - cat.getSubcategories().add(subCatBaz); - - Session s = openSession(); - s.beginTransaction(); - s.save( catWA ); - s.save( cat ); - s.getTransaction().commit(); - s.close(); - - cat.setName("new foo"); - subCatBar.setName("new bar"); - cat.getSubcategories().remove(subCatBaz); - Category newCat = new Category(); - newCat.setName("new"); - cat.getSubcategories().add(newCat); - Category newSubCat = new Category(); - newSubCat.setName("new sub"); - newCat.getSubcategories().add(newSubCat); - - s = openSession(); - s.beginTransaction(); - Category copiedCat = (Category) s.merge( cat ); - s.getTransaction().commit(); - s.close(); - - assertFalse( copiedCat==cat ); - //assertFalse( copiedCat.getSubcategories().contains(newCat) ); - assertTrue( cat.getSubcategories().contains(newCat) ); - - s = openSession(); - cat = (Category) s.createQuery("from Category cat where cat.name='new foo'").uniqueResult(); - newSubCat = (Category) s.createQuery("from Category cat left join fetch cat.subcategories where cat.name='new sub'").uniqueResult(); - assertTrue( newSubCat.getName().equals("new sub") ); - s.close(); - - newSubCat.getSubcategories().add(cat); - cat.setName("new new foo"); - - s = openSession(); - s.beginTransaction(); - s.delete(cat); - s.delete( subCatBaz ); - s.delete( catWA ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testNotNullDiscriminator() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Up up = new Up(); - up.setId1("foo"); - up.setId2(123l); - Down down = new Down(); - down.setId1("foo"); - down.setId2(321l); - down.setValue(12312312l); - s.save(up); - s.save(down); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - List list = s.createQuery( "from Up up order by up.id2 asc" ).list(); - assertTrue( list.size()==2 ); - assertFalse( list.get(0) instanceof Down ); - assertTrue( list.get(1) instanceof Down ); - list = s.createQuery( "from Down down" ).list(); - assertTrue( list.size()==1 ); - assertTrue( list.get(0) instanceof Down ); - //list = s.find("from Up down where down.class = Down"); - assertTrue( list.size()==1 ); - assertTrue( list.get(0) instanceof Down ); - for ( Object entity : s.createQuery( "from Up" ).list() ) { - s.delete( entity ); - } - t.commit(); - s.close(); - - } - - @Test - @SkipForDialect(value = CockroachDB192Dialect.class, comment = "https://github.com/cockroachdb/cockroach/issues/27871") - public void testSelfManyToOne() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Root m = new Root(); - m.setOtherRoot(m); - s.save(m); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Iterator i = s.createQuery( "from Root" ).iterate(); - m = (Root) i.next(); - assertTrue( m.getOtherRoot()==m ); - if ( getDialect() instanceof HSQLDialect || getDialect() instanceof MySQLDialect ) { - m.setOtherRoot(null); - s.flush(); - } - s.delete(m); - t.commit(); - s.close(); - } - - @Test - @SkipForDialect(value = CockroachDB192Dialect.class, comment = "https://github.com/cockroachdb/cockroach/issues/27871") - public void testExample() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Root m = new Root(); - m.setName("name"); - m.setX(5); - m.setOtherRoot(m); - s.save(m); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Root m1 = (Root) s.createCriteria( Root.class) - .add( Example.create(m).enableLike().ignoreCase().excludeProperty("bigDecimal") ) - .uniqueResult(); - assertTrue( m1.getOtherRoot()==m1 ); - m1 = (Root) s.createCriteria( Root.class) - .add( Restrictions.eq("name", "foobar") ) - .uniqueResult(); - assertTrue( m1==null ); - m1 = (Root) s.createCriteria( Root.class) - .add( Example.create(m).excludeProperty("bigDecimal") ) - .createCriteria("otherRoot") - .add( Example.create(m).excludeZeroes().excludeProperty("bigDecimal") ) - .uniqueResult(); - assertTrue( m1.getOtherRoot()==m1 ); - Root m2 = (Root) s.createCriteria( Root.class) - .add( Example.create(m).excludeNone().excludeProperty("bigDecimal") ) - .uniqueResult(); - assertTrue( m2==m1 ); - m.setName(null); - m2 = (Root) s.createCriteria( Root.class) - .add( Example.create(m).excludeNone().excludeProperty("bigDecimal") ) - .uniqueResult(); - assertTrue( null == m2 ); - if (getDialect() instanceof HSQLDialect || getDialect() instanceof MySQLDialect) { - m1.setOtherRoot(null); - s.flush(); - } - s.delete(m1); - t.commit(); - s.close(); - } - - @Test - public void testNonLazyBidirectional() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Single sin = new Single(); - sin.setId("asdfds"); - sin.setString("adsa asdfasd"); - Several sev = new Several(); - sev.setId("asdfasdfasd"); - sev.setString("asd ddd"); - sin.getSeveral().add(sev); - sev.setSingle(sin); - s.save(sin); - t.commit(); - s.close(); - s = openSession(); - t = s.beginTransaction(); - sin = (Single) s.load( Single.class, sin ); - t.commit(); - s.close(); - s = openSession(); - t = s.beginTransaction(); - sev = (Several) s.load( Several.class, sev ); - t.commit(); - s.close(); - s = openSession(); - t = s.beginTransaction(); - s.createQuery( "from Several" ).list(); - t.commit(); - s.close(); - s = openSession(); - t = s.beginTransaction(); - for ( Object entity : s.createQuery( "from Single" ).list() ) { - s.delete( entity ); - } - t.commit(); - s.close(); - } - - @Test - public void testCollectionQuery() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - if ( !(getDialect() instanceof MySQLDialect) && !(getDialect() instanceof SAPDBDialect) && !(getDialect() instanceof MckoiDialect) ) { - s.createQuery( "FROM Root m WHERE NOT EXISTS ( FROM m.details d WHERE NOT d.i=5 )" ).iterate(); - s.createQuery( "FROM Root m WHERE NOT 5 IN ( SELECT d.i FROM m.details AS d )" ).iterate(); - } - s.createQuery( "SELECT m FROM Root m JOIN m.details d WHERE d.i=5" ).iterate(); - s.createQuery( "SELECT m FROM Root m JOIN m.details d WHERE d.i=5" ).list(); - s.createQuery( "SELECT m.id FROM Root AS m JOIN m.details AS d WHERE d.i=5" ).list(); - t.commit(); - s.close(); - } - - @Test - public void tesRootDetail() throws Exception { - if (getDialect() instanceof HSQLDialect) return; - - Session s = openSession(); - Transaction t = s.beginTransaction(); - Root root = new Root(); - assertTrue( "save returned native id", s.save( root )!=null ); - Serializable mid = s.getIdentifier( root ); - Detail d1 = new Detail(); - d1.setRoot( root ); - Serializable did = s.save(d1); - Detail d2 = new Detail(); - d2.setI(12); - d2.setRoot( root ); - assertTrue( "generated id returned", s.save(d2)!=null); - root.addDetail(d1); - root.addDetail(d2); - if ( !(getDialect() instanceof MySQLDialect) && !(getDialect() instanceof SAPDBDialect) && !(getDialect() instanceof MckoiDialect) && !(getDialect() instanceof TimesTenDialect)) { - assertTrue( - "query", - s.createQuery( - "from Detail d, Root m where m = d.root and size(m.outgoing) = 0 and size(m.incoming) = 0" - ).list().size()==2 - ); - } - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - root = new Root(); - s.load( root, mid); - assertTrue( root.getDetails().size()==2 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - root = (Root) s.load( Root.class, mid); - Iterator iter = root.getDetails().iterator(); - int i=0; - while ( iter.hasNext() ) { - Detail d = (Detail) iter.next(); - assertTrue( "root-detail", d.getRoot()== root ); - i++; - } - assertTrue( "root-detail", i==2 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - assertTrue( s.createQuery( "select elements(root.details) from Root root" ).list().size()==2 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - List list = s.createQuery( "from Root m left join fetch m.details" ).list(); - Root m = (Root) list.get(0); - assertTrue( Hibernate.isInitialized( m.getDetails() ) ); - assertTrue( m.getDetails().size()==2 ); - list = s.createQuery( "from Detail d inner join fetch d.root" ).list(); - Detail dt = (Detail) list.get(0); - Serializable dtid = s.getIdentifier(dt); - assertTrue( dt.getRoot()==m ); - - //assertTrue(m.getAllDetails().size()==2); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - list = s.createQuery( "select m from Root m1, Root m left join fetch m.details where m.name=m1.name" ) - .list(); - assertTrue( Hibernate.isInitialized( ( (Root) list.get(0) ).getDetails() ) ); - dt = (Detail) s.load(Detail.class, dtid); - assertTrue( ( (Root) list.get(0) ).getDetails().contains(dt) ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - list = s.createQuery( - "select m, m1.name from Root m1, Root m left join fetch m.details where m.name=m1.name" - ).list(); - assertTrue( Hibernate.isInitialized( ( (Root) ( (Object[]) list.get(0) )[0] ).getDetails() ) ); - dt = (Detail) s.load(Detail.class, dtid); - assertTrue( ( (Root) ( (Object[]) list.get(0) )[0] ).getDetails().contains(dt) ); - t.commit(); - s.close(); - - - s = openSession(); - t = s.beginTransaction(); - Detail dd = (Detail) s.load(Detail.class, did); - root = dd.getRoot(); - assertTrue( "detail-root", root.getDetails().contains(dd) ); - assertTrue( s.createFilter( root.getDetails(), "order by this.i desc" ).list().size()==2 ); - assertTrue( s.createFilter( root.getDetails(), "select this where this.id > -1" ).list().size()==2 ); - Query q = s.createFilter( root.getDetails(), "where this.id > :id" ); - q.setInteger("id", -1); - assertTrue( q.list().size()==2 ); - q = s.createFilter( root.getDetails(), "where this.id > :id1 and this.id < :id2" ); - q.setInteger("id1", -1); - q.setInteger("id2", 99999999); - assertTrue( q.list().size()==2 ); - q.setInteger("id2", -1); - assertTrue( q.list().size()==0 ); - - list = new ArrayList(); - list.add(did); - list.add( new Long(-1) ); - - q = s.createFilter( root.getDetails(), "where this.id in (:ids)" ); - q.setParameterList("ids", list); - assertTrue( q.list().size()==1 ); - - q = s.createFilter( root.getDetails(), "where this.id in (:ids)" ); - q.setParameterList("ids", list); - assertTrue( q.iterate().hasNext() ); - - assertTrue( s.createFilter( root.getDetails(), "where this.id > -1" ).list().size()==2 ); - assertTrue( s.createFilter( root.getDetails(), "select this.root where this.id > -1" ).list().size()==2 ); - assertTrue( - s.createFilter( root.getDetails(), "select m from Root m where this.id > -1 and this.root=m" ) - .list() - .size()==2 ); - assertTrue( s.createFilter( root.getIncoming(), "where this.id > -1 and this.name is not null" ).list().size()==0 ); - - assertTrue( s.createFilter( root.getDetails(), "select max(this.i)" ).iterate().next() instanceof Integer ); - assertTrue( s.createFilter( root.getDetails(), "select max(this.i) group by this.id" ).iterate().next() instanceof Integer ); - assertTrue( s.createFilter( root.getDetails(), "select count(*)" ).iterate().next() instanceof Long ); - - assertTrue( s.createFilter( root.getDetails(), "select this.root" ).list().size()==2 ); - assertTrue( s.createFilter( root.getMoreDetails(), "" ).list().size()==0 ); - assertTrue( s.createFilter( root.getIncoming(), "" ).list().size()==0 ); - - Query f = s.createFilter( root.getDetails(), "select max(this.i) where this.i < :top and this.i>=:bottom" ); - f.setInteger("top", 100); - f.setInteger("bottom", 0); - assertEquals( f.iterate().next(), new Integer(12) ); - f.setInteger("top", 2); - assertEquals( f.iterate().next(), new Integer(0) ); - - f = s.createFilter( root.getDetails(), "select max(this.i) where this.i not in (:list)" ); - Collection coll = new ArrayList(); - coll.add( new Integer(-666) ); - coll.add( new Integer(22) ); - coll.add( new Integer(0) ); - f.setParameterList("list", coll); - assertEquals( f.iterate().next(), new Integer(12) ); - - f = s.createFilter( root.getDetails(), "select max(this.i) where this.i not in (:list) and this.root.name = :listy2" ); - f.setParameterList("list", coll); - f.setParameter( "listy2", root.getName() ); - assertEquals( f.iterate().next(), new Integer(12) ); - - iter = root.getDetails().iterator(); - i=0; - while ( iter.hasNext() ) { - Detail d = (Detail) iter.next(); - assertTrue( "root-detail", d.getRoot()== root ); - s.delete(d); - i++; - } - assertTrue( "root-detail", i==2 ); - s.delete( root ); - t.commit(); - s.close(); - } - - @Test - public void testIncomingOutgoing() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Root root1 = new Root(); - Root root2 = new Root(); - Root root3 = new Root(); - s.save( root1 ); - s.save( root2 ); - s.save( root3 ); - root1.addIncoming( root2 ); - root2.addOutgoing( root1 ); - root1.addIncoming( root3 ); - root3.addOutgoing( root1 ); - Serializable m1id = s.getIdentifier( root1 ); - assertTrue( - s.createFilter( root1.getIncoming(), "where this.id > 0 and this.name is not null" ) - .list() - .size() == 2 - ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - root1 = (Root) s.load( Root.class, m1id); - Iterator iter = root1.getIncoming().iterator(); - int i=0; - while ( iter.hasNext() ) { - Root m = (Root) iter.next(); - assertTrue( "outgoing", m.getOutgoing().size()==1 ); - assertTrue( "outgoing", m.getOutgoing().contains( root1 ) ); - s.delete(m); - i++; - } - assertTrue( "incoming-outgoing", i == 2 ); - s.delete( root1 ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testCascading() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Detail d1 = new Detail(); - Detail d2 = new Detail(); - d2.setI(22); - Root m = new Root(); - Root m0 = new Root(); - Serializable m0id = s.save(m0); - m0.addDetail(d1); m0.addDetail(d2); - d1.setRoot(m0); d2.setRoot(m0); - m.getMoreDetails().add(d1); - m.getMoreDetails().add(d2); - Serializable mid = s.save(m); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - m = (Root) s.load( Root.class, mid); - assertTrue( "cascade save", m.getMoreDetails().size()==2 ); - assertTrue( "cascade save", ( (Detail) m.getMoreDetails().iterator().next() ).getRoot().getDetails().size()==2 ); - s.delete( m ); - s.delete( s.load( Root.class, m0id ) ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testNamedQuery() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Query q = s.getNamedQuery("all_details"); - q.list(); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testUpdateLazyCollections() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Root m = new Root(); - s.save( m ); - Detail d1 = new Detail(); - Detail d2 = new Detail(); - d2.setX( 14 ); - d1.setRoot( m ); - d2.setRoot( m ); - s.save( d1 ); - s.save( d2 ); - m.addDetail( d1 ); - m.addDetail( d2 ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - m = (Root) s.load( Root.class, m.getId() ); - s.getTransaction().commit(); - s.close(); - m.setName("New Name"); - - s = openSession(); - s.beginTransaction(); - s.update( m ); - Iterator iter = m.getDetails().iterator(); - int i=0; - while ( iter.hasNext() ) { - assertTrue( iter.next()!=null ); - i++; - } - assertTrue(i==2); - iter = m.getDetails().iterator(); - while ( iter.hasNext() ) s.delete( iter.next() ); - s.delete( m ); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testMultiLevelCascade() throws Exception { - Session s = openSession(); - Transaction txn = s.beginTransaction(); - Detail detail = new Detail(); - SubDetail subdetail = new SubDetail(); - Root m = new Root(); - Root m0 = new Root(); - Serializable m0id = s.save(m0); - m0.addDetail(detail); - detail.setRoot(m0); - m.getMoreDetails().add(detail); - detail.setSubDetails( new HashSet() ); - detail.getSubDetails().add(subdetail); - Serializable mid = s.save(m); - txn.commit(); - s.close(); - - s = openSession(); - txn = s.beginTransaction(); - m = (Root) s.load( Root.class, mid ); - assertTrue( ( (Detail) m.getMoreDetails().iterator().next() ).getSubDetails().size()!=0 ); - s.delete(m); - assertTrue( s.createQuery( "from SubDetail" ).list().size()==0 ); - assertTrue( s.createQuery( "from Detail d" ).list().size()==0 ); - s.delete( s.load( Root.class, m0id) ); - txn.commit(); - s.close(); - } - - @Test - public void testMixNativeAssigned() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Category c = new Category(); - c.setName("NAME"); - Assignable assn = new Assignable(); - assn.setId("i.d."); - List l = new ArrayList(); - l.add( c ); - assn.setCategories( l ); - c.setAssignable( assn ); - s.save( assn ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.delete( assn ); - s.getTransaction().commit(); - s.close(); - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testCollectionReplaceOnUpdate() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Category c = new Category(); - List list = new ArrayList(); - c.setSubcategories(list); - list.add( new Category() ); - s.save(c); - t.commit(); - s.close(); - c.setSubcategories(list); - - s = openSession(); - t = s.beginTransaction(); - s.update(c); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Category) s.load( Category.class, new Long( c.getId() ), LockMode.UPGRADE ); - List list2 = c.getSubcategories(); - t.commit(); - s.close(); - - assertTrue( !Hibernate.isInitialized( c.getSubcategories() ) ); - - c.setSubcategories(list2); - s = openSession(); - t = s.beginTransaction(); - s.update(c); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Category) s.load( Category.class, new Long( c.getId() ), LockMode.UPGRADE ); - assertTrue( c.getSubcategories().size()==1 ); - s.delete(c); - t.commit(); - s.close(); - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testCollectionReplace2() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Category c = new Category(); - List list = new ArrayList(); - c.setSubcategories(list); - list.add( new Category() ); - Category c2 = new Category(); - s.save(c2); - s.save(c); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Category) s.load( Category.class, new Long( c.getId() ), LockMode.UPGRADE ); - List list2 = c.getSubcategories(); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c2 = (Category) s.load( Category.class, new Long( c2.getId() ), LockMode.UPGRADE ); - c2.setSubcategories(list2); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c2 = (Category) s.load( Category.class, new Long( c2.getId() ), LockMode.UPGRADE ); - assertTrue( c2.getSubcategories().size()==1 ); - s.delete(c2); - s.delete( s.load( Category.class, new Long( c.getId() ) ) ); - t.commit(); - s.close(); - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testCollectionReplace() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Category c = new Category(); - List list = new ArrayList(); - c.setSubcategories(list); - list.add( new Category() ); - s.save(c); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Category) s.load( Category.class, new Long( c.getId() ), LockMode.UPGRADE ); - c.setSubcategories(list); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Category) s.load( Category.class, new Long( c.getId() ), LockMode.UPGRADE ); - List list2 = c.getSubcategories(); - t.commit(); - s.close(); - - assertTrue( !Hibernate.isInitialized( c.getSubcategories() ) ); - - s = openSession(); - t = s.beginTransaction(); - c = (Category) s.load( Category.class, new Long( c.getId() ), LockMode.UPGRADE ); - c.setSubcategories(list2); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - c = (Category) s.load( Category.class, new Long( c.getId() ), LockMode.UPGRADE ); - assertTrue( c.getSubcategories().size()==1 ); - s.delete(c); - t.commit(); - s.close(); - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testCategories() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Category c = new Category(); - c.setName(Category.ROOT_CATEGORY); - Category c1 = new Category(); - Category c2 = new Category(); - Category c3 = new Category(); - c.getSubcategories().add(c1); - c.getSubcategories().add(c2); - c2.getSubcategories().add( null ); - c2.getSubcategories().add( c3 ); - s.save( c ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.lock(c, LockMode.UPGRADE); - Category loaded = (Category) s.load( Category.class, new Long( c3.getId() ) ); - assertTrue( s.contains(c3) ); - assertTrue(loaded==c3); - assertTrue( s.getCurrentLockMode(c3)==LockMode.NONE ); - assertTrue( s.getCurrentLockMode( c ) == LockMode.UPGRADE ); - s.flush(); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - loaded = (Category) s.load( Category.class, new Long( c.getId() ) ); - assertFalse( Hibernate.isInitialized( loaded.getSubcategories() ) ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.lock(loaded, LockMode.NONE); - assertTrue( loaded.getSubcategories().size()==2 ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - c = (Category) s.load( Category.class, new Long( c.getId() ) ); - System.out.println( c.getSubcategories() ); - assertTrue( c.getSubcategories().get(0)!=null && c.getSubcategories().get(1)!=null ); - List list = ( (Category) c.getSubcategories().get(1) ).getSubcategories(); - assertTrue( list.get(1)!=null && list.get(0)==null ); - - assertTrue( - s.createQuery( "from Category c where c.name = org.hibernate.test.legacy.Category.ROOT_CATEGORY" ) - .iterate().hasNext() - ); - s.delete( c ); - s.getTransaction().commit(); - s.close(); - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testCollectionRefresh() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Category c = new Category(); - List list = new ArrayList(); - c.setSubcategories(list); - list.add( new Category() ); - c.setName("root"); - Serializable id = s.save(c); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - c = (Category) s.load(Category.class, id); - s.refresh( c ); - s.flush(); - assertTrue( c.getSubcategories().size() == 1 ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - c = (Category) s.load(Category.class, id); - assertTrue( c.getSubcategories().size() == 1 ); - s.delete( c ); - s.getTransaction().commit(); - s.close(); - } - - protected boolean isSerializableIsolationEnforced() throws Exception { - JdbcConnectionAccess connectionAccess = sessionFactory().getServiceRegistry().getService( JdbcServices.class ).getBootstrapJdbcConnectionAccess(); - Connection conn = null; - try { - conn = connectionAccess.obtainConnection(); - return conn.getTransactionIsolation() >= Connection.TRANSACTION_SERIALIZABLE; - } - finally { - if ( conn != null ) { - try { - connectionAccess.releaseConnection( conn ); - } - catch ( Throwable ignore ) { - // ignore... - } - } - } - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testCachedCollectionRefresh() throws Exception { - if ( isSerializableIsolationEnforced() ) { - SkipLog.reportSkip( "SERIALIZABLE isolation", "cached collection refreshing" ); - return; - } - Session s = openSession(); - s.beginTransaction(); - Category c = new Category(); - List list = new ArrayList(); - c.setSubcategories(list); - list.add( new Category() ); - c.setName("root"); - Serializable id = s.save(c); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - c = (Category) s.load(Category.class, id); - c.getSubcategories().size(); //force load and cache - s.getTransaction().commit(); - s.close(); - - s = openSession(); - if ( (getDialect() instanceof MySQLDialect) ) { - s.doWork( - new AbstractWork() { - @Override - public void execute(Connection connection) throws SQLException { - connection.setTransactionIsolation( Connection.TRANSACTION_READ_COMMITTED ); - } - } - ); - } - s.beginTransaction(); - c = (Category) s.load(Category.class, id); - c.getSubcategories().size(); //force load - - Session ss = openSession(); - ss.beginTransaction(); - Category c2 = (Category) ss.load(Category.class, id); - ss.delete( c2.getSubcategories().get(0) ); - c2.getSubcategories().clear(); - ss.getTransaction().commit(); - ss.close(); - - s.refresh(c); - assertTrue( c.getSubcategories().size()==0 ); - - ss = openSession(); - ss.beginTransaction(); - c2 = (Category) ss.load(Category.class, id); - c2.getSubcategories().add( new Category() ); - c2.getSubcategories().add( new Category() ); - ss.getTransaction().commit(); - ss.close(); - - s.refresh(c); - assertEquals( 2, c.getSubcategories().size() ); - - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - c = (Category) s.load(Category.class, id); - assertEquals( 2, c.getSubcategories().size() ); - s.delete(c); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testCustomPersister() throws Exception { - Session s = openSession(); - Custom c = new Custom(); - c.setName( "foo" ); - c.id="100"; - s.beginTransaction(); - String id = id = (String) s.save( c ); - assertTrue( c == s.load( Custom.class, id ) ); - s.flush(); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - c = (Custom) s.load(Custom.class, id); - assertTrue( c.getName().equals("foo") ); - c.setName( "bar" ); - s.flush(); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - c = (Custom) s.load(Custom.class, id); - assertTrue( c.getName().equals("bar") ); - s.delete(c); - s.flush(); - s.getTransaction().commit(); - s.close(); - s = openSession(); - boolean none = false; - try { - s.load(Custom.class, id); - } - catch (ObjectNotFoundException onfe) { - none=true; - } - assertTrue(none); - s.close(); - } - - @Test - public void testInterface() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Serializable id = s.save( new BasicNameable() ); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Nameable n = (Nameable) s.load(Nameable.class, id); - s.delete(n); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testNoUpdateManyToOne() throws Exception { - Session s = openSession(); - s.beginTransaction(); - W w1 = new W(); - W w2 = new W(); - Z z = new Z(); - z.setW(w1); - s.save(z); - s.flush(); - z.setW(w2); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - s.update(z); - s.flush(); - s.delete(z); - for ( Object entity : s.createQuery( "from W" ).list() ) { - s.delete( entity ); - } - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testQueuedBagAdds() throws Exception { - Session s = openSession(); - s.beginTransaction(); - Assignable a = new Assignable(); - a.setId("foo"); - a.setCategories( new ArrayList() ); - Category c = new Category(); - c.setAssignable(a); - a.getCategories().add(c); - s.save(a); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictCollectionRegion( "org.hibernate.test.legacy.Assignable.categories" ); - - s = openSession(); - s.beginTransaction(); - a = (Assignable) s.get(Assignable.class, "foo"); - c = new Category(); - c.setAssignable(a); - a.getCategories().add(c); - assertFalse( Hibernate.isInitialized( a.getCategories() ) ); - assertTrue( a.getCategories().size()==2 ); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictCollectionRegion( "org.hibernate.test.legacy.Assignable.categories" ); - - s = openSession(); - s.beginTransaction(); - a = (Assignable) s.get(Assignable.class, "foo"); - c = new Category(); - c.setAssignable(a); - a.getCategories().add(c); - assertFalse( Hibernate.isInitialized( a.getCategories() ) ); - s.flush(); - assertFalse( Hibernate.isInitialized( a.getCategories() ) ); - assertTrue( a.getCategories().size()==3 ); - s.getTransaction().commit(); - s.close(); - - sessionFactory().getCache().evictCollectionRegion( "org.hibernate.test.legacy.Assignable.categories" ); - - s = openSession(); - s.beginTransaction(); - a = (Assignable) s.get(Assignable.class, "foo"); - assertTrue( a.getCategories().size()==3 ); - s.delete(a); - s.getTransaction().commit(); - s.close(); - - } - - @Test - @SkipForDialect(value = AbstractHANADialect.class, comment = " HANA doesn't support tables consisting of only a single auto-generated column") - public void testPolymorphicCriteria() throws Exception { - Session s = openSession(); - Transaction txn = s.beginTransaction(); - Category f = new Category(); - Single b = new Single(); - b.setId("asdfa"); - b.setString("asdfasdf"); - s.save(f); - s.save(b); - List list = s.createCriteria(Object.class).list(); - assertTrue( list.size()==2 ); - assertTrue( list.contains(f) && list.contains(b) ); - s.delete(f); - s.delete(b); - txn.commit(); - s.close(); - } - -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/SQLFunctionsTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/SQLFunctionsTest.java deleted file mode 100644 index 035538c691..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/SQLFunctionsTest.java +++ /dev/null @@ -1,689 +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 . - */ -package org.hibernate.orm.test.legacy; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.hibernate.query.Query; -import org.hibernate.ScrollableResults; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.dialect.DB2Dialect; -import org.hibernate.dialect.DerbyDialect; -import org.hibernate.dialect.HSQLDialect; -import org.hibernate.dialect.InterbaseDialect; -import org.hibernate.dialect.MckoiDialect; -import org.hibernate.dialect.MySQLDialect; -import org.hibernate.dialect.Oracle9iDialect; -import org.hibernate.dialect.SQLServerDialect; -import org.hibernate.dialect.Sybase11Dialect; -import org.hibernate.dialect.SybaseASE15Dialect; -import org.hibernate.dialect.SybaseAnywhereDialect; -import org.hibernate.dialect.SybaseDialect; -import org.hibernate.dialect.TeradataDialect; -import org.hibernate.dialect.TimesTenDialect; -import org.hibernate.dialect.function.SQLFunction; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -public class SQLFunctionsTest extends LegacyTestCase { - - @Override - public String[] getMappings() { - return new String[] { - "legacy/AltSimple.hbm.xml", - "legacy/Broken.hbm.xml", - "legacy/Blobber.hbm.xml" - }; - } - - @Test - public void testDialectSQLFunctions() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Iterator iter = s.createQuery( "select max(s.count) from Simple s" ).iterate(); - - if ( getDialect() instanceof MySQLDialect ) assertTrue( iter.hasNext() && iter.next()==null ); - - Simple simple = new Simple( Long.valueOf(10) ); - simple.setName("Simple Dialect Function Test"); - simple.setAddress("Simple Address"); - simple.setPay( Float.valueOf(45.8f) ); - simple.setCount(2); - s.save( simple ); - - // Test to make sure allocating a specified object operates correctly. - assertTrue( - s.createQuery( "select new org.hibernate.test.legacy.S(s.count, s.address) from Simple s" ).list().size() == 1 - ); - - // Quick check the base dialect functions operate correctly - assertTrue( - s.createQuery( "select max(s.count) from Simple s" ).list().size() == 1 - ); - assertTrue( - s.createQuery( "select count(*) from Simple s" ).list().size() == 1 - ); - - if ( getDialect() instanceof Oracle9iDialect ) { - // Check Oracle Dialect mix of dialect functions - no args (no parenthesis and single arg functions - List rset = s.createQuery( "select s.name, sysdate, trunc(s.pay), round(s.pay) from Simple s" ).list(); - assertNotNull("Name string should have been returned",(((Object[])rset.get(0))[0])); - assertNotNull("Todays Date should have been returned",(((Object[])rset.get(0))[1])); - assertEquals("trunc(45.8) result was incorrect ", Float.valueOf(45), ( (Object[]) rset.get(0) )[2] ); - assertEquals("round(45.8) result was incorrect ", Float.valueOf(46), ( (Object[]) rset.get(0) )[3] ); - - simple.setPay(new Float(-45.8)); - s.update(simple); - - // Test type conversions while using nested functions (Float to Int). - rset = s.createQuery( "select abs(round(s.pay)) from Simple s" ).list(); - assertEquals("abs(round(-45.8)) result was incorrect ", Float.valueOf( 46 ), rset.get(0)); - - // Test a larger depth 3 function example - Not a useful combo other than for testing - assertTrue( - s.createQuery( "select trunc(round(sysdate)) from Simple s" ).list().size() == 1 - ); - - // Test the oracle standard NVL funtion as a test of multi-param functions... - simple.setPay(null); - s.update(simple); - Integer value = (Integer) s.createQuery( - "select MOD( NVL(s.pay, 5000), 2 ) from Simple as s where s.id = 10" - ).list() - .get(0); - assertTrue( 0 == value.intValue() ); - } - - if ( (getDialect() instanceof HSQLDialect) ) { - // Test the hsql standard MOD funtion as a test of multi-param functions... - Integer value = (Integer) s.createQuery( "select MOD(s.count, 2) from Simple as s where s.id = 10" ) - .list() - .get(0); - assertTrue( 0 == value.intValue() ); - } - - s.delete(simple); - t.commit(); - s.close(); - } - - @Test - public void testSetProperties() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Simple simple = new Simple( Long.valueOf(10) ); - simple.setName("Simple 1"); - s.save( simple ); - Query q = s.createQuery("from Simple s where s.name=:name and s.count=:count"); - q.setProperties(simple); - assertTrue( q.list().get(0)==simple ); - //misuse of "Single" as a propertyobject, but it was the first testclass i found with a collection ;) - Single single = new Single() { // trivial hack to test properties with arrays. - String[] getStuff() { - return (String[]) getSeveral().toArray(new String[getSeveral().size()]); - } - void setStuff(String[] stuff) { - setSeveral( Arrays.asList( stuff ) ); - } - }; - - List l = new ArrayList(); - l.add("Simple 1"); - l.add("Slimeball"); - single.setSeveral(l); - q = s.createQuery("from Simple s where s.name in (:several)"); - q.setProperties(single); - assertTrue( q.list().get(0)==simple ); - - q = s.createQuery("from Simple s where s.name in :several"); - q.setProperties(single); - assertTrue( q.list().get(0)==simple ); - - q = s.createQuery("from Simple s where s.name in (:stuff)"); - q.setProperties(single); - assertTrue( q.list().get(0)==simple ); - - q = s.createQuery("from Simple s where s.name in :stuff"); - q.setProperties(single); - assertTrue( q.list().get(0)==simple ); - - s.delete(simple); - t.commit(); - s.close(); - } - - @Test - public void testSetPropertiesMap() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Simple simple = new Simple( Long.valueOf(10) ); - simple.setName("Simple 1"); - s.save( simple ); - - Map parameters = new HashMap<>(); - parameters.put( "name", simple.getName() ); - parameters.put( "count", simple.getCount() ); - Query q = s.createQuery("from Simple s where s.name=:name and s.count=:count"); - q.setProperties((parameters)); - assertTrue( q.list().get(0)==simple ); - - List l = new ArrayList<>(); - l.add("Simple 1"); - l.add("Slimeball"); - parameters.put("several", l); - q = s.createQuery("from Simple s where s.name in (:several)"); - q.setProperties(parameters); - assertTrue( q.list().get(0)==simple ); - - parameters.put("stuff", l.toArray(new String[0])); - q = s.createQuery("from Simple s where s.name in (:stuff)"); - q.setProperties(parameters); - assertTrue( q.list().get(0)==simple ); - - s.delete(simple); - t.commit(); - s.close(); - } - - @Test - public void testBroken() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Broken b = new Fixed(); - b.setId( new Long(123)); - b.setOtherId("foobar"); - s.save(b); - s.flush(); - b.setTimestamp( new Date() ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - s.update(b); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - b = (Broken) s.load( Broken.class, b ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - s.delete(b); - t.commit(); - s.close(); - } - - @Test - public void testNothinToUpdate() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Simple simple = new Simple( Long.valueOf(10) ); - simple.setName("Simple 1"); - s.save( simple ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - s.update( simple ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - s.update( simple ); - s.delete(simple); - t.commit(); - s.close(); - } - - @Test - public void testCachedQuery() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Simple simple = new Simple( Long.valueOf(10) ); - simple.setName( "Simple 1" ); - Long id = (Long) s.save( simple ); - assertEquals( Long.valueOf( 10 ), id ); - assertEquals( Long.valueOf( 10 ), simple.getId() ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Query q = s.createQuery("from Simple s where s.name=?"); - q.setCacheable(true); - q.setString(0, "Simple 1"); - assertTrue( q.list().size()==1 ); - assertTrue( q.list().size()==1 ); - assertTrue( q.list().size()==1 ); - q = s.createQuery("from Simple s where s.name=:name"); - q.setCacheable(true); - q.setString("name", "Simple 1"); - assertTrue( q.list().size()==1 ); - simple = (Simple) q.list().get(0); - - q.setString("name", "Simple 2"); - assertTrue( q.list().size()==0 ); - assertTrue( q.list().size()==0 ); - simple.setName("Simple 2"); - assertTrue( q.list().size()==1 ); - assertTrue( q.list().size()==1 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - q = s.createQuery("from Simple s where s.name=:name"); - q.setString("name", "Simple 2"); - q.setCacheable(true); - assertTrue( q.list().size()==1 ); - assertTrue( q.list().size()==1 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - s.update( simple ); - s.delete(simple); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - q = s.createQuery("from Simple s where s.name=?"); - q.setCacheable(true); - q.setString(0, "Simple 1"); - assertTrue( q.list().size()==0 ); - assertTrue( q.list().size()==0 ); - t.commit(); - s.close(); - } - - @Test - public void testCachedQueryRegion() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Simple simple = new Simple( Long.valueOf(10) ); - simple.setName("Simple 1"); - s.save( simple ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Query q = s.createQuery("from Simple s where s.name=?"); - q.setCacheRegion("foo"); - q.setCacheable(true); - q.setString(0, "Simple 1"); - assertTrue( q.list().size()==1 ); - assertTrue( q.list().size()==1 ); - assertTrue( q.list().size()==1 ); - q = s.createQuery("from Simple s where s.name=:name"); - q.setCacheRegion("foo"); - q.setCacheable(true); - q.setString("name", "Simple 1"); - assertTrue( q.list().size()==1 ); - simple = (Simple) q.list().get(0); - - q.setString("name", "Simple 2"); - assertTrue( q.list().size()==0 ); - assertTrue( q.list().size()==0 ); - simple.setName("Simple 2"); - assertTrue( q.list().size()==1 ); - assertTrue( q.list().size()==1 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - s.update( simple ); - s.delete(simple); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - q = s.createQuery("from Simple s where s.name=?"); - q.setCacheRegion("foo"); - q.setCacheable(true); - q.setString(0, "Simple 1"); - assertTrue( q.list().size()==0 ); - assertTrue( q.list().size()==0 ); - t.commit(); - s.close(); - } - - @Test - public void testSQLFunctions() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Simple simple = new Simple( Long.valueOf(10) ); - simple.setName("Simple 1"); - s.save( simple ); - - if ( getDialect() instanceof DB2Dialect && !(getDialect() instanceof DerbyDialect) ) { - s.createQuery( "from Simple s where repeat('foo', 3) = 'foofoofoo'" ).list(); - s.createQuery( "from Simple s where repeat(s.name, 3) = 'foofoofoo'" ).list(); - s.createQuery( "from Simple s where repeat( lower(s.name), 3 + (1-1) / 2) = 'foofoofoo'" ).list(); - } - - assertTrue( - s.createQuery( "from Simple s where upper( s.name ) ='SIMPLE 1'" ).list().size()==1 - ); - if ( !(getDialect() instanceof HSQLDialect) ) { - assertTrue( - s.createQuery( - "from Simple s where not( upper( s.name ) ='yada' or 1=2 or 'foo'='bar' or not('foo'='foo') or 'foo' like 'bar' )" - ).list() - .size()==1 - ); - } - if ( !(getDialect() instanceof MySQLDialect) && !(getDialect() instanceof SybaseDialect) && !(getDialect() instanceof SQLServerDialect) && !(getDialect() instanceof MckoiDialect) && !(getDialect() instanceof InterbaseDialect) && !(getDialect() instanceof TimesTenDialect) ) { //My SQL has a funny concatenation operator - assertTrue( - s.createQuery( "from Simple s where lower( s.name || ' foo' ) ='simple 1 foo'" ).list().size()==1 - ); - } - if ( (getDialect() instanceof SybaseDialect) ) { - assertTrue( - s.createQuery( "from Simple s where lower( s.name + ' foo' ) ='simple 1 foo'" ).list().size()==1 - ); - } - if ( (getDialect() instanceof MckoiDialect) || (getDialect() instanceof TimesTenDialect)) { - assertTrue( - s.createQuery( "from Simple s where lower( concat(s.name, ' foo') ) ='simple 1 foo'" ).list().size()==1 - ); - } - - Simple other = new Simple( Long.valueOf(20) ); - other.setName("Simple 2"); - other.setCount(12); - simple.setOther(other); - s.save( other ); - //s.find("from Simple s where s.name ## 'cat|rat|bag'"); - assertTrue( - s.createQuery( "from Simple s where upper( s.other.name ) ='SIMPLE 2'" ).list().size()==1 - ); - assertTrue( - s.createQuery( "from Simple s where not ( upper( s.other.name ) ='SIMPLE 2' )" ).list().size()==0 - ); - assertTrue( - s.createQuery( - "select distinct s from Simple s where ( ( s.other.count + 3 ) = (15*2)/2 and s.count = 69) or ( ( s.other.count + 2 ) / 7 ) = 2" - ).list() - .size()==1 - ); - assertTrue( - s.createQuery( - "select s from Simple s where ( ( s.other.count + 3 ) = (15*2)/2 and s.count = 69) or ( ( s.other.count + 2 ) / 7 ) = 2 order by s.other.count" - ).list() - .size()==1 - ); - Simple min = new Simple( Long.valueOf(30) ); - min.setCount(-1); - s.save( min ); - if ( ! (getDialect() instanceof MySQLDialect) && ! (getDialect() instanceof HSQLDialect) ) { //My SQL has no subqueries - assertTrue( - s.createQuery( "from Simple s where s.count > ( select min(sim.count) from Simple sim )" ) - .list() - .size()==2 - ); - t.commit(); - t = s.beginTransaction(); - assertTrue( - s.createQuery( - "from Simple s where s = some( select sim from Simple sim where sim.count>=0 ) and s.count >= 0" - ).list() - .size()==2 - ); - assertTrue( - s.createQuery( - "from Simple s where s = some( select sim from Simple sim where sim.other.count=s.other.count ) and s.other.count > 0" - ).list() - .size()==1 - ); - } - - Iterator iter = s.createQuery( "select sum(s.count) from Simple s group by s.count having sum(s.count) > 10" ) - .iterate(); - assertTrue( iter.hasNext() ); - assertEquals( Long.valueOf(12), iter.next() ); - assertTrue( !iter.hasNext() ); - if ( ! (getDialect() instanceof MySQLDialect) ) { - iter = s.createQuery( "select s.count from Simple s group by s.count having s.count = 12" ).iterate(); - assertTrue( iter.hasNext() ); - } - - s.createQuery( - "select s.id, s.count, count(t), max(t.date) from Simple s, Simple t where s.count = t.count group by s.id, s.count order by s.count" - ).iterate(); - - Query q = s.createQuery("from Simple s"); - q.setMaxResults(10); - assertTrue( q.list().size()==3 ); - q = s.createQuery("from Simple s"); - q.setMaxResults(1); - assertTrue( q.list().size()==1 ); - q = s.createQuery("from Simple s"); - assertTrue( q.list().size()==3 ); - q = s.createQuery("from Simple s where s.name = ?"); - q.setString(0, "Simple 1"); - assertTrue( q.list().size()==1 ); - q = s.createQuery("from Simple s where s.name = ? and upper(s.name) = ?"); - q.setString(1, "SIMPLE 1"); - q.setString(0, "Simple 1"); - q.setFirstResult(0); - assertTrue( q.iterate().hasNext() ); - q = s.createQuery("from Simple s where s.name = :foo and upper(s.name) = :bar or s.count=:count or s.count=:count + 1"); - q.setParameter("bar", "SIMPLE 1"); - q.setString("foo", "Simple 1"); - q.setInteger("count", 69); - q.setFirstResult(0); - assertTrue( q.iterate().hasNext() ); - q = s.createQuery("select s.id from Simple s"); - q.setFirstResult(1); - q.setMaxResults(2); - iter = q.iterate(); - int i=0; - while ( iter.hasNext() ) { - assertTrue( iter.next() instanceof Long ); - i++; - } - assertTrue(i==2); - q = s.createQuery("select all s, s.other from Simple s where s = :s"); - q.setParameter("s", simple); - assertTrue( q.list().size()==1 ); - - - q = s.createQuery("from Simple s where s.name in (:name_list) and s.count > :count"); - HashSet set = new HashSet(); - set.add("Simple 1"); set.add("foo"); - q.setParameterList( "name_list", set ); - q.setParameter("count", Integer.valueOf( -1 ) ); - assertTrue( q.list().size()==1 ); - - ScrollableResults sr = s.createQuery("from Simple s").scroll(); - sr.next(); - sr.get(0); - sr.close(); - - s.delete(other); - s.delete(simple); - s.delete(min); - t.commit(); - s.close(); - - } - - @Test - public void testBlobClob() throws Exception { - // Sybase does not support ResultSet.getBlob(String) - if ( getDialect() instanceof SybaseDialect || getDialect() instanceof Sybase11Dialect || getDialect() instanceof SybaseASE15Dialect || getDialect() instanceof SybaseAnywhereDialect || getDialect() instanceof TeradataDialect) { - return; - } - Session s = openSession(); - s.beginTransaction(); - Blobber b = new Blobber(); - b.setBlob( s.getLobHelper().createBlob( "foo/bar/baz".getBytes() ) ); - b.setClob( s.getLobHelper().createClob("foo/bar/baz") ); - s.save(b); - //s.refresh(b); - //assertTrue( b.getClob() instanceof ClobImpl ); - s.flush(); - - s.refresh(b); - //b.getBlob().setBytes( 2, "abc".getBytes() ); - b.getClob().getSubString(2, 3); - //b.getClob().setString(2, "abc"); - s.flush(); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) ); - Blobber b2 = new Blobber(); - s.save(b2); - b2.setBlob( b.getBlob() ); - b.setBlob(null); - //assertTrue( b.getClob().getSubString(1, 3).equals("fab") ); - b.getClob().getSubString(1, 6); - //b.getClob().setString(1, "qwerty"); - s.flush(); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) ); - b.setClob( s.getLobHelper().createClob("xcvfxvc xcvbx cvbx cvbx cvbxcvbxcvbxcvb") ); - s.flush(); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) ); - assertTrue( b.getClob().getSubString(1, 7).equals("xcvfxvc") ); - //b.getClob().setString(5, "1234567890"); - s.flush(); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testSqlFunctionAsAlias() throws Exception { - String functionName = locateAppropriateDialectFunctionNameForAliasTest(); - if (functionName == null) { - log.info("Dialect does not list any no-arg functions"); - return; - } - - log.info("Using function named [" + functionName + "] for 'function as alias' test"); - String query = "select " + functionName + " from Simple as " + functionName + " where " + functionName + ".id = 10"; - - Session s = openSession(); - Transaction t = s.beginTransaction(); - Simple simple = new Simple( Long.valueOf(10) ); - simple.setName("Simple 1"); - s.save( simple ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - List result = s.createQuery( query ).list(); - assertTrue( result.size() == 1 ); - assertTrue(result.get(0) instanceof Simple); - s.delete( result.get(0) ); - t.commit(); - s.close(); - } - - private String locateAppropriateDialectFunctionNameForAliasTest() { - for (Iterator itr = getDialect().getFunctions().entrySet().iterator(); itr.hasNext(); ) { - final Map.Entry entry = (Map.Entry) itr.next(); - final SQLFunction function = (SQLFunction) entry.getValue(); - if ( !function.hasArguments() && !function.hasParenthesesIfNoArguments() ) { - return (String) entry.getKey(); - } - } - return null; - } - - @Test - public void testCachedQueryOnInsert() throws Exception { - Session s = openSession(); - Transaction t = s.beginTransaction(); - Simple simple = new Simple( Long.valueOf(10) ); - simple.setName("Simple 1"); - s.save( simple ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Query q = s.createQuery("from Simple s"); - List list = q.setCacheable(true).list(); - assertTrue( list.size()==1 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - q = s.createQuery("from Simple s"); - list = q.setCacheable(true).list(); - assertTrue( list.size()==1 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Simple simple2 = new Simple( Long.valueOf(12) ); - simple2.setCount(133); - s.save( simple2 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - q = s.createQuery("from Simple s"); - list = q.setCacheable(true).list(); - assertTrue( list.size()==2 ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - q = s.createQuery("from Simple s"); - list = q.setCacheable(true).list(); - assertTrue( list.size()==2 ); - Iterator i = list.iterator(); - while ( i.hasNext() ) s.delete( i.next() ); - t.commit(); - s.close(); - - } - -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/SQLLoaderTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/SQLLoaderTest.java deleted file mode 100644 index 50c85fc14f..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/SQLLoaderTest.java +++ /dev/null @@ -1,781 +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 . - */ - -//$Id: SQLLoaderTest.java 11383 2007-04-02 15:34:02Z steve.ebersole@jboss.com $ -package org.hibernate.orm.test.legacy; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.hibernate.HibernateException; -import org.hibernate.query.NativeQuery; -import org.hibernate.query.Query; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.cfg.AvailableSettings; -import org.hibernate.cfg.Configuration; -import org.hibernate.dialect.Dialect; -import org.hibernate.dialect.HSQLDialect; -import org.hibernate.dialect.MySQLDialect; -import org.hibernate.dialect.PostgreSQL81Dialect; -import org.hibernate.dialect.PostgreSQLDialect; -import org.hibernate.dialect.TimesTenDialect; - -import org.hibernate.testing.DialectCheck; -import org.hibernate.testing.FailureExpected; -import org.hibernate.testing.RequiresDialectFeature; -import org.hibernate.testing.SkipForDialect; -import org.hibernate.testing.TestForIssue; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -public class SQLLoaderTest extends LegacyTestCase { - static int nextInt = 1; - static long nextLong = 1; - - @Override - public void configure(Configuration cfg) { - super.configure( cfg ); - - cfg.setProperty( AvailableSettings.KEYWORD_AUTO_QUOTING_ENABLED, "true" ); - } - - @Override - public String[] getMappings() { - return new String[] { - "legacy/ABC.hbm.xml", - "legacy/Category.hbm.xml", - "legacy/Simple.hbm.xml", - "legacy/Fo.hbm.xml", - "legacy/SingleSeveral.hbm.xml", - "legacy/Componentizable.hbm.xml", - "legacy/CompositeIdId.hbm.xml" - }; - } - - @Test - public void testTS() throws Exception { - Session session = openSession(); - Transaction txn = session.beginTransaction(); - Simple sim = new Simple( Long.valueOf(1) ); - sim.setDate( new Date() ); - session.save( sim ); - Query q = session.createNativeQuery( "select {sim.*} from SimpleEntity {sim} where {sim}.date_ = ?" ).addEntity( "sim", Simple.class ); - q.setTimestamp( 0, sim.getDate() ); - assertTrue ( q.list().size()==1 ); - session.delete(sim); - txn.commit(); - session.close(); - } - - @Test - public void testFindBySQLStar() throws HibernateException, SQLException { - Session session = openSession(); - session.beginTransaction(); - for ( Object entity : session.createQuery( "from Assignable" ).list() ) { - session.delete( entity ); - } - for ( Object entity : session.createQuery( "from Category" ).list() ) { - session.delete( entity ); - } - for ( Object entity : session.createQuery( "from Simple" ).list() ) { - session.delete( entity ); - } - for ( Object entity : session.createQuery( "from A" ).list() ) { - session.delete( entity ); - } - - Category s = new Category(); - s.setName(String.valueOf(nextLong++)); - session.save( s ); - - Simple simple = new Simple( Long.valueOf(nextLong++) ); - simple.init(); - session.save( simple ); - - A a = new A(); - session.save(a); - - B b = new B(); - session.save( b ); - session.flush(); - - session.createNativeQuery( "select {category.*} from category {category}" ).addEntity( "category", Category.class ).list(); - session.createNativeQuery( "select {simple.*} from SimpleEntity {simple}" ).addEntity( "simple", Simple.class ).list(); - session.createNativeQuery( "select {a.*} from TA {a}" ).addEntity( "a", A.class ).list(); - - session.getTransaction().commit(); - session.close(); - } - - @Test - public void testFindBySQLProperties() throws HibernateException, SQLException { - Session session = openSession(); - session.beginTransaction(); - for ( Object entity : session.createQuery( "from Category" ).list() ) { - session.delete( entity ); - } - - Category s = new Category(); - s.setName( String.valueOf( nextLong++ ) ); - session.save( s ); - - s = new Category(); - s.setName( "WannaBeFound" ); - session.flush(); - - Query query = session.createNativeQuery( "select {category.*} from category {category} where {category}.name = :name" ) - .addEntity( "category", Category.class ); - - query.setProperties( s ); - //query.setParameter("name", s.getName()); - - query.list(); - - query = session.createNativeQuery( "select {category.*} from category {category} where {category}.name in (:names)" ) - .addEntity( "category", Category.class ); - String[] str = new String[] { "WannaBeFound", "NotThere" }; - query.setParameterList( "names", str ); - query.uniqueResult(); - - query = session.createNativeQuery( "select {category.*} from category {category} where {category}.name in :names" ) - .addEntity( "category", Category.class ); - query.setParameterList("names", str); - query.uniqueResult(); - - query = session.createNativeQuery( "select {category.*} from category {category} where {category}.name in (:names)" ) - .addEntity( "category", Category.class ); - str = new String[] { "WannaBeFound" }; - query.setParameterList( "names", str ); - query.uniqueResult(); - - query = session.createNativeQuery( "select {category.*} from category {category} where {category}.name in :names" ) - .addEntity( "category", Category.class ); - query.setParameterList( "names", str ); - query.uniqueResult(); - - session.getTransaction().commit(); - session.close(); - } - - @Test - public void testFindBySQLAssociatedObjects() throws HibernateException, SQLException { - Session s = openSession(); - s.beginTransaction(); - for ( Object entity : s.createQuery( "from Assignable" ).list() ) { - s.delete( entity ); - } - for ( Object entity : s.createQuery( "from Category" ).list() ) { - s.delete( entity ); - } - - Category c = new Category(); - c.setName("NAME"); - Assignable assn = new Assignable(); - assn.setId("i.d."); - List l = new ArrayList(); - l.add(c); - assn.setCategories(l); - c.setAssignable(assn); - s.save(assn); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - List list = s.createNativeQuery( "select {category.*} from category {category}" ).addEntity( "category", Category.class ).list(); - list.get(0); - s.getTransaction().commit(); - s.close(); - - if ( getDialect() instanceof MySQLDialect ) { - return; - } - - s = openSession(); - s.beginTransaction(); - - Query query = s.getNamedQuery("namedsql"); - assertNotNull(query); - list = query.list(); - assertNotNull(list); - - Object[] values = (Object[]) list.get(0); - assertNotNull(values[0]); - assertNotNull(values[1]); - assertTrue("wrong type: " + values[0].getClass(), values[0] instanceof Category); - assertTrue("wrong type: " + values[1].getClass(), values[1] instanceof Assignable); - - s.getTransaction().commit(); - s.close(); - - } - - @Test - @SkipForDialect( MySQLDialect.class ) - public void testPropertyResultSQL() throws HibernateException, SQLException { - Session s = openSession(); - s.beginTransaction(); - for ( Object entity : s.createQuery( "from Assignable" ).list() ) { - s.delete( entity ); - } - for ( Object entity : s.createQuery( "from Category" ).list() ) { - s.delete( entity ); - } - - Category c = new Category(); - c.setName("NAME"); - Assignable assn = new Assignable(); - assn.setId("i.d."); - List l = new ArrayList(); - l.add(c); - assn.setCategories(l); - c.setAssignable(assn); - s.save(assn); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Query query = s.getNamedQuery("nonaliasedsql"); - assertNotNull(query); - List list = query.list(); - assertNotNull(list); - assertTrue(list.get(0) instanceof Category); - s.getTransaction().commit(); - s.close(); - - } - - @Test - public void testFindBySQLMultipleObject() throws HibernateException, SQLException { - Session s = openSession(); - s.beginTransaction(); - for ( Object entity : s.createQuery( "from Assignable" ).list() ) { - s.delete( entity ); - } - for ( Object entity : s.createQuery( "from Category" ).list() ) { - s.delete( entity ); - } - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Category c = new Category(); - c.setName("NAME"); - Assignable assn = new Assignable(); - assn.setId("i.d."); - List l = new ArrayList(); - l.add(c); - assn.setCategories(l); - c.setAssignable(assn); - s.save(assn); - s.flush(); - c = new Category(); - c.setName("NAME2"); - assn = new Assignable(); - assn.setId("i.d.2"); - l = new ArrayList(); - l.add(c); - assn.setCategories(l); - c.setAssignable(assn); - s.save(assn); - s.flush(); - - assn = new Assignable(); - assn.setId("i.d.3"); - s.save(assn); - s.getTransaction().commit(); - s.close(); - - if ( getDialect() instanceof MySQLDialect ) { - return; - } - - s = openSession(); - s.beginTransaction(); - String sql = "select {category.*}, {assignable.*} from category {category}, \"assign-able\" {assignable}"; - - List list = s.createNativeQuery( sql ).addEntity( "category", Category.class ).addEntity( "assignable", Assignable.class ).list(); - - assertTrue(list.size() == 6); // crossproduct of 2 categories x 3 assignables - assertTrue(list.get(0) instanceof Object[]); - s.getTransaction().commit(); - s.close(); - } - - @Test - public void testFindBySQLParameters() throws HibernateException, SQLException { - Session s = openSession(); - s.beginTransaction(); - for ( Object entity : s.createQuery( "from Assignable" ).list() ) { - s.delete( entity ); - } - for ( Object entity : s.createQuery( "from Category" ).list() ) { - s.delete( entity ); - } - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Category c = new Category(); - c.setName("Good"); - Assignable assn = new Assignable(); - assn.setId("i.d."); - List l = new ArrayList(); - l.add(c); - assn.setCategories(l); - c.setAssignable(assn); - s.save(assn); - s.flush(); - c = new Category(); - c.setName("Best"); - assn = new Assignable(); - assn.setId("i.d.2"); - l = new ArrayList(); - l.add(c); - assn.setCategories(l); - c.setAssignable(assn); - s.save(assn); - s.flush(); - c = new Category(); - c.setName("Better"); - assn = new Assignable(); - assn.setId("i.d.7"); - l = new ArrayList(); - l.add(c); - assn.setCategories(l); - c.setAssignable(assn); - s.save(assn); - s.flush(); - - assn = new Assignable(); - assn.setId("i.d.3"); - s.save(assn); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - Query basicParam = s.createNativeQuery( "select {category.*} from category {category} where {category}.name = 'Best'" ) - .addEntity( "category", Category.class ); - List list = basicParam.list(); - assertEquals(1, list.size()); - - Query unnamedParam = s.createNativeQuery( "select {category.*} from category {category} where {category}.name = ? or {category}.name = ?" ) - .addEntity( "category", Category.class ); - unnamedParam.setString(0, "Good"); - unnamedParam.setString(1, "Best"); - list = unnamedParam.list(); - assertEquals(2, list.size()); - - Query namedParam = s.createNativeQuery( "select {category.*} from category {category} where ({category}.name=:firstCat or {category}.name=:secondCat)" ) - .addEntity( "category", Category.class); - namedParam.setString("firstCat", "Better"); - namedParam.setString("secondCat", "Best"); - list = namedParam.list(); - assertEquals(2, list.size()); - s.getTransaction().commit(); - s.close(); - } - - @Test - @SkipForDialect( { HSQLDialect.class, PostgreSQL81Dialect.class, PostgreSQLDialect.class } ) - public void testEscapedJDBC() throws HibernateException, SQLException { - Session session = openSession(); - session.beginTransaction(); - for ( Object entity : session.createQuery( "from A" ).list() ) { - session.delete( entity ); - } - A savedA = new A(); - savedA.setName("Max"); - session.save( savedA ); - - B savedB = new B(); - session.save( savedB ); - session.flush(); - - int count = session.createQuery("from A").list().size(); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.beginTransaction(); - - Query query; - if( getDialect() instanceof TimesTenDialect) { - // TimesTen does not permit general expressions (like UPPER) in the second part of a LIKE expression, - // so we execute a similar test - query = session.createNativeQuery("select identifier_column as {a.id}, clazz_discriminata as {a.class}, count_ as {a.count}, name as {a.name} from TA where {fn ucase(name)} like 'MAX'" ) - .addEntity( "a", A.class ); - } - else { - query = session.createNativeQuery( "select identifier_column as {a.id}, clazz_discriminata as {a.class}, count_ as {a.count}, name as {a.name} from TA where {fn ucase(name)} like {fn ucase('max')}" ) - .addEntity( "a", A.class ); - } - List list = query.list(); - - assertNotNull(list); - assertEquals( 1, list.size() ); - session.getTransaction().commit(); - session.close(); - } - - @Test - public void testDoubleAliasing() throws HibernateException, SQLException { - Session session = openSession(); - session.beginTransaction(); - for ( Object entity : session.createQuery( "from A" ).list() ) { - session.delete( entity ); - } - A savedA = new A(); - savedA.setName("Max"); - session.save( savedA ); - - B savedB = new B(); - session.save( savedB ); - session.flush(); - - int count = session.createQuery("from A").list().size(); - session.getTransaction().commit(); - session.close(); - - session = openSession(); - session.beginTransaction(); - String sql = "select a.identifier_column as {a1.id}, " + - " a.clazz_discriminata as {a1.class}, " + - " a.count_ as {a1.count}, " + - " a.name as {a1.name}, " + - " b.identifier_column as {a2.id}, " + - " b.clazz_discriminata as {a2.class}, " + - " b.count_ as {a2.count}, " + - " b.name as {a2.name} " + - "from TA a, TA b " + - "where a.identifier_column = b.identifier_column"; - Query query = session.createNativeQuery( sql ).addEntity( "a1", A.class ).addEntity( "a2", A.class ); - List list = query.list(); - - assertNotNull(list); - assertEquals( 2, list.size() ); - session.getTransaction().commit(); - session.close(); - } - - @Test - public void testEmbeddedCompositeProperties() throws HibernateException, SQLException { - Session session = openSession(); - session.beginTransaction(); - Single s = new Single(); - s.setId("my id"); - s.setString("string 1"); - session.save(s); - session.getTransaction().commit(); - - session = openSession(); - session.beginTransaction(); - - NativeQuery query = session.createNativeQuery( "select {sing.*} from Single {sing}" ).addEntity( "sing", Single.class ); - List list = query.list(); - assertTrue(list.size()==1); - - session.clear(); - - query = session.createNativeQuery( "select {sing.*} from Single {sing} where sing.id = ?" ).addEntity( "sing", Single.class ); - query.setString(0, "my id"); - list = query.list(); - assertTrue(list.size()==1); - - session.clear(); - - query = session.createNativeQuery( "select s.id as {sing.id}, s.string_ as {sing.string}, s.prop as {sing.prop} from Single s where s.id = ?" ) - .addEntity( "sing", Single.class ); - query.setString(0, "my id"); - list = query.list(); - assertTrue(list.size()==1); - - session.clear(); - - query = session.createNativeQuery( "select s.id as {sing.id}, s.string_ as {sing.string}, s.prop as {sing.prop} from Single s where s.id = ?" ) - .addEntity( "sing", Single.class ); - query.setString(0, "my id"); - list = query.list(); - - assertTrue(list.size()==1); - - session.getTransaction().commit(); - session.close(); - } - - @Test - @FailureExpected( jiraKey = "unknown" ) - public void testReturnPropertyComponentRename() throws HibernateException, SQLException { - // failure expected because this was a regression introduced previously which needs to get tracked down. - Componentizable componentizable = setupComponentData(); - - Session session = openSession(); - session.beginTransaction(); - Query namedQuery = session.getNamedQuery("queryComponentWithOtherColumn"); - List list = namedQuery.list(); - - assertEquals(1, list.size()); - assertEquals( "flakky comp", ( (Componentizable) list.get(0) ).getComponent().getName() ); - - session.clear(); - session.delete(componentizable); - session.getTransaction().commit(); - session.close(); - } - - @Test - public void testComponentStar() throws HibernateException, SQLException { - componentTest("select {comp.*} from Componentizable comp"); - } - - @Test - public void testComponentNoStar() throws HibernateException, SQLException { - componentTest("select comp.id as {comp.id}, comp.nickName as {comp.nickName}, comp.name as {comp.component.name}, comp.subName as {comp.component.subComponent.subName}, comp.subName1 as {comp.component.subComponent.subName1} from Componentizable comp"); - } - - private void componentTest(String sql) throws SQLException { - Componentizable c = setupComponentData(); - - Session session = openSession(); - session.beginTransaction(); - NativeQuery q = session.createNativeQuery( sql ).addEntity( "comp", Componentizable.class ); - List list = q.list(); - assertEquals( list.size(), 1 ); - - Componentizable co = (Componentizable) list.get(0); - assertEquals( c.getNickName(), co.getNickName() ); - assertEquals( c.getComponent().getName(), co.getComponent().getName() ); - assertEquals( c.getComponent().getSubComponent().getSubName(), co.getComponent().getSubComponent().getSubName() ); - - session.delete( co ); - session.getTransaction().commit(); - session.close(); - } - - private Componentizable setupComponentData() throws SQLException { - Session session = sessionFactory().openSession(); - session.beginTransaction(); - - Componentizable c = new Componentizable(); - c.setNickName( "Flacky" ); - Component component = new Component(); - component.setName("flakky comp"); - SubComponent subComponent = new SubComponent(); - subComponent.setSubName("subway"); - component.setSubComponent( subComponent ); - - c.setComponent( component ); - - session.save( c ); - session.getTransaction().commit(); - session.clear(); - - return c; - } - - @Test - @SkipForDialect( MySQLDialect.class ) - public void testFindSimpleBySQL() throws Exception { - Session session = openSession(); - session.beginTransaction(); - Category s = new Category(); - s.setName(String.valueOf(nextLong++)); - session.save(s); - session.flush(); - - Query query = session.createNativeQuery( "select s.category_key_col as {category.id}, s.name as {category.name}, s.\"assign-able-id\" as {category.assignable} from {category} s" ) - .addEntity( "category", Category.class ); - List list = query.list(); - - assertNotNull( list ); - assertTrue( list.size() > 0 ); - assertTrue(list.get(0) instanceof Category); - session.getTransaction().commit(); - session.close(); - // How do we handle objects with composite id's ? (such as Single) - } - - @Test - public void testFindBySQLSimpleByDiffSessions() throws Exception { - Session session = openSession(); - session.beginTransaction(); - Category s = new Category(); - s.setName(String.valueOf(nextLong++)); - session.save(s); - session.getTransaction().commit(); - session.close(); - - if ( getDialect() instanceof MySQLDialect ) { - return; - } - - session = openSession(); - session.beginTransaction(); - - Query query = session.createNativeQuery( "select s.category_key_col as {category.id}, s.name as {category.name}, s.\"assign-able-id\" as {category.assignable} from {category} s" ) - .addEntity( "category", Category.class ); - List list = query.list(); - - assertNotNull( list ); - assertTrue( list.size() > 0 ); - assertTrue( list.get( 0 ) instanceof Category ); - - // How do we handle objects that does not have id property (such as Simple ?) - // How do we handle objects with composite id's ? (such as Single) - session.getTransaction().commit(); - session.close(); - } - - @Test - public void testFindBySQLDiscriminatedSameSession() throws Exception { - Session session = openSession(); - session.beginTransaction(); - for ( Object entity : session.createQuery( "from A" ).list() ) { - session.delete( entity ); - } - A savedA = new A(); - session.save(savedA); - - B savedB = new B(); - session.save(savedB); - session.flush(); - - Query query = session.createNativeQuery( "select identifier_column as {a.id}, clazz_discriminata as {a.class}, name as {a.name}, count_ as {a.count} from TA {a}" ) - .addEntity( "a", A.class ); - List list = query.list(); - - assertNotNull(list); - assertEquals(2, list.size()); - - A a1 = (A) list.get(0); - A a2 = (A) list.get(1); - - assertTrue((a2 instanceof B) || (a1 instanceof B)); - assertFalse( a1 instanceof B && a2 instanceof B ); - - if (a1 instanceof B) { - assertSame(a1, savedB); - assertSame(a2, savedA); - } - else { - assertSame(a2, savedB); - assertSame(a1, savedA); - } - - session.clear(); - List list2 = session.getNamedQuery("propertyResultDiscriminator").list(); - assertEquals(2, list2.size()); - - session.getTransaction().commit(); - session.close(); - } - - @Test - public void testFindBySQLDiscriminatedDiffSession() throws Exception { - Session session = openSession(); - session.beginTransaction(); - for ( Object entity : session.createQuery( "from A" ).list() ) { - session.delete( entity ); - } - A savedA = new A(); - session.save(savedA); - - B savedB = new B(); - session.save(savedB); - session.getTransaction().commit(); - int count = session.createQuery("from A").list().size(); - session.close(); - - session = openSession(); - session.beginTransaction(); - Query query = session.createNativeQuery( "select identifier_column as {a.id}, clazz_discriminata as {a.class}, count_ as {a.count}, name as {a.name} from TA" ) - .addEntity( "a", A.class ); - List list = query.list(); - - assertNotNull(list); - assertEquals(count, list.size()); - session.getTransaction().commit(); - session.close(); - } - - public static class DoubleQuoteDialect implements DialectCheck { - @Override - public boolean isMatch(Dialect dialect) { - return '"' == dialect.openQuote() && '"' == dialect.closeQuote(); - } - } - - @Test - @TestForIssue( jiraKey = "HHH-21" ) - // because the XML mapping defines the loader for CompositeIdId using a column name that needs to be quoted - @RequiresDialectFeature( DoubleQuoteDialect.class ) - public void testCompositeIdId() throws HibernateException, SQLException { - Session s = openSession(); - s.beginTransaction(); - CompositeIdId id = new CompositeIdId(); - id.setName("Max"); - id.setUser( "c64" ); - id.setId("games"); - s.save(id); - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - // having a composite id with one property named id works since the map used by sqlloader to map names to properties handles it. - // NOTE : SYSTEM is an ANSI SQL defined keyword, so it gets quoted; so it needs to get quoted here too - String sql = String.format( - "select %1$s as {c.user}, " + - " id as {c.id}, name as {c.name}, " + - " foo as {c.composite.foo}, " + - " bar as {c.composite.bar} " + - "from CompositeIdId " + - "where %1$s=? and id=?", - getDialect().openQuote() + "user" + getDialect().closeQuote() - ); - - NativeQuery query = s.createNativeQuery( sql ).addEntity( "c", CompositeIdId.class ); - query.setString(0, "c64"); - query.setString(1, "games"); - - CompositeIdId id2 = (CompositeIdId) query.uniqueResult(); - check(id, id2); - - s.getTransaction().commit(); - s.close(); - - s = openSession(); - s.beginTransaction(); - CompositeIdId useForGet = new CompositeIdId(); - useForGet.setUser( "c64" ); - useForGet.setId("games"); - // this doesn't work since the verification does not take column span into respect! - CompositeIdId getted = (CompositeIdId) s.get(CompositeIdId.class, useForGet); - check(id,getted); - s.getTransaction().commit(); - s.close(); - } - - private void check(CompositeIdId id, CompositeIdId id2) { - assertEquals(id,id2); - assertEquals(id.getName(), id2.getName()); - assertEquals(id.getId(), id2.getId()); - assertEquals(id.getUser(), id2.getUser()); - } -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/StatisticsTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/legacy/StatisticsTest.java deleted file mode 100644 index f0d21f20af..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/legacy/StatisticsTest.java +++ /dev/null @@ -1,61 +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 . - */ -package org.hibernate.orm.test.legacy; - -import org.hibernate.query.Query; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; -import org.hibernate.stat.Statistics; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * @author Emmanuel Bernard - */ -public class StatisticsTest extends LegacyTestCase { - @Override - public String[] getMappings() { - return new String[] { "legacy/ABC.hbm.xml", "legacy/ABCExtends.hbm.xml" }; - } - - @Test - public void testSessionStats() throws Exception { - SessionFactory sf = sessionFactory(); - Statistics stats = sf.getStatistics(); - boolean isStats = stats.isStatisticsEnabled(); - stats.clear(); - stats.setStatisticsEnabled(true); - Session s = sf.openSession(); - assertEquals( 1, stats.getSessionOpenCount() ); - s.close(); - assertEquals( 1, stats.getSessionCloseCount() ); - s = sf.openSession(); - Transaction tx = s.beginTransaction(); - A a = new A(); - a.setName("mya"); - s.save(a); - a.setName("b"); - tx.commit(); - s.close(); - assertEquals( 1, stats.getFlushCount() ); - s = sf.openSession(); - tx = s.beginTransaction(); - String hql = "from " + A.class.getName(); - Query q = s.createQuery(hql); - q.list(); - tx.commit(); - s.close(); - assertEquals(1, stats.getQueryExecutionCount() ); - assertEquals(1, stats.getQueryStatistics(hql).getExecutionCount() ); - - stats.setStatisticsEnabled(isStats); - } - -} diff --git a/hibernate-core/src/test_legacy/org/hibernate/test/readonly/ReadOnlyCriteriaQueryTest.java b/hibernate-core/src/test_legacy/org/hibernate/test/readonly/ReadOnlyCriteriaQueryTest.java deleted file mode 100644 index d5846aa5f6..0000000000 --- a/hibernate-core/src/test_legacy/org/hibernate/test/readonly/ReadOnlyCriteriaQueryTest.java +++ /dev/null @@ -1,1287 +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 . - */ -package org.hibernate.test.readonly; - -import java.util.List; - -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.criterion.DetachedCriteria; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.Property; -import org.hibernate.criterion.Restrictions; -import org.hibernate.criterion.Subqueries; -import org.hibernate.dialect.SybaseASE15Dialect; -import org.hibernate.internal.util.SerializationHelper; -import org.hibernate.proxy.HibernateProxy; -import org.hibernate.proxy.LazyInitializer; -import org.hibernate.testing.SkipForDialect; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -/** - * (adapted from org.hibernate.test.criteria.CriteriaQueryTest by Gavin King) - * - * @author Gail Badner - */ -public class ReadOnlyCriteriaQueryTest extends AbstractReadOnlyTest { - @Override - public String[] getMappings() { - return new String[] { "readonly/Enrolment.hbm.xml" }; - } - - @Override - public void configure(Configuration cfg) { - super.configure( cfg ); - cfg.setProperty( Environment.USE_QUERY_CACHE, "true" ); - cfg.setProperty( Environment.CACHE_REGION_PREFIX, "criteriaquerytest" ); - cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, "true" ); - cfg.setProperty( Environment.GENERATE_STATISTICS, "true" ); - } - - @Test - public void testModifiableSessionDefaultCriteria() { - clearCounts(); - - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.persist(course); - - Course coursePreferred = new Course(); - coursePreferred.setCourseCode( "JBOSS" ); - coursePreferred.setDescription( "JBoss" ); - s.persist( coursePreferred ); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse( coursePreferred ); - s.persist(gavin); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add( enrolment ); - s.persist( enrolment ); - - t.commit(); - s.close(); - - assertInsertCount( 4 ); - assertUpdateCount( 0 ); - clearCounts(); - - s = openSession(); - t = s.beginTransaction(); - Criteria criteria = s.createCriteria( Student.class ); - assertFalse( s.isDefaultReadOnly() ); - assertFalse( criteria.isReadOnlyInitialized() ); - assertFalse( criteria.isReadOnly() ); - gavin = ( Student ) criteria.uniqueResult(); - assertFalse( s.isDefaultReadOnly() ); - assertFalse( criteria.isReadOnlyInitialized() ); - assertFalse( criteria.isReadOnly() ); - assertFalse( s.isReadOnly( gavin ) ); - assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - checkProxyReadOnly( s, gavin.getPreferredCourse(), false ); - assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - Hibernate.initialize( gavin.getPreferredCourse() ); - assertTrue( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - checkProxyReadOnly( s, gavin.getPreferredCourse(), false ); - assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) ); - Hibernate.initialize( gavin.getEnrolments() ); - assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) ); - assertEquals( 1, gavin.getEnrolments().size() ); - enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next(); - assertFalse( s.isReadOnly( enrolment ) ); - assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - Hibernate.initialize( enrolment.getCourse() ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - s.delete(gavin.getPreferredCourse()); - s.delete(gavin); - s.delete( enrolment.getCourse() ); - s.delete(enrolment); - t.commit(); - s.close(); - - assertUpdateCount( 1 ); - assertDeleteCount( 4 ); - } - - @Test - public void testModifiableSessionReadOnlyCriteria() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.persist(course); - - Course coursePreferred = new Course(); - coursePreferred.setCourseCode( "JBOSS" ); - coursePreferred.setDescription( "JBoss" ); - s.persist( coursePreferred ); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse( coursePreferred ); - s.persist(gavin); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add( enrolment ); - s.persist( enrolment ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Criteria criteria = s.createCriteria( Student.class ).setReadOnly( true ); - assertFalse( s.isDefaultReadOnly() ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertTrue( criteria.isReadOnly() ); - gavin = ( Student ) criteria.uniqueResult(); - assertFalse( s.isDefaultReadOnly() ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertTrue( criteria.isReadOnly() ); - assertTrue( s.isReadOnly( gavin ) ); - assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - checkProxyReadOnly( s, gavin.getPreferredCourse(), true ); - assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - Hibernate.initialize( gavin.getPreferredCourse() ); - assertTrue( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - checkProxyReadOnly( s, gavin.getPreferredCourse(), true ); - assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) ); - Hibernate.initialize( gavin.getEnrolments() ); - assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) ); - assertEquals( 1, gavin.getEnrolments().size() ); - enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next(); - assertFalse( s.isReadOnly( enrolment ) ); - assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - Hibernate.initialize( enrolment.getCourse() ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - s.delete(gavin.getPreferredCourse()); - s.delete(gavin); - s.delete( enrolment.getCourse() ); - s.delete(enrolment); - t.commit(); - s.close(); - } - - @Test - public void testModifiableSessionModifiableCriteria() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.persist(course); - - Course coursePreferred = new Course(); - coursePreferred.setCourseCode( "JBOSS" ); - coursePreferred.setDescription( "JBoss" ); - s.persist( coursePreferred ); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse( coursePreferred ); - s.persist(gavin); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add( enrolment ); - s.persist( enrolment ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - Criteria criteria = s.createCriteria( Student.class ); - assertFalse( s.isDefaultReadOnly() ); - assertFalse( criteria.isReadOnlyInitialized() ); - assertFalse( criteria.isReadOnly() ); - criteria.setReadOnly( false ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertFalse( criteria.isReadOnly() ); - gavin = ( Student ) criteria.uniqueResult(); - assertFalse( s.isDefaultReadOnly() ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertFalse( criteria.isReadOnly() ); - assertFalse( s.isReadOnly( gavin ) ); - assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - checkProxyReadOnly( s, gavin.getPreferredCourse(), false ); - assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - Hibernate.initialize( gavin.getPreferredCourse() ); - assertTrue( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - checkProxyReadOnly( s, gavin.getPreferredCourse(), false ); - assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) ); - Hibernate.initialize( gavin.getEnrolments() ); - assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) ); - assertEquals( 1, gavin.getEnrolments().size() ); - enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next(); - assertFalse( s.isReadOnly( enrolment ) ); - assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - Hibernate.initialize( enrolment.getCourse() ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - s.delete(gavin.getPreferredCourse()); - s.delete(gavin); - s.delete( enrolment.getCourse() ); - s.delete(enrolment); - t.commit(); - s.close(); - } - - @Test - public void testReadOnlySessionDefaultCriteria() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.persist(course); - - Course coursePreferred = new Course(); - coursePreferred.setCourseCode( "JBOSS" ); - coursePreferred.setDescription( "JBoss" ); - s.persist( coursePreferred ); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse( coursePreferred ); - s.persist(gavin); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add( enrolment ); - s.persist( enrolment ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - s.setDefaultReadOnly( true ); - Criteria criteria = s.createCriteria( Student.class ); - assertTrue( s.isDefaultReadOnly() ); - assertFalse( criteria.isReadOnlyInitialized() ); - assertTrue( criteria.isReadOnly() ); - gavin = ( Student ) criteria.uniqueResult(); - assertTrue( s.isDefaultReadOnly() ); - assertFalse( criteria.isReadOnlyInitialized() ); - assertTrue( criteria.isReadOnly() ); - assertTrue( s.isReadOnly( gavin ) ); - assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - checkProxyReadOnly( s, gavin.getPreferredCourse(), true ); - assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - Hibernate.initialize( gavin.getPreferredCourse() ); - assertTrue( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - checkProxyReadOnly( s, gavin.getPreferredCourse(), true ); - assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) ); - Hibernate.initialize( gavin.getEnrolments() ); - assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) ); - assertEquals( 1, gavin.getEnrolments().size() ); - enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next(); - assertTrue( s.isReadOnly( enrolment ) ); - assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), true ); - Hibernate.initialize( enrolment.getCourse() ); - checkProxyReadOnly( s, enrolment.getCourse(), true ); - s.delete(gavin.getPreferredCourse()); - s.delete(gavin); - s.delete( enrolment.getCourse() ); - s.delete(enrolment); - t.commit(); - s.close(); - } - - @Test - public void testReadOnlySessionReadOnlyCriteria() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.persist(course); - - Course coursePreferred = new Course(); - coursePreferred.setCourseCode( "JBOSS" ); - coursePreferred.setDescription( "JBoss" ); - s.persist( coursePreferred ); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse( coursePreferred ); - s.persist(gavin); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add( enrolment ); - s.persist( enrolment ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - s.setDefaultReadOnly( true ); - Criteria criteria = s.createCriteria( Student.class ); - assertTrue( s.isDefaultReadOnly() ); - assertFalse( criteria.isReadOnlyInitialized() ); - assertTrue( criteria.isReadOnly() ); - criteria.setReadOnly( true ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertTrue( criteria.isReadOnly() ); - gavin = ( Student ) criteria.uniqueResult(); - assertTrue( s.isDefaultReadOnly() ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertTrue( criteria.isReadOnly() ); - assertTrue( s.isReadOnly( gavin ) ); - assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - checkProxyReadOnly( s, gavin.getPreferredCourse(), true ); - assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - Hibernate.initialize( gavin.getPreferredCourse() ); - assertTrue( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - checkProxyReadOnly( s, gavin.getPreferredCourse(), true ); - assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) ); - Hibernate.initialize( gavin.getEnrolments() ); - assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) ); - assertEquals( 1, gavin.getEnrolments().size() ); - enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next(); - assertTrue( s.isReadOnly( enrolment ) ); - assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), true ); - Hibernate.initialize( enrolment.getCourse() ); - checkProxyReadOnly( s, enrolment.getCourse(), true ); - s.delete(gavin.getPreferredCourse()); - s.delete(gavin); - s.delete( enrolment.getCourse() ); - s.delete(enrolment); - t.commit(); - s.close(); - } - - @Test - public void testReadOnlySessionModifiableCriteria() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.persist(course); - - Course coursePreferred = new Course(); - coursePreferred.setCourseCode( "JBOSS" ); - coursePreferred.setDescription( "JBoss" ); - s.persist( coursePreferred ); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse( coursePreferred ); - s.persist(gavin); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add( enrolment ); - s.persist( enrolment ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - s.setDefaultReadOnly( true ); - Criteria criteria = s.createCriteria( Student.class ); - assertTrue( s.isDefaultReadOnly() ); - assertFalse( criteria.isReadOnlyInitialized() ); - assertTrue( criteria.isReadOnly() ); - criteria.setReadOnly( false ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertFalse( criteria.isReadOnly() ); - gavin = ( Student ) criteria.uniqueResult(); - assertTrue( s.isDefaultReadOnly() ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertFalse( criteria.isReadOnly() ); - assertFalse( s.isReadOnly( gavin ) ); - assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - checkProxyReadOnly( s, gavin.getPreferredCourse(), false ); - assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - Hibernate.initialize( gavin.getPreferredCourse() ); - assertTrue( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - checkProxyReadOnly( s, gavin.getPreferredCourse(), false); - assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) ); - Hibernate.initialize( gavin.getEnrolments() ); - assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) ); - assertEquals( 1, gavin.getEnrolments().size() ); - enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next(); - assertTrue( s.isReadOnly( enrolment ) ); - assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), true ); - Hibernate.initialize( enrolment.getCourse() ); - checkProxyReadOnly( s, enrolment.getCourse(), true ); - s.delete(gavin.getPreferredCourse()); - s.delete(gavin); - s.delete( enrolment.getCourse() ); - s.delete(enrolment); - t.commit(); - s.close(); - } - - @Test - public void testReadOnlyCriteriaReturnsModifiableExistingEntity() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.persist(course); - - Course coursePreferred = new Course(); - coursePreferred.setCourseCode( "JBOSS" ); - coursePreferred.setDescription( "JBoss" ); - s.persist( coursePreferred ); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse( coursePreferred ); - s.persist(gavin); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add( enrolment ); - s.persist( enrolment ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - assertFalse( s.isDefaultReadOnly() ); - coursePreferred = ( Course ) s.get( Course.class, coursePreferred.getCourseCode() ); - assertFalse( s.isReadOnly( coursePreferred ) ); - Criteria criteria = s.createCriteria( Student.class ).setReadOnly( true ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertTrue( criteria.isReadOnly() ); - gavin = ( Student ) criteria.uniqueResult(); - assertFalse( s.isDefaultReadOnly() ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertTrue( criteria.isReadOnly() ); - assertTrue( s.isReadOnly( gavin ) ); - assertFalse( s.isReadOnly( coursePreferred ) ); - assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) ); - Hibernate.initialize( gavin.getEnrolments() ); - assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) ); - assertEquals( 1, gavin.getEnrolments().size() ); - enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next(); - assertFalse( s.isReadOnly( enrolment ) ); - assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - Hibernate.initialize( enrolment.getCourse() ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - s.delete(gavin.getPreferredCourse()); - s.delete(gavin); - s.delete( enrolment.getCourse() ); - s.delete(enrolment); - t.commit(); - s.close(); - } - - @Test - public void testReadOnlyCriteriaReturnsExistingModifiableProxyNotInit() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.persist(course); - - Course coursePreferred = new Course(); - coursePreferred.setCourseCode( "JBOSS" ); - coursePreferred.setDescription( "JBoss" ); - s.persist( coursePreferred ); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse( coursePreferred ); - s.persist(gavin); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add( enrolment ); - s.persist( enrolment ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - assertFalse( s.isDefaultReadOnly() ); - coursePreferred = ( Course ) s.load( Course.class, coursePreferred.getCourseCode() ); - assertFalse( Hibernate.isInitialized( coursePreferred ) ); - checkProxyReadOnly( s, coursePreferred, false ); - Criteria criteria = s.createCriteria( Student.class ).setReadOnly( true ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertTrue( criteria.isReadOnly() ); - gavin = ( Student ) criteria.uniqueResult(); - assertFalse( s.isDefaultReadOnly() ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertTrue( criteria.isReadOnly() ); - assertTrue( s.isReadOnly( gavin ) ); - assertFalse( Hibernate.isInitialized( coursePreferred ) ); - checkProxyReadOnly( s, coursePreferred, false ); - Hibernate.initialize( coursePreferred ); - checkProxyReadOnly( s, coursePreferred, false ); - assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) ); - Hibernate.initialize( gavin.getEnrolments() ); - assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) ); - assertEquals( 1, gavin.getEnrolments().size() ); - enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next(); - assertFalse( s.isReadOnly( enrolment ) ); - assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - Hibernate.initialize( enrolment.getCourse() ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - s.delete(gavin.getPreferredCourse()); - s.delete(gavin); - s.delete( enrolment.getCourse() ); - s.delete(enrolment); - t.commit(); - s.close(); - } - - @Test - public void testReadOnlyCriteriaReturnsExistingModifiableProxyInit() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.persist(course); - - Course coursePreferred = new Course(); - coursePreferred.setCourseCode( "JBOSS" ); - coursePreferred.setDescription( "JBoss" ); - s.persist( coursePreferred ); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse( coursePreferred ); - s.persist(gavin); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add( enrolment ); - s.persist( enrolment ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - assertFalse( s.isDefaultReadOnly() ); - coursePreferred = ( Course ) s.load( Course.class, coursePreferred.getCourseCode() ); - assertFalse( Hibernate.isInitialized( coursePreferred ) ); - checkProxyReadOnly( s, coursePreferred, false ); - Hibernate.initialize( coursePreferred ); - checkProxyReadOnly( s, coursePreferred, false ); - Criteria criteria = s.createCriteria( Student.class ).setReadOnly( true ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertTrue( criteria.isReadOnly() ); - gavin = ( Student ) criteria.uniqueResult(); - assertFalse( s.isDefaultReadOnly() ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertTrue( criteria.isReadOnly() ); - assertTrue( s.isReadOnly( gavin ) ); - assertTrue( Hibernate.isInitialized( coursePreferred ) ); - checkProxyReadOnly( s, coursePreferred, false ); - assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) ); - Hibernate.initialize( gavin.getEnrolments() ); - assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) ); - assertEquals( 1, gavin.getEnrolments().size() ); - enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next(); - assertFalse( s.isReadOnly( enrolment ) ); - assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - Hibernate.initialize( enrolment.getCourse() ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - s.delete(gavin.getPreferredCourse()); - s.delete(gavin); - s.delete( enrolment.getCourse() ); - s.delete(enrolment); - t.commit(); - s.close(); - } - - @Test - public void testModifiableCriteriaReturnsExistingReadOnlyEntity() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.persist(course); - - Course coursePreferred = new Course(); - coursePreferred.setCourseCode( "JBOSS" ); - coursePreferred.setDescription( "JBoss" ); - s.persist( coursePreferred ); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse( coursePreferred ); - s.persist(gavin); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add( enrolment ); - s.persist( enrolment ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - assertFalse( s.isDefaultReadOnly() ); - coursePreferred = ( Course ) s.get( Course.class, coursePreferred.getCourseCode() ); - assertFalse( s.isReadOnly( coursePreferred ) ); - s.setReadOnly( coursePreferred, true ); - Criteria criteria = s.createCriteria( Student.class ).setReadOnly( false ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertFalse( criteria.isReadOnly() ); - gavin = ( Student ) criteria.uniqueResult(); - assertFalse( s.isDefaultReadOnly() ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertFalse( criteria.isReadOnly() ); - assertFalse( s.isReadOnly( gavin ) ); - assertTrue( s.isReadOnly( coursePreferred ) ); - assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) ); - Hibernate.initialize( gavin.getEnrolments() ); - assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) ); - assertEquals( 1, gavin.getEnrolments().size() ); - enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next(); - assertFalse( s.isReadOnly( enrolment ) ); - assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - Hibernate.initialize( enrolment.getCourse() ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - s.delete(gavin.getPreferredCourse()); - s.delete(gavin); - s.delete( enrolment.getCourse() ); - s.delete(enrolment); - t.commit(); - s.close(); - } - - @Test - public void testModifiableCriteriaReturnsExistingReadOnlyProxyNotInit() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.persist(course); - - Course coursePreferred = new Course(); - coursePreferred.setCourseCode( "JBOSS" ); - coursePreferred.setDescription( "JBoss" ); - s.persist( coursePreferred ); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse( coursePreferred ); - s.persist(gavin); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add( enrolment ); - s.persist( enrolment ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - assertFalse( s.isDefaultReadOnly() ); - coursePreferred = ( Course ) s.load( Course.class, coursePreferred.getCourseCode() ); - assertFalse( Hibernate.isInitialized( coursePreferred ) ); - checkProxyReadOnly( s, coursePreferred, false ); - s.setReadOnly( coursePreferred, true ); - checkProxyReadOnly( s, coursePreferred, true ); - Criteria criteria = s.createCriteria( Student.class ).setReadOnly( false ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertFalse( criteria.isReadOnly() ); - gavin = ( Student ) criteria.uniqueResult(); - assertFalse( s.isDefaultReadOnly() ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertFalse( criteria.isReadOnly() ); - assertFalse( s.isReadOnly( gavin ) ); - assertFalse( Hibernate.isInitialized( coursePreferred ) ); - checkProxyReadOnly( s, coursePreferred, true ); - Hibernate.initialize( coursePreferred ); - checkProxyReadOnly( s, coursePreferred, true ); - assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) ); - Hibernate.initialize( gavin.getEnrolments() ); - assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) ); - assertEquals( 1, gavin.getEnrolments().size() ); - enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next(); - assertFalse( s.isReadOnly( enrolment ) ); - assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - Hibernate.initialize( enrolment.getCourse() ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - s.delete(gavin.getPreferredCourse()); - s.delete(gavin); - s.delete( enrolment.getCourse() ); - s.delete(enrolment); - t.commit(); - s.close(); - } - - @Test - public void testModifiableCriteriaReturnsExistingReadOnlyProxyInit() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.persist(course); - - Course coursePreferred = new Course(); - coursePreferred.setCourseCode( "JBOSS" ); - coursePreferred.setDescription( "JBoss" ); - s.persist( coursePreferred ); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse( coursePreferred ); - s.persist(gavin); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add( enrolment ); - s.persist( enrolment ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - assertFalse( s.isDefaultReadOnly() ); - coursePreferred = ( Course ) s.load( Course.class, coursePreferred.getCourseCode() ); - assertFalse( Hibernate.isInitialized( coursePreferred ) ); - checkProxyReadOnly( s, coursePreferred, false ); - Hibernate.initialize( coursePreferred ); - checkProxyReadOnly( s, coursePreferred, false ); - s.setReadOnly( coursePreferred, true ); - checkProxyReadOnly( s, coursePreferred, true ); - Criteria criteria = s.createCriteria( Student.class ).setReadOnly( false ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertFalse( criteria.isReadOnly() ); - gavin = ( Student ) criteria.uniqueResult(); - assertFalse( s.isDefaultReadOnly() ); - assertTrue( criteria.isReadOnlyInitialized() ); - assertFalse( criteria.isReadOnly() ); - assertFalse( s.isReadOnly( gavin ) ); - assertTrue( Hibernate.isInitialized( coursePreferred ) ); - checkProxyReadOnly( s, coursePreferred, true ); - assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) ); - Hibernate.initialize( gavin.getEnrolments() ); - assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) ); - assertEquals( 1, gavin.getEnrolments().size() ); - enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next(); - assertFalse( s.isReadOnly( enrolment ) ); - assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - Hibernate.initialize( enrolment.getCourse() ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - s.delete(gavin.getPreferredCourse()); - s.delete(gavin); - s.delete( enrolment.getCourse() ); - s.delete(enrolment); - t.commit(); - s.close(); - } - - @Test - public void testScrollCriteria() { - Session session = openSession(); - Transaction t = session.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - session.persist(course); - session.flush(); - session.clear(); - ScrollableResults sr = session.createCriteria(Course.class).setReadOnly( true ).scroll(); - assertTrue( sr.next() ); - course = (Course) sr.get(0); - assertNotNull(course); - assertTrue( session.isReadOnly( course ) ); - sr.close(); - session.delete(course); - - t.commit(); - session.close(); - } - - @Test - @SkipForDialect( value = SybaseASE15Dialect.class, jiraKey = "HHH-3032", strictMatching = true) - public void testSubselect() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.persist(course); - - Course coursePreferred = new Course(); - coursePreferred.setCourseCode( "JBOSS" ); - coursePreferred.setDescription( "JBoss" ); - s.persist( coursePreferred ); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - gavin.setPreferredCourse( coursePreferred ); - s.persist(gavin); - - Enrolment enrolment = new Enrolment(); - enrolment.setCourse(course); - enrolment.setCourseCode(course.getCourseCode()); - enrolment.setSemester((short) 3); - enrolment.setYear((short) 1998); - enrolment.setStudent(gavin); - enrolment.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add(enrolment); - s.persist(enrolment); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - DetachedCriteria dc = DetachedCriteria.forClass(Student.class) - .add( Property.forName("studentNumber").eq( new Long(232) ) ) - .setProjection( Property.forName("name") ); - gavin = ( Student ) s.createCriteria(Student.class) - .add( Subqueries.exists(dc) ) - .setReadOnly( true ) - .uniqueResult(); - assertFalse( s.isDefaultReadOnly() ); - assertTrue( s.isReadOnly( gavin ) ); - assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - checkProxyReadOnly( s, gavin.getPreferredCourse(), true ); - assertFalse( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - Hibernate.initialize( gavin.getPreferredCourse() ); - assertTrue( Hibernate.isInitialized( gavin.getPreferredCourse() ) ); - checkProxyReadOnly( s, gavin.getPreferredCourse(), true ); - assertFalse( Hibernate.isInitialized( gavin.getEnrolments() ) ); - Hibernate.initialize( gavin.getEnrolments() ); - assertTrue( Hibernate.isInitialized( gavin.getEnrolments() ) ); - assertEquals( 1, gavin.getEnrolments().size() ); - enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next(); - assertFalse( s.isReadOnly( enrolment ) ); - assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - Hibernate.initialize( enrolment.getCourse() ); - checkProxyReadOnly( s, enrolment.getCourse(), false ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - DetachedCriteria dc2 = DetachedCriteria.forClass(Student.class, "st") - .add( Property.forName("st.studentNumber").eqProperty("e.studentNumber") ) - .setProjection( Property.forName("name") ); - enrolment = ( Enrolment ) s.createCriteria(Enrolment.class, "e") - .add( Subqueries.eq("Gavin King", dc2) ) - .setReadOnly( true ) - .uniqueResult(); - assertTrue( s.isReadOnly( enrolment ) ); - assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), true ); - Hibernate.initialize( enrolment.getCourse() ); - assertTrue( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), true ); - assertFalse( Hibernate.isInitialized( enrolment.getStudent() ) ); - checkProxyReadOnly( s, enrolment.getStudent(), true ); - Hibernate.initialize( enrolment.getStudent() ); - assertTrue( Hibernate.isInitialized( enrolment.getStudent() ) ); - checkProxyReadOnly( s, enrolment.getStudent(), true ); - assertFalse( Hibernate.isInitialized( enrolment.getStudent().getPreferredCourse() ) ); - checkProxyReadOnly( s, enrolment.getStudent().getPreferredCourse(), false ); - Hibernate.initialize( enrolment.getStudent().getPreferredCourse() ); - assertTrue( Hibernate.isInitialized( enrolment.getStudent().getPreferredCourse() ) ); - checkProxyReadOnly( s, enrolment.getStudent().getPreferredCourse(), false ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - DetachedCriteria dc3 = DetachedCriteria.forClass(Student.class, "st") - .createCriteria("enrolments") - .createCriteria("course") - .add( Property.forName("description").eq("Hibernate Training") ) - .setProjection( Property.forName("st.name") ); - enrolment = ( Enrolment ) s.createCriteria(Enrolment.class, "e") - .add( Subqueries.eq("Gavin King", dc3) ) - .setReadOnly( true ) - .uniqueResult(); - assertTrue( s.isReadOnly( enrolment ) ); - assertFalse( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), true ); - Hibernate.initialize( enrolment.getCourse() ); - assertTrue( Hibernate.isInitialized( enrolment.getCourse() ) ); - checkProxyReadOnly( s, enrolment.getCourse(), true ); - assertFalse( Hibernate.isInitialized( enrolment.getStudent() ) ); - checkProxyReadOnly( s, enrolment.getStudent(), true ); - Hibernate.initialize( enrolment.getStudent() ); - assertTrue( Hibernate.isInitialized( enrolment.getStudent() ) ); - checkProxyReadOnly( s, enrolment.getStudent(), true ); - assertFalse( Hibernate.isInitialized( enrolment.getStudent().getPreferredCourse() ) ); - checkProxyReadOnly( s, enrolment.getStudent().getPreferredCourse(), false ); - Hibernate.initialize( enrolment.getStudent().getPreferredCourse() ); - assertTrue( Hibernate.isInitialized( enrolment.getStudent().getPreferredCourse() ) ); - checkProxyReadOnly( s, enrolment.getStudent().getPreferredCourse(), false ); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - s.delete(gavin.getPreferredCourse()); - s.delete(gavin); - enrolment = ( Enrolment ) gavin.getEnrolments().iterator().next(); - s.delete( enrolment.getCourse() ); - s.delete(enrolment); - t.commit(); - s.close(); - } - - @Test - public void testDetachedCriteria() { - DetachedCriteria dc = DetachedCriteria.forClass(Student.class) - .add( Property.forName("name").eq("Gavin King") ) - .addOrder( Order.asc("studentNumber") ); - - byte[] bytes = SerializationHelper.serialize(dc); - - dc = (DetachedCriteria) SerializationHelper.deserialize( bytes ); - - Session session = openSession(); - Transaction t = session.beginTransaction(); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(232); - Student bizarroGavin = new Student(); - bizarroGavin.setName("Gavin King"); - bizarroGavin.setStudentNumber(666); - session.persist(bizarroGavin); - session.persist(gavin); - - t.commit(); - session.close(); - - session = openSession(); - t = session.beginTransaction(); - - List result = dc.getExecutableCriteria(session) - .setMaxResults(3) - .setReadOnly( true ) - .list(); - - assertEquals( result.size(), 2 ); - gavin = ( Student ) result.get( 0 ); - bizarroGavin = ( Student ) result.get( 1 ); - assertEquals( 232, gavin.getStudentNumber() ); - assertEquals( 666, bizarroGavin.getStudentNumber() ); - assertTrue( session.isReadOnly( gavin ) ); - assertTrue( session.isReadOnly( bizarroGavin ) ); - - session.delete(gavin); - session.delete(bizarroGavin); - t.commit(); - session.close(); - } - - @Test - public void testTwoAliasesCache() { - Session s = openSession(); - Transaction t = s.beginTransaction(); - - Course course = new Course(); - course.setCourseCode("HIB"); - course.setDescription("Hibernate Training"); - s.save(course); - - Student gavin = new Student(); - gavin.setName("Gavin King"); - gavin.setStudentNumber(666); - s.save(gavin); - - Student xam = new Student(); - xam.setName("Max Rydahl Andersen"); - xam.setStudentNumber(101); - s.save(xam); - - Enrolment enrolment1 = new Enrolment(); - enrolment1.setCourse(course); - enrolment1.setCourseCode(course.getCourseCode()); - enrolment1.setSemester((short) 1); - enrolment1.setYear((short) 1999); - enrolment1.setStudent(xam); - enrolment1.setStudentNumber(xam.getStudentNumber()); - xam.getEnrolments().add(enrolment1); - s.save(enrolment1); - - Enrolment enrolment2 = new Enrolment(); - enrolment2.setCourse(course); - enrolment2.setCourseCode(course.getCourseCode()); - enrolment2.setSemester((short) 3); - enrolment2.setYear((short) 1998); - enrolment2.setStudent(gavin); - enrolment2.setStudentNumber(gavin.getStudentNumber()); - gavin.getEnrolments().add(enrolment2); - s.save(enrolment2); - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - - List list = s.createCriteria(Enrolment.class) - .createAlias("student", "s") - .createAlias("course", "c") - .add( Restrictions.isNotEmpty("s.enrolments") ) - .setCacheable(true) - .setReadOnly( true ) - .list(); - - assertEquals( list.size(), 2 ); - - Enrolment e = ( Enrolment ) list.get( 0 ); - if ( e.getStudent().getStudentNumber() == gavin.getStudentNumber() ) { - enrolment1 = e; - enrolment2 = ( Enrolment ) list.get( 1 ); - } - else if ( e.getStudent().getStudentNumber() == xam.getStudentNumber() ) { - enrolment2 = e; - enrolment1 = ( Enrolment ) list.get( 1 ); - } - else { - fail( "Enrolment has unknown student number: " + e.getStudent().getStudentNumber() ); - } - - assertTrue( s.isReadOnly( enrolment1 ) ); - assertTrue( s.isReadOnly( enrolment2 ) ); - assertTrue( s.isReadOnly( enrolment1.getCourse() ) ); - assertTrue( s.isReadOnly( enrolment2.getCourse() ) ); - assertSame( enrolment1.getCourse(), enrolment2.getCourse() ); - assertTrue( s.isReadOnly( enrolment1.getStudent() ) ); - assertTrue( s.isReadOnly( enrolment2.getStudent() ) ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - - list = s.createCriteria(Enrolment.class) - .createAlias("student", "s") - .createAlias("course", "c") - .setReadOnly( true ) - .add( Restrictions.isNotEmpty("s.enrolments") ) - .setCacheable(true) - .setReadOnly( true ) - .list(); - - assertEquals( list.size(), 2 ); - - e = ( Enrolment ) list.get( 0 ); - if ( e.getStudent().getStudentNumber() == gavin.getStudentNumber() ) { - enrolment1 = e; - enrolment2 = ( Enrolment ) list.get( 1 ); - } - else if ( e.getStudent().getStudentNumber() == xam.getStudentNumber() ) { - enrolment2 = e; - enrolment1 = ( Enrolment ) list.get( 1 ); - } - else { - fail( "Enrolment has unknown student number: " + e.getStudent().getStudentNumber() ); - } - - assertTrue( s.isReadOnly( enrolment1 ) ); - assertTrue( s.isReadOnly( enrolment2 ) ); - assertTrue( s.isReadOnly( enrolment1.getCourse() ) ); - assertTrue( s.isReadOnly( enrolment2.getCourse() ) ); - assertSame( enrolment1.getCourse(), enrolment2.getCourse() ); - assertTrue( s.isReadOnly( enrolment1.getStudent() ) ); - assertTrue( s.isReadOnly( enrolment2.getStudent() ) ); - - t.commit(); - s.close(); - - s = openSession(); - t = s.beginTransaction(); - - list = s.createCriteria(Enrolment.class) - .setReadOnly( true ) - .createAlias("student", "s") - .createAlias("course", "c") - .add( Restrictions.isNotEmpty("s.enrolments") ) - .setCacheable(true) - .list(); - - assertEquals( list.size(), 2 ); - - e = ( Enrolment ) list.get( 0 ); - if ( e.getStudent().getStudentNumber() == gavin.getStudentNumber() ) { - enrolment1 = e; - enrolment2 = ( Enrolment ) list.get( 1 ); - } - else if ( e.getStudent().getStudentNumber() == xam.getStudentNumber() ) { - enrolment2 = e; - enrolment1 = ( Enrolment ) list.get( 1 ); - } - else { - fail( "Enrolment has unknown student number: " + e.getStudent().getStudentNumber() ); - } - - assertTrue( s.isReadOnly( enrolment1 ) ); - assertTrue( s.isReadOnly( enrolment2 ) ); - assertTrue( s.isReadOnly( enrolment1.getCourse() ) ); - assertTrue( s.isReadOnly( enrolment2.getCourse() ) ); - assertSame( enrolment1.getCourse(), enrolment2.getCourse() ); - assertTrue( s.isReadOnly( enrolment1.getStudent() ) ); - assertTrue( s.isReadOnly( enrolment2.getStudent() ) ); - - s.delete( enrolment1 ); - s.delete( enrolment2 ); - s.delete( enrolment1.getCourse() ); - s.delete( enrolment1.getStudent() ); - s.delete( enrolment2.getStudent() ); - - t.commit(); - s.close(); - } - - private void checkProxyReadOnly(Session s, Object proxy, boolean expectedReadOnly) { - assertTrue( proxy instanceof HibernateProxy ); - LazyInitializer li = ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer(); - assertSame( s, li.getSession() ); - assertEquals( expectedReadOnly, s.isReadOnly( proxy ) ); - assertEquals( expectedReadOnly, li.isReadOnly() ); - assertEquals( Hibernate.isInitialized( proxy ), ! li.isUninitialized() ); - if ( Hibernate.isInitialized( proxy ) ) { - assertEquals( expectedReadOnly, s.isReadOnly( li.getImplementation() ) ); - } - } - -} -