6.0 Final tasks - analyze legacy Criteria tests
See if anything makes sense as additions to SqmNodeBuilder (as JPA CriteriaBuilder extension); make list; delete The only one I considered was support for the legacy `Restrictions#naturalId`
This commit is contained in:
parent
8cc9a064ec
commit
8f9d200936
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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<TableB> 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<TableB> getTableBs() {
|
||||
return this.tableBs;
|
||||
}
|
||||
|
||||
public void setTableBs(Set<TableB> 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<TableC> 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<TableC> getTableCs() {
|
||||
return tableCs;
|
||||
}
|
||||
|
||||
public void setTableCs(Set<TableC> 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;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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" );
|
||||
}
|
||||
}
|
|
@ -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<Zoo> iterator = (Iterator<Zoo>) 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
|
||||
};
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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:
|
||||
*
|
||||
* <code>
|
||||
* 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=?
|
||||
* </code>
|
||||
*
|
||||
* Which results in this error from the SQL server:
|
||||
*
|
||||
* <code>
|
||||
* Unknown column 'complexjoi1_.is_deleted' in 'where clause'
|
||||
* </code>
|
||||
*
|
||||
* 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();
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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<Cat> 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<Kitten> 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;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,113 +0,0 @@
|
|||
/*
|
||||
* Hibernate, Relational Persistence for Idiomatic Java
|
||||
*
|
||||
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
|
||||
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
package org.hibernate.test.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() );
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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();
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -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";
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,76 +0,0 @@
|
|||
/*
|
||||
* Hibernate, Relational Persistence for Idiomatic Java
|
||||
*
|
||||
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
|
||||
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
package org.hibernate.test.criteria;
|
||||
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();
|
||||
|
||||
}
|
||||
}
|
|
@ -1,111 +0,0 @@
|
|||
/*
|
||||
* Hibernate, Relational Persistence for Idiomatic Java
|
||||
*
|
||||
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
|
||||
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
package org.hibernate.test.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
|
||||
* "<argLine>-Xss128k</argLine>" 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;
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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<TestEntity> query = createTestEntityCriteriaQuery( entityName, session );
|
||||
final Optional<TestEntity> result = session.createQuery( query ).uniqueResultOptional();
|
||||
assertThat( result.isPresent(), is( false ) );
|
||||
}
|
||||
}
|
||||
|
||||
private CriteriaQuery<TestEntity> createTestEntityCriteriaQuery(
|
||||
String entityName,
|
||||
Session session) {
|
||||
final CriteriaBuilder builder = session.getCriteriaBuilder();
|
||||
final CriteriaQuery<TestEntity> query =
|
||||
builder.createQuery( TestEntity.class );
|
||||
final Root<TestEntity> 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<TestEntity> query = createTestEntityCriteriaQuery(
|
||||
entityName,
|
||||
session
|
||||
);
|
||||
final Stream<TestEntity> 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<TestEntity> 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;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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<String> 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;
|
||||
}
|
||||
}
|
|
@ -1,41 +0,0 @@
|
|||
/*
|
||||
* Hibernate, Relational Persistence for Idiomatic Java
|
||||
*
|
||||
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
|
||||
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
package org.hibernate.test.criteria.limitexpression;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class Person {
|
||||
private Long id;
|
||||
private Set<UsState> states;
|
||||
private Set<Country> countries;
|
||||
|
||||
public Set<UsState> getStates() {
|
||||
return states;
|
||||
}
|
||||
|
||||
public void setStates(Set<UsState> states) {
|
||||
this.states = states;
|
||||
}
|
||||
|
||||
public Set<Country> getCountries() {
|
||||
return countries;
|
||||
}
|
||||
|
||||
public void setCountries(Set<Country> countries) {
|
||||
this.countries = countries;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -1,28 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
|
||||
|
||||
<hibernate-mapping package="org.hibernate.test.criteria.limitexpression">
|
||||
<class name="Person" table="person">
|
||||
<id name="id" column="id" type="long">
|
||||
<generator class="increment"/>
|
||||
</id>
|
||||
|
||||
<set name="states" table="person_states" inverse="false" lazy="false" fetch="join">
|
||||
<key column="id_person" not-null="true"/>
|
||||
<many-to-many class="UsState" column="code_state"/>
|
||||
</set>
|
||||
|
||||
<set name="countries" table="person_countries" inverse="false" lazy="false" fetch="join">
|
||||
<key column="id_person" not-null="true"/>
|
||||
<many-to-many class="Country" column="code_country"/>
|
||||
</set>
|
||||
</class>
|
||||
|
||||
<class name="UsState" table="us_state">
|
||||
<id column="code" name="code" type="string"/>
|
||||
</class>
|
||||
|
||||
<class name="Country" table="country">
|
||||
<id column="code" name="code" type="string"/>
|
||||
</class>
|
||||
</hibernate-mapping>
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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<Seller> 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<Seller> results2 = criteria.list();
|
||||
assertTrue( results2.size() == 2 );
|
||||
assertTrue( results2.contains( seller1 ) );
|
||||
assertTrue( results2.contains( seller2 ) );
|
||||
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMappedBy() {
|
||||
Set<Customer> customersAll = new LinkedHashSet<Customer>();
|
||||
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<Customer> 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<Customer> 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};
|
||||
}
|
||||
}
|
|
@ -1,55 +0,0 @@
|
|||
/*
|
||||
* Hibernate, Relational Persistence for Idiomatic Java
|
||||
*
|
||||
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
|
||||
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
package org.hibernate.test.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<Seller> boughtFrom = new HashSet<Seller>();
|
||||
|
||||
protected Customer() {
|
||||
}
|
||||
|
||||
public Customer(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Set<Seller> 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();
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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<Customer> soldTo = new HashSet<Customer>();
|
||||
|
||||
protected Seller() {
|
||||
}
|
||||
|
||||
public Seller(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Set<Customer> 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();
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
|
||||
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<PostDetails> query = cb.createQuery( PostDetails.class );
|
||||
Root<PostDetails> 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;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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();
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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();
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
|
||||
//$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();
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -1,921 +0,0 @@
|
|||
/*
|
||||
* Hibernate, Relational Persistence for Idiomatic Java
|
||||
*
|
||||
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
|
||||
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
|
||||
//$Id: 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");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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();
|
||||
}
|
||||
}
|
|
@ -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>.
|
||||
*/
|
||||
|
||||
//$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();
|
||||
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
|
||||
//$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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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
|
||||
* <p/>
|
||||
* 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
|
||||
* <p/>
|
||||
* 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
|
||||
* <p/>
|
||||
* 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;
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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<String,Object> 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<String> 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();
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
|
||||
//$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());
|
||||
}
|
||||
}
|
|
@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue