+ */
+public class MonetaryAmount implements Serializable {
+
+ private final BigDecimal value;
+ private final Currency currency;
+
+ public MonetaryAmount(BigDecimal value, Currency currency) {
+ this.value = value;
+ this.currency = currency;
+ }
+
+ public Currency getCurrency() {
+ return currency;
+ }
+
+ public BigDecimal getValue() {
+ return value;
+ }
+
+ // ********************** Common Methods ********************** //
+
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof MonetaryAmount)) return false;
+
+ final MonetaryAmount monetaryAmount = (MonetaryAmount) o;
+
+ if (!currency.equals(monetaryAmount.currency)) return false;
+ if (!value.equals(monetaryAmount.value)) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ int result;
+ result = value.hashCode();
+ result = 29 * result + currency.hashCode();
+ return result;
+ }
+
+ public String toString() {
+ return "Value: '" + getValue() + "', " +
+ "Currency: '" + getCurrency() + "'";
+ }
+
+ public int compareTo(Object o) {
+ if (o instanceof MonetaryAmount) {
+ // TODO: This would actually require some currency conversion magic
+ return this.getValue().compareTo(((MonetaryAmount) o).getValue());
+ }
+ return 0;
+ }
+
+ // ********************** Business Methods ********************** //
+
+ public static MonetaryAmount fromString(String amount, String currencyCode) {
+ return new MonetaryAmount(new BigDecimal(amount),
+ Currency.getInstance(currencyCode));
+ }
+
+ public static MonetaryAmount convert(MonetaryAmount amount,
+ Currency toConcurrency) {
+ // TODO: This requires some conversion magic and is therefore broken
+ return new MonetaryAmount(amount.getValue(), toConcurrency);
+ }
+
+}
diff --git a/test/org/hibernate/test/sql/hand/MonetaryAmountUserType.java b/test/org/hibernate/test/sql/hand/MonetaryAmountUserType.java
new file mode 100644
index 0000000000..9b1c7611fd
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/MonetaryAmountUserType.java
@@ -0,0 +1,85 @@
+package org.hibernate.test.sql.hand;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.util.Currency;
+
+import org.hibernate.HibernateException;
+import org.hibernate.usertype.UserType;
+
+/**
+ * This is a simple Hibernate custom mapping type for MonetaryAmount value types.
+ *
+ *
+ * @author Max & Christian
+ */
+public class MonetaryAmountUserType
+ implements UserType {
+
+ private static final int[] SQL_TYPES = {Types.NUMERIC, Types.VARCHAR };
+
+ public int[] sqlTypes() { return SQL_TYPES; }
+
+ public Class returnedClass() { return MonetaryAmount.class; }
+
+ public boolean isMutable() { return false; }
+
+ public Object deepCopy(Object value) {
+ return value; // MonetaryAmount is immutable
+ }
+
+ public boolean equals(Object x, Object y) {
+ if (x == y) return true;
+ if (x == null || y == null) return false;
+ return x.equals(y);
+ }
+
+ public Object nullSafeGet(ResultSet resultSet,
+ String[] names,
+ Object owner)
+ throws HibernateException, SQLException {
+
+ BigDecimal value = resultSet.getBigDecimal(names[0]);
+ if (resultSet.wasNull()) return null;
+ String cur = resultSet.getString(names[1]);
+ Currency userCurrency = Currency.getInstance(cur);
+
+ return new MonetaryAmount(value, userCurrency);
+ }
+
+ public void nullSafeSet(PreparedStatement statement,
+ Object value,
+ int index)
+ throws HibernateException, SQLException {
+
+ if (value == null) {
+ statement.setNull(index, Types.NUMERIC);
+ statement.setNull(index+1, Types.VARCHAR);
+ } else {
+ MonetaryAmount currency = (MonetaryAmount)value;
+ statement.setBigDecimal(index, currency.getValue());
+ statement.setString(index+1, currency.getCurrency().getCurrencyCode());
+ }
+ }
+
+ public Serializable disassemble(Object value) throws HibernateException {
+ return (Serializable) value;
+ }
+
+ public Object assemble(Serializable cached, Object owner) throws HibernateException {
+ return cached;
+ }
+
+ public Object replace(Object original, Object target, Object owner)
+ throws HibernateException {
+ return original;
+ }
+
+ public int hashCode(Object x) throws HibernateException {
+ return x.hashCode();
+ }
+}
diff --git a/test/org/hibernate/test/sql/hand/Order.java b/test/org/hibernate/test/sql/hand/Order.java
new file mode 100644
index 0000000000..015aba8897
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/Order.java
@@ -0,0 +1,55 @@
+package org.hibernate.test.sql.hand;
+
+import java.io.Serializable;
+
+public class Order {
+
+ static public class OrderId implements Serializable {
+ String orgid;
+ String ordernumber;
+ public String getOrdernumber() {
+ return ordernumber;
+ }
+ public void setOrdernumber(String ordernumber) {
+ this.ordernumber = ordernumber;
+ }
+ public String getOrgid() {
+ return orgid;
+ }
+ public void setOrgid(String orgid) {
+ this.orgid = orgid;
+ }
+
+
+ }
+
+ OrderId orderId;
+
+ Product product;
+
+ Person person;
+
+ public Person getPerson() {
+ return person;
+ }
+
+ public void setPerson(Person person) {
+ this.person = person;
+ }
+ public OrderId getOrderId() {
+ return orderId;
+ }
+
+ public void setOrderId(OrderId orderId) {
+ this.orderId = orderId;
+ }
+
+ public Product getProduct() {
+ return product;
+ }
+
+ public void setProduct(Product product) {
+ this.product = product;
+ }
+
+}
diff --git a/test/org/hibernate/test/sql/hand/Organization.java b/test/org/hibernate/test/sql/hand/Organization.java
new file mode 100644
index 0000000000..06cc648372
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/Organization.java
@@ -0,0 +1,59 @@
+//$Id: Organization.java 7547 2005-07-19 18:21:35Z oneovthafew $
+package org.hibernate.test.sql.hand;
+
+import java.util.Collection;
+import java.util.HashSet;
+
+/**
+ * @author Gavin King
+ */
+public class Organization {
+ private long id;
+ private String name;
+ private Collection employments;
+
+ public Organization(String name) {
+ this.name = name;
+ employments = new HashSet();
+ }
+
+ public Organization() {}
+
+ /**
+ * @return Returns the employments.
+ */
+ public Collection getEmployments() {
+ return employments;
+ }
+ /**
+ * @param employments The employments to set.
+ */
+ public void setEmployments(Collection employments) {
+ this.employments = employments;
+ }
+ /**
+ * @return Returns the id.
+ */
+ public long getId() {
+ return id;
+ }
+ /**
+ * @param id The id to set.
+ */
+ public void setId(long id) {
+ this.id = id;
+ }
+ /**
+ * @return Returns the name.
+ */
+ public String getName() {
+ return name;
+ }
+ /**
+ * @param name The name to set.
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+}
diff --git a/test/org/hibernate/test/sql/hand/Person.java b/test/org/hibernate/test/sql/hand/Person.java
new file mode 100644
index 0000000000..c91b5a1a46
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/Person.java
@@ -0,0 +1,41 @@
+//$Id: Person.java 4316 2004-08-14 13:12:03Z oneovthafew $
+package org.hibernate.test.sql.hand;
+
+/**
+ * @author Gavin King
+ */
+public class Person {
+ private long id;
+ private String name;
+
+ public Person(String name) {
+ this.name = name;
+ }
+
+ public Person() {}
+
+/**
+ * @return Returns the id.
+ */
+ public long getId() {
+ return id;
+ }
+ /**
+ * @param id The id to set.
+ */
+ public void setId(long id) {
+ this.id = id;
+ }
+ /**
+ * @return Returns the name.
+ */
+ public String getName() {
+ return name;
+ }
+ /**
+ * @param name The name to set.
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/test/org/hibernate/test/sql/hand/Product.java b/test/org/hibernate/test/sql/hand/Product.java
new file mode 100644
index 0000000000..98d3dd462a
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/Product.java
@@ -0,0 +1,66 @@
+package org.hibernate.test.sql.hand;
+
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.Set;
+
+public class Product {
+
+ static public class ProductId implements Serializable {
+ String orgid;
+ String productnumber;
+ public String getProductnumber() {
+ return productnumber;
+ }
+ public void setProductnumber(String ordernumber) {
+ this.productnumber = ordernumber;
+ }
+ public String getOrgid() {
+ return orgid;
+ }
+ public void setOrgid(String orgid) {
+ this.orgid = orgid;
+ }
+
+
+ }
+
+ ProductId productId;
+
+ String name;
+
+ Person person;
+
+ Set orders = new HashSet();
+
+ public Set getOrders() {
+ return orders;
+ }
+
+ public void setOrders(Set orders) {
+ this.orders = orders;
+ }
+ public Person getPerson() {
+ return person;
+ }
+
+ public void setPerson(Person person) {
+ this.person = person;
+ }
+ public ProductId getProductId() {
+ return productId;
+ }
+
+ public void setProductId(ProductId orderId) {
+ this.productId = orderId;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String product) {
+ this.name = product;
+ }
+
+}
diff --git a/test/org/hibernate/test/sql/hand/SpaceShip.java b/test/org/hibernate/test/sql/hand/SpaceShip.java
new file mode 100644
index 0000000000..2e9e48839b
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/SpaceShip.java
@@ -0,0 +1,53 @@
+//$Id: $
+package org.hibernate.test.sql.hand;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class SpaceShip {
+ private Integer id;
+ private String name;
+ private String model;
+ private double speed;
+ private Dimension dimensions;
+
+ public Dimension getDimensions() {
+ return dimensions;
+ }
+
+ public void setDimensions(Dimension dimensions) {
+ this.dimensions = dimensions;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getModel() {
+ return model;
+ }
+
+ public void setModel(String model) {
+ this.model = model;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public double getSpeed() {
+ return speed;
+ }
+
+ public void setSpeed(double speed) {
+ this.speed = speed;
+ }
+}
diff --git a/test/org/hibernate/test/sql/hand/Speech.java b/test/org/hibernate/test/sql/hand/Speech.java
new file mode 100644
index 0000000000..b50bcb419c
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/Speech.java
@@ -0,0 +1,35 @@
+//$Id: $
+package org.hibernate.test.sql.hand;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Speech {
+ private Integer id;
+ private String name;
+ private Double length;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Double getLength() {
+ return length;
+ }
+
+ public void setLength(Double length) {
+ this.length = length;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/test/org/hibernate/test/sql/hand/custom/CustomSQLTestSupport.java b/test/org/hibernate/test/sql/hand/custom/CustomSQLTestSupport.java
new file mode 100644
index 0000000000..6828ba12fd
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/custom/CustomSQLTestSupport.java
@@ -0,0 +1,94 @@
+package org.hibernate.test.sql.hand.custom;
+
+import java.io.Serializable;
+import java.util.Date;
+import java.util.Iterator;
+
+import org.hibernate.LockMode;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.sql.hand.Employment;
+import org.hibernate.test.sql.hand.Organization;
+import org.hibernate.test.sql.hand.Person;
+import org.hibernate.junit.functional.DatabaseSpecificFunctionalTestCase;
+
+/**
+ * Abstract test case defining tests for the support for user-supplied (aka
+ * custom) insert, update, delete SQL.
+ *
+ * @author Steve Ebersole
+ */
+public abstract class CustomSQLTestSupport extends DatabaseSpecificFunctionalTestCase {
+
+ public CustomSQLTestSupport(String name) {
+ super( name );
+ }
+
+ public String getCacheConcurrencyStrategy() {
+ return null;
+ }
+
+ public void testHandSQL() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Organization ifa = new Organization( "IFA" );
+ Organization jboss = new Organization( "JBoss" );
+ Person gavin = new Person( "Gavin" );
+ Employment emp = new Employment( gavin, jboss, "AU" );
+ Serializable orgId = s.save( jboss );
+ s.save( ifa );
+ s.save( gavin );
+ s.save( emp );
+ t.commit();
+
+ t = s.beginTransaction();
+ Person christian = new Person( "Christian" );
+ s.save( christian );
+ Employment emp2 = new Employment( christian, jboss, "EU" );
+ s.save( emp2 );
+ t.commit();
+ s.close();
+
+ getSessions().evict( Organization.class );
+ getSessions().evict( Person.class );
+ getSessions().evict( Employment.class );
+
+ s = openSession();
+ t = s.beginTransaction();
+ jboss = ( Organization ) s.get( Organization.class, orgId );
+ assertEquals( jboss.getEmployments().size(), 2 );
+ assertEquals( jboss.getName(), "JBOSS" );
+ emp = ( Employment ) jboss.getEmployments().iterator().next();
+ gavin = emp.getEmployee();
+ assertEquals( gavin.getName(), "GAVIN" );
+ assertEquals( s.getCurrentLockMode( gavin ), LockMode.UPGRADE );
+ emp.setEndDate( new Date() );
+ Employment emp3 = new Employment( gavin, jboss, "US" );
+ s.save( emp3 );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Iterator iter = s.getNamedQuery( "allOrganizationsWithEmployees" ).list().iterator();
+ assertTrue( iter.hasNext() );
+ Organization o = ( Organization ) iter.next();
+ assertEquals( o.getEmployments().size(), 3 );
+ Iterator iter2 = o.getEmployments().iterator();
+ while ( iter2.hasNext() ) {
+ Employment e = ( Employment ) iter2.next();
+ s.delete( e );
+ }
+ iter2 = o.getEmployments().iterator();
+ while ( iter2.hasNext() ) {
+ Employment e = ( Employment ) iter2.next();
+ s.delete( e.getEmployee() );
+ }
+ s.delete( o );
+ assertFalse( iter.hasNext() );
+ s.delete( ifa );
+ t.commit();
+ s.close();
+ }
+
+}
diff --git a/test/org/hibernate/test/sql/hand/custom/CustomStoredProcTestSupport.java b/test/org/hibernate/test/sql/hand/custom/CustomStoredProcTestSupport.java
new file mode 100644
index 0000000000..d0467d65b4
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/custom/CustomStoredProcTestSupport.java
@@ -0,0 +1,83 @@
+package org.hibernate.test.sql.hand.custom;
+
+import java.sql.SQLException;
+import java.util.List;
+
+import org.hibernate.HibernateException;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.sql.hand.Employment;
+import org.hibernate.test.sql.hand.Organization;
+import org.hibernate.test.sql.hand.Person;
+
+/**
+ * Abstract test case defining tests of stored procedure support.
+ *
+ * @author Gail Badner
+ */
+public abstract class CustomStoredProcTestSupport extends CustomSQLTestSupport {
+
+ public CustomStoredProcTestSupport(String name) {
+ super( name );
+ }
+
+ public void testScalarStoredProcedure() throws HibernateException, SQLException {
+ Session s = openSession();
+ Query namedQuery = s.getNamedQuery( "simpleScalar" );
+ namedQuery.setLong( "number", 43 );
+ List list = namedQuery.list();
+ Object o[] = ( Object[] ) list.get( 0 );
+ assertEquals( o[0], "getAll" );
+ assertEquals( o[1], new Long( 43 ) );
+ s.close();
+ }
+
+ public void testParameterHandling() throws HibernateException, SQLException {
+ Session s = openSession();
+
+ Query namedQuery = s.getNamedQuery( "paramhandling" );
+ namedQuery.setLong( 0, 10 );
+ namedQuery.setLong( 1, 20 );
+ List list = namedQuery.list();
+ Object[] o = ( Object[] ) list.get( 0 );
+ assertEquals( o[0], new Long( 10 ) );
+ assertEquals( o[1], new Long( 20 ) );
+
+ namedQuery = s.getNamedQuery( "paramhandling_mixed" );
+ namedQuery.setLong( 0, 10 );
+ namedQuery.setLong( "second", 20 );
+ list = namedQuery.list();
+ o = ( Object[] ) list.get( 0 );
+ assertEquals( o[0], new Long( 10 ) );
+ assertEquals( o[1], new Long( 20 ) );
+ s.close();
+ }
+
+ public void testEntityStoredProcedure() throws HibernateException, SQLException {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Organization ifa = new Organization( "IFA" );
+ Organization jboss = new Organization( "JBoss" );
+ Person gavin = new Person( "Gavin" );
+ Employment emp = new Employment( gavin, jboss, "AU" );
+ s.persist( ifa );
+ s.persist( jboss );
+ s.persist( gavin );
+ s.persist( emp );
+
+ Query namedQuery = s.getNamedQuery( "selectAllEmployments" );
+ List list = namedQuery.list();
+ assertTrue( list.get( 0 ) instanceof Employment );
+ s.delete( emp );
+ s.delete( ifa );
+ s.delete( jboss );
+ s.delete( gavin );
+
+ t.commit();
+ s.close();
+ }
+
+
+}
diff --git a/test/org/hibernate/test/sql/hand/custom/datadirect/oracle/DataDirectOracleCustomSQLTest.java b/test/org/hibernate/test/sql/hand/custom/datadirect/oracle/DataDirectOracleCustomSQLTest.java
new file mode 100644
index 0000000000..5836d24270
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/custom/datadirect/oracle/DataDirectOracleCustomSQLTest.java
@@ -0,0 +1,35 @@
+//$Id$
+package org.hibernate.test.sql.hand.custom.datadirect.oracle;
+
+import junit.framework.Test;
+
+import org.hibernate.dialect.DataDirectOracle9Dialect;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.test.sql.hand.custom.CustomStoredProcTestSupport;
+
+/**
+ * Custom SQL tests for Oracle via the DataDirect drivers.
+ *
+ * @author Max Rydahl Andersen
+ */
+public class DataDirectOracleCustomSQLTest extends CustomStoredProcTestSupport {
+
+ public DataDirectOracleCustomSQLTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "sql/hand/custom/oracle/Mappings.hbm.xml", "sql/hand/custom/datadirect/oracle/StoredProcedures.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( DataDirectOracleCustomSQLTest.class );
+ }
+
+ public boolean appliesTo(Dialect dialect) {
+ return ( dialect instanceof DataDirectOracle9Dialect );
+ }
+
+}
+
diff --git a/test/org/hibernate/test/sql/hand/custom/datadirect/oracle/StoredProcedures.hbm.xml b/test/org/hibernate/test/sql/hand/custom/datadirect/oracle/StoredProcedures.hbm.xml
new file mode 100644
index 0000000000..c0e03329fe
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/custom/datadirect/oracle/StoredProcedures.hbm.xml
@@ -0,0 +1,44 @@
+
+
+
+
+
+
+
+
+
+ { call simpleScalar(:number) }
+
+
+
+
+ { call testParamHandling(?,?) }
+
+
+
+
+
+ { call testParamHandling(?,:second) }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ { call allEmployments() }
+
+
+
diff --git a/test/org/hibernate/test/sql/hand/custom/db2/DB2CustomSQLTest.java b/test/org/hibernate/test/sql/hand/custom/db2/DB2CustomSQLTest.java
new file mode 100644
index 0000000000..43ba22a985
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/custom/db2/DB2CustomSQLTest.java
@@ -0,0 +1,35 @@
+//$Id$
+package org.hibernate.test.sql.hand.custom.db2;
+
+import junit.framework.Test;
+
+import org.hibernate.dialect.DB2Dialect;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.test.sql.hand.custom.CustomStoredProcTestSupport;
+
+/**
+ * Custom SQL tests for DB2
+ *
+ * @author Max Rydahl Andersen
+ */
+public class DB2CustomSQLTest extends CustomStoredProcTestSupport {
+
+ public DB2CustomSQLTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "sql/hand/custom/db2/Mappings.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( DB2CustomSQLTest.class );
+ }
+
+ public boolean appliesTo(Dialect dialect) {
+ return ( dialect instanceof DB2Dialect);
+ }
+
+}
+
diff --git a/test/org/hibernate/test/sql/hand/custom/db2/Mappings.hbm.xml b/test/org/hibernate/test/sql/hand/custom/db2/Mappings.hbm.xml
new file mode 100644
index 0000000000..0a9cc15cce
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/custom/db2/Mappings.hbm.xml
@@ -0,0 +1,236 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ INSERT INTO ORGANIZATION (NAME, ORGID) VALUES ( UPPER(? || ''), ? )
+ UPDATE ORGANIZATION SET NAME=UPPER(? || '') WHERE ORGID=?
+ DELETE FROM ORGANIZATION WHERE ORGID=?
+
+
+
+
+
+
+
+
+ INSERT INTO PERSON (NAME, PERID) VALUES ( UPPER(? || ''), ? )
+ UPDATE PERSON SET NAME=UPPER(? || '') WHERE PERID=?
+ DELETE FROM PERSON WHERE PERID=?
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ INSERT INTO EMPLOYMENT
+ (EMPLOYEE, EMPLOYER, STARTDATE, REGIONCODE, VALUE, CURRENCY, EMPID)
+
+ VALUES (?, ?, TIMESTAMP ('2006-02-28 11:39:00'), UPPER(? || ''), ?, ?, ?)
+
+ UPDATE EMPLOYMENT SET ENDDATE=?, VALUE=?, CURRENCY=? WHERE EMPID=?
+ DELETE FROM EMPLOYMENT WHERE EMPID=?
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ SELECT NAME AS {p.name}, PERID AS {p.id} FROM PERSON WHERE PERID=? /*FOR UPDATE*/
+
+
+
+
+
+ SELECT {org.*}, {emp.*}
+ FROM ORGANIZATION org
+ LEFT OUTER JOIN EMPLOYMENT emp ON org.ORGID = emp.EMPLOYER
+ WHERE org.ORGID=?
+
+
+
+
+
+
+
+ SELECT DISTINCT org.NAME AS {org.name}, org.ORGID AS {org.id}
+ FROM ORGANIZATION org
+ INNER JOIN EMPLOYMENT e ON e.EMPLOYER = org.ORGID
+
+
+
+
+
+
+
+
+ SELECT EMPLOYEE AS {emp.employee}, EMPLOYER AS {emp.employer},
+ STARTDATE AS {emp.startDate}, ENDDATE AS {emp.endDate},
+ REGIONCODE as {emp.regionCode}, EMPID AS {emp.id}
+ FROM EMPLOYMENT
+ WHERE EMPID = ?
+
+
+
+
+ SELECT {empcol.*}
+ FROM EMPLOYMENT empcol
+ WHERE EMPLOYER = :id
+ ORDER BY STARTDATE ASC, EMPLOYEE ASC
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ SELECT EMPLOYEE AS {emp.employee}, EMPLOYER AS {emp.employer},
+ STARTDATE AS {emp.startDate}, ENDDATE AS {emp.endDate},
+ REGIONCODE as {emp.regionCode}, EMPID AS {emp.id}, VALUE, CURRENCY
+ FROM EMPLOYMENT
+ WHERE EMPLOYER = :id AND ENDDATE IS NULL
+ ORDER BY STARTDATE ASC
+
+
+
+
+
+ { call HIBDB2TST.simpleScalar(:number) }
+
+
+
+
+
+ { call HIBDB2TST.paramHandling(?,?) }
+
+
+
+
+
+ { call HIBDB2TST.paramHandling(?,:second) }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ { call HIBDB2TST.selectAllEmployments() }
+
+
+
+
+ CREATE SCHEMA HIBDB2TST
+ DROP SCHEMA HIBDB2TST RESTRICT
+
+
+
+
+ CREATE PROCEDURE HIBDB2TST.selectAllEmployments ()
+ P1: BEGIN
+ DECLARE C1 CURSOR WITH RETURN FOR
+ SELECT EMPLOYEE, EMPLOYER, STARTDATE, ENDDATE,
+ REGIONCODE, EMPID, VALUE, CURRENCY
+ FROM EMPLOYMENT;
+ OPEN C1;
+ END P1
+
+
+ DROP PROCEDURE HIBDB2TST.selectAllEmployments
+
+
+
+
+
+
+ CREATE PROCEDURE HIBDB2TST.paramHandling (IN j SMALLINT, IN i SMALLINT)
+ P1: BEGIN
+ DECLARE C1 CURSOR WITH RETURN FOR
+ SELECT j as value, i as value2 from sysibm.sysdummy1;
+ OPEN C1;
+ END P1
+
+
+ DROP PROCEDURE HIBDB2TST.paramHandling
+
+
+
+
+
+ CREATE PROCEDURE HIBDB2TST.simpleScalar (IN j SMALLINT)
+ P1: BEGIN
+ DECLARE C1 CURSOR WITH RETURN FOR
+ SELECT j as value, 'getAll' as name from sysibm.sysdummy1;
+ OPEN C1;
+ END P1
+
+
+ DROP PROCEDURE HIBDB2TST.simpleScalar
+
+
+
diff --git a/test/org/hibernate/test/sql/hand/custom/mysql/Mappings.hbm.xml b/test/org/hibernate/test/sql/hand/custom/mysql/Mappings.hbm.xml
new file mode 100644
index 0000000000..ebb445512e
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/custom/mysql/Mappings.hbm.xml
@@ -0,0 +1,216 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ INSERT INTO ORGANIZATION (NAME, ORGID) VALUES ( UPPER(?), ? )
+ UPDATE ORGANIZATION SET NAME=UPPER(?) WHERE ORGID=?
+ DELETE FROM ORGANIZATION WHERE ORGID=?
+
+
+
+
+
+
+
+
+ INSERT INTO PERSON (NAME, PERID) VALUES ( UPPER(?), ? )
+ UPDATE PERSON SET NAME=UPPER(?) WHERE PERID=?
+ DELETE FROM PERSON WHERE PERID=?
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ INSERT INTO EMPLOYMENT
+ (EMPLOYEE, EMPLOYER, STARTDATE, REGIONCODE, VALUE, CURRENCY, EMPID)
+ VALUES (?, ?, now(), UPPER(?), ?, ?, ?)
+
+ UPDATE EMPLOYMENT SET ENDDATE=?, VALUE=?, CURRENCY=? WHERE EMPID=?
+ DELETE FROM EMPLOYMENT WHERE EMPID=?
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ SELECT NAME AS {p.name}, PERID AS {p.id} FROM PERSON WHERE PERID=? /*FOR UPDATE*/
+
+
+
+
+
+ SELECT {org.*}, {emp.*}
+ FROM ORGANIZATION org
+ LEFT OUTER JOIN EMPLOYMENT emp ON org.ORGID = emp.EMPLOYER
+ WHERE org.ORGID=?
+
+
+
+
+
+
+
+
+ SELECT DISTINCT org.NAME AS {org.name}, org.ORGID AS {org.id}
+ FROM ORGANIZATION org
+ INNER JOIN EMPLOYMENT e ON e.EMPLOYER = org.ORGID
+
+
+
+
+ SELECT EMPLOYEE AS {emp.employee}, EMPLOYER AS {emp.employer},
+ STARTDATE AS {emp.startDate}, ENDDATE AS {emp.endDate},
+ REGIONCODE as {emp.regionCode}, EMPID AS {emp.id}
+ FROM EMPLOYMENT
+ WHERE EMPID = ?
+
+
+
+
+
+ SELECT {empcol.*}
+ FROM EMPLOYMENT empcol
+ WHERE EMPLOYER = :id
+ ORDER BY STARTDATE ASC, EMPLOYEE ASC
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ SELECT EMPLOYEE AS {emp.employee}, EMPLOYER AS {emp.employer},
+ STARTDATE AS {emp.startDate}, ENDDATE AS {emp.endDate},
+ REGIONCODE as {emp.regionCode}, EMPID AS {emp.id}, VALUE, CURRENCY
+ FROM EMPLOYMENT
+ WHERE EMPLOYER = :id AND ENDDATE IS NULL
+ ORDER BY STARTDATE ASC
+
+
+
+
+
+ { call simpleScalar(:number) }
+
+
+
+
+
+ { call paramHandling(?,?) }
+
+
+
+
+
+ { call paramHandling(?,:second) }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ { call selectAllEmployments() }
+
+
+
+
+ CREATE PROCEDURE selectAllEmployments ()
+ SELECT EMPLOYEE, EMPLOYER, STARTDATE, ENDDATE,
+ REGIONCODE, EMPID, VALUE, CURRENCY
+ FROM EMPLOYMENT
+
+
+ DROP PROCEDURE selectAllEmployments
+
+
+
+
+
+ CREATE PROCEDURE paramHandling (j int, i int)
+ SELECT j AS value, i AS value2
+
+
+ DROP PROCEDURE paramHandling
+
+
+
+
+
+ CREATE PROCEDURE simpleScalar (number int)
+ SELECT number AS value, 'getAll' AS name
+
+
+ DROP PROCEDURE simpleScalar
+
+
+
+
diff --git a/test/org/hibernate/test/sql/hand/custom/mysql/MySQLCustomSQLTest.java b/test/org/hibernate/test/sql/hand/custom/mysql/MySQLCustomSQLTest.java
new file mode 100644
index 0000000000..5bb1a58239
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/custom/mysql/MySQLCustomSQLTest.java
@@ -0,0 +1,34 @@
+//$Id: MySQLCustomSQLTest.java 10977 2006-12-12 17:28:04 -0600 (Tue, 12 Dec 2006) steve.ebersole@jboss.com $
+package org.hibernate.test.sql.hand.custom.mysql;
+
+import junit.framework.Test;
+
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.MySQLDialect;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.test.sql.hand.custom.CustomStoredProcTestSupport;
+
+/**
+ * Custom SQL tests for MySQL
+ *
+ * @author Gavin King
+ */
+public class MySQLCustomSQLTest extends CustomStoredProcTestSupport {
+
+ public MySQLCustomSQLTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "sql/hand/custom/mysql/Mappings.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( MySQLCustomSQLTest.class );
+ }
+
+ public boolean appliesTo(Dialect dialect) {
+ return ( dialect instanceof MySQLDialect );
+ }
+}
+
diff --git a/test/org/hibernate/test/sql/hand/custom/oracle/Mappings.hbm.xml b/test/org/hibernate/test/sql/hand/custom/oracle/Mappings.hbm.xml
new file mode 100644
index 0000000000..7dfbf585eb
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/custom/oracle/Mappings.hbm.xml
@@ -0,0 +1,209 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ INSERT INTO ORGANIZATION (NAME, ORGID) VALUES ( UPPER(?), ? )
+ UPDATE ORGANIZATION SET NAME=UPPER(?) WHERE ORGID=?
+ DELETE FROM ORGANIZATION WHERE ORGID=?
+
+
+
+
+
+
+
+
+ {call createPerson(?,?)}
+ UPDATE PERSON SET NAME=UPPER(?) WHERE PERID=?
+ DELETE FROM PERSON WHERE PERID=?
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ INSERT INTO EMPLOYMENT
+ (EMPLOYEE, EMPLOYER, STARTDATE, REGIONCODE, VALUE, CURRENCY, EMPID)
+ VALUES (?, ?, CURRENT_DATE, UPPER(?), ?, ?, ?)
+
+ UPDATE EMPLOYMENT SET ENDDATE=?, VALUE=?, CURRENCY=? WHERE EMPID=?
+ DELETE FROM EMPLOYMENT WHERE EMPID=?
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ SELECT NAME AS {p.name}, PERID AS {p.id} FROM PERSON WHERE PERID=? /*FOR UPDATE*/
+
+
+
+
+
+ SELECT {org.*}, {emp.*}
+ FROM ORGANIZATION org
+ LEFT OUTER JOIN EMPLOYMENT emp ON org.ORGID = emp.EMPLOYER
+ WHERE org.ORGID=?
+
+
+
+
+
+ SELECT DISTINCT org.NAME AS {org.name}, org.ORGID AS {org.id}
+ FROM ORGANIZATION org
+ INNER JOIN EMPLOYMENT e ON e.EMPLOYER = org.ORGID
+
+
+
+
+
+ SELECT EMPLOYEE AS {emp.employee}, EMPLOYER AS {emp.employer},
+ STARTDATE AS {emp.startDate}, ENDDATE AS {emp.endDate},
+ REGIONCODE as {emp.regionCode}, EMPID AS {emp.id}
+ FROM EMPLOYMENT
+ WHERE EMPID = ?
+
+
+
+
+
+ SELECT {empcol.*}
+ FROM EMPLOYMENT empcol
+ WHERE EMPLOYER = :id
+ ORDER BY STARTDATE ASC, EMPLOYEE ASC
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ SELECT EMPLOYEE AS {emp.employee}, EMPLOYER AS {emp.employer},
+ STARTDATE AS {emp.startDate}, ENDDATE AS {emp.endDate},
+ REGIONCODE as {emp.regionCode}, EMPID AS {emp.id}, VALUE, CURRENCY
+ FROM EMPLOYMENT
+ WHERE EMPLOYER = :id AND ENDDATE IS NULL
+ ORDER BY STARTDATE ASC
+
+
+
+
+ CREATE OR REPLACE FUNCTION testParamHandling (j number, i number)
+ RETURN SYS_REFCURSOR AS st_cursor SYS_REFCURSOR;
+ BEGIN
+ OPEN st_cursor FOR
+ SELECT j as value, i as value2 from dual;
+ RETURN st_cursor;
+ END;
+
+
+ DROP FUNCTION testParamHandling
+
+
+
+
+
+ CREATE OR REPLACE FUNCTION simpleScalar (j number)
+ RETURN SYS_REFCURSOR AS st_cursor SYS_REFCURSOR;
+ BEGIN
+ OPEN st_cursor FOR
+ SELECT j as value, 'getAll' as name from dual;
+ RETURN st_cursor;
+ END;
+
+
+ DROP FUNCTION simpleScalar
+
+
+
+
+
+ CREATE OR REPLACE FUNCTION allEmployments
+ RETURN SYS_REFCURSOR AS st_cursor SYS_REFCURSOR;
+ BEGIN
+ OPEN st_cursor FOR
+ SELECT EMPLOYEE, EMPLOYER, STARTDATE, ENDDATE,
+ REGIONCODE, EMPID, VALUE, CURRENCY
+ FROM EMPLOYMENT;
+ RETURN st_cursor;
+ END;
+
+
+ DROP FUNCTION allEmployments
+
+
+
+
+
+ CREATE OR REPLACE PROCEDURE createPerson(p_name PERSON.NAME%TYPE, p_id PERSON.PERID%TYPE)
+ AS
+ rowcount INTEGER;
+ BEGIN
+ INSERT INTO PERSON ( PERID, NAME ) VALUES ( p_id, UPPER( p_name ) );
+ rowcount := SQL%ROWCOUNT;
+ IF rowcount = 1 THEN
+ NULL;
+ ELSE
+ RAISE_APPLICATION_ERROR( -20001, 'Unexpected rowcount [' || rowcount || ']' );
+ END IF;
+ END;
+
+
+ DROP PROCEDURE createPerson;
+
+
+
+
diff --git a/test/org/hibernate/test/sql/hand/custom/oracle/OracleCustomSQLTest.java b/test/org/hibernate/test/sql/hand/custom/oracle/OracleCustomSQLTest.java
new file mode 100644
index 0000000000..c07b224b13
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/custom/oracle/OracleCustomSQLTest.java
@@ -0,0 +1,36 @@
+//$Id$
+package org.hibernate.test.sql.hand.custom.oracle;
+
+import junit.framework.Test;
+
+import org.hibernate.dialect.DataDirectOracle9Dialect;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.Oracle9Dialect;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.test.sql.hand.custom.CustomStoredProcTestSupport;
+
+/**
+ * Custom SQL tests for Oracle
+ *
+ * @author Gavin King
+ */
+public class OracleCustomSQLTest extends CustomStoredProcTestSupport {
+
+ public OracleCustomSQLTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "sql/hand/custom/oracle/Mappings.hbm.xml", "sql/hand/custom/oracle/StoredProcedures.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( OracleCustomSQLTest.class );
+ }
+
+ public boolean appliesTo(Dialect dialect) {
+ return ( dialect instanceof Oracle9Dialect ) && !( dialect instanceof DataDirectOracle9Dialect );
+ }
+
+}
+
diff --git a/test/org/hibernate/test/sql/hand/custom/oracle/StoredProcedures.hbm.xml b/test/org/hibernate/test/sql/hand/custom/oracle/StoredProcedures.hbm.xml
new file mode 100644
index 0000000000..85b2bfed09
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/custom/oracle/StoredProcedures.hbm.xml
@@ -0,0 +1,45 @@
+
+
+
+
+
+
+
+
+
+ { ? = call simpleScalar(:number) }
+
+
+
+
+
+ { ? = call testParamHandling(?,?) }
+
+
+
+
+
+ { ? = call testParamHandling(?,:second) }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ { ? = call allEmployments() }
+
+
+
diff --git a/test/org/hibernate/test/sql/hand/custom/sybase/Mappings.hbm.xml b/test/org/hibernate/test/sql/hand/custom/sybase/Mappings.hbm.xml
new file mode 100644
index 0000000000..e6a9fcb7f3
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/custom/sybase/Mappings.hbm.xml
@@ -0,0 +1,217 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ INSERT INTO ORGANIZATION (NAME, ORGID) VALUES ( UPPER(?), ? )
+ UPDATE ORGANIZATION SET NAME=UPPER(?) WHERE ORGID=?
+ DELETE FROM ORGANIZATION WHERE ORGID=?
+
+
+
+
+
+
+
+
+ INSERT INTO PERSON (NAME, PERID) VALUES ( UPPER(?), ? )
+ UPDATE PERSON SET NAME=UPPER(?) WHERE PERID=?
+ DELETE FROM PERSON WHERE PERID=?
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ INSERT INTO EMPLOYMENT
+ (EMPLOYEE, EMPLOYER, STARTDATE, REGIONCODE, VALUE, CURRENCY, EMPID)
+ VALUES (?, ?, getdate(), UPPER(?), ?, ?, ?)
+
+ UPDATE EMPLOYMENT SET ENDDATE=?, VALUE=?, CURRENCY=? WHERE EMPID=?
+ DELETE FROM EMPLOYMENT WHERE EMPID=?
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ SELECT NAME AS {p.name}, PERID AS {p.id} FROM PERSON WHERE PERID=? /*FOR UPDATE*/
+
+
+
+
+
+ SELECT {org.*}, {emp.*}
+ FROM ORGANIZATION org
+ LEFT OUTER JOIN EMPLOYMENT emp ON org.ORGID = emp.EMPLOYER
+ WHERE org.ORGID=?
+
+
+
+
+
+
+
+ SELECT DISTINCT org.NAME AS {org.name}, org.ORGID AS {org.id}
+ FROM ORGANIZATION org
+ INNER JOIN EMPLOYMENT e ON e.EMPLOYER = org.ORGID
+
+
+
+
+
+
+
+
+ SELECT EMPLOYEE AS {emp.employee}, EMPLOYER AS {emp.employer},
+ STARTDATE AS {emp.startDate}, ENDDATE AS {emp.endDate},
+ REGIONCODE as {emp.regionCode}, EMPID AS {emp.id}
+ FROM EMPLOYMENT
+ WHERE EMPID = ?
+
+
+
+
+ SELECT {empcol.*}
+ FROM EMPLOYMENT empcol
+ WHERE EMPLOYER = :id
+ ORDER BY STARTDATE ASC, EMPLOYEE ASC
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ SELECT EMPLOYEE AS {emp.employee}, EMPLOYER AS {emp.employer},
+ STARTDATE AS {emp.startDate}, ENDDATE AS {emp.endDate},
+ REGIONCODE as {emp.regionCode}, EMPID AS {emp.id}, VALUE, CURRENCY
+ FROM EMPLOYMENT
+ WHERE EMPLOYER = :id AND ENDDATE IS NULL
+ ORDER BY STARTDATE ASC
+
+
+
+
+
+ { call simpleScalar(:number) }
+
+
+
+
+
+ { call paramHandling(?,?) }
+
+
+
+
+
+ { call paramHandling(?,:second) }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ { call selectAllEmployments() }
+
+
+
+
+ CREATE PROCEDURE selectAllEmployments AS
+ SELECT EMPLOYEE, EMPLOYER, STARTDATE, ENDDATE,
+ REGIONCODE, EMPID, VALUE, CURRENCY
+ FROM EMPLOYMENT
+
+
+ DROP PROCEDURE selectAllEmployments
+
+
+
+
+
+ CREATE PROCEDURE paramHandling @j int, @i int AS
+ SELECT @j as value, @i as value2
+
+
+ DROP PROCEDURE paramHandling
+
+
+
+
+
+ CREATE PROCEDURE simpleScalar @number int AS
+ SELECT @number as value, 'getAll' as name
+
+
+ DROP PROCEDURE simpleScalar
+
+
+
+
diff --git a/test/org/hibernate/test/sql/hand/custom/sybase/SybaseCustomSQLTest.java b/test/org/hibernate/test/sql/hand/custom/sybase/SybaseCustomSQLTest.java
new file mode 100644
index 0000000000..bd2524bbb8
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/custom/sybase/SybaseCustomSQLTest.java
@@ -0,0 +1,34 @@
+//$Id$
+package org.hibernate.test.sql.hand.custom.sybase;
+
+import junit.framework.Test;
+
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.SybaseDialect;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.test.sql.hand.custom.CustomStoredProcTestSupport;
+
+/**
+ * Custom SQL tests for Sybase/SQLServer (Transact-SQL)
+ *
+ * @author Gavin King
+ */
+public class SybaseCustomSQLTest extends CustomStoredProcTestSupport {
+
+ public SybaseCustomSQLTest(String str) {
+ super( str );
+ }
+
+ public String[] getMappings() {
+ return new String[] { "sql/hand/custom/sybase/Mappings.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( SybaseCustomSQLTest.class );
+ }
+
+ public boolean appliesTo(Dialect dialect) {
+ return ( dialect instanceof SybaseDialect );
+ }
+}
+
diff --git a/test/org/hibernate/test/sql/hand/identity/CustomInsertSQLWithIdentityColumnTest.java b/test/org/hibernate/test/sql/hand/identity/CustomInsertSQLWithIdentityColumnTest.java
new file mode 100644
index 0000000000..938ea29a76
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/identity/CustomInsertSQLWithIdentityColumnTest.java
@@ -0,0 +1,50 @@
+package org.hibernate.test.sql.hand.identity;
+
+import junit.framework.Test;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.junit.functional.DatabaseSpecificFunctionalTestCase;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.Session;
+import org.hibernate.JDBCException;
+import org.hibernate.test.sql.hand.Organization;
+
+/**
+ * Custom SQL tests for combined usage of custom insert SQL and identity columns
+ *
+ * @author Gail Badner
+ */
+public class CustomInsertSQLWithIdentityColumnTest extends DatabaseSpecificFunctionalTestCase {
+
+ public CustomInsertSQLWithIdentityColumnTest(String str) {
+ super( str );
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( CustomInsertSQLWithIdentityColumnTest.class );
+ }
+
+ public String[] getMappings() {
+ return new String[] {"sql/hand/identity/Mappings.hbm.xml"};
+ }
+
+ public boolean appliesTo(Dialect dialect) {
+ return dialect.supportsIdentityColumns();
+ }
+
+ public void testBadInsertionFails() {
+ Session session = openSession();
+ session.beginTransaction();
+ Organization org = new Organization( "hola!" );
+ try {
+ session.save( org );
+ session.delete( org );
+ fail( "expecting bad custom insert statement to fail" );
+ }
+ catch( JDBCException e ) {
+ // expected failure
+ }
+
+ session.getTransaction().rollback();
+ session.close();
+ }
+}
diff --git a/test/org/hibernate/test/sql/hand/identity/Mappings.hbm.xml b/test/org/hibernate/test/sql/hand/identity/Mappings.hbm.xml
new file mode 100644
index 0000000000..daf21afcc4
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/identity/Mappings.hbm.xml
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+ INSERT INTO PERSON WHERE x=y
+
+
+
diff --git a/test/org/hibernate/test/sql/hand/query/NativeSQLQueries.hbm.xml b/test/org/hibernate/test/sql/hand/query/NativeSQLQueries.hbm.xml
new file mode 100644
index 0000000000..4d42100b26
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/query/NativeSQLQueries.hbm.xml
@@ -0,0 +1,262 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ select id as id,
+ fld_name as name,
+ fld_model as model,
+ fld_speed as speed,
+ fld_length as length,
+ fld_width as width,
+ fld_length * fld_width as surface,
+ fld_length * fld_width *10 as volume
+ from SpaceShip
+
+
+
+
+ SELECT org.NAME FROM ORGANIZATION org
+
+
+
+
+
+ SELECT org.NAME AS thename, org.NAME AS {org.name}, org.ORGID AS {org.id}
+ FROM ORGANIZATION org
+ ORDER BY thename
+
+
+
+
+
+ SELECT org.NAME AS thename, org.NAME AS {org.name}, org.ORGID AS {org.id}
+ FROM ORGANIZATION org
+ ORDER BY thename
+
+
+
+
+
+ SELECT NAME AS thename, ORGID AS orgid
+ FROM ORGANIZATION
+ ORDER BY thename
+
+
+
+
+ SELECT * FROM EMPLOYMENT
+
+
+
+
+
+ SELECT * FROM EMPLOYMENT, PERSON
+
+
+
+
+ SELECT empcol.EMPLOYER as {empcol.key}, empcol.EMPID as {empcol.element}, {empcol.element.*}
+ FROM EMPLOYMENT empcol
+ WHERE EMPLOYER = :id
+ ORDER BY STARTDATE ASC, EMPLOYEE ASC
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ SELECT org.ORGID as orgid,
+ org.NAME as name,
+ emp.EMPLOYER as employer,
+ emp.EMPID as empid,
+ emp.EMPLOYEE as employee,
+ emp.EMPLOYER as employer,
+ emp.STARTDATE as xstartDate,
+ emp.ENDDATE as endDate,
+ emp.REGIONCODE as regionCode,
+ emp.VALUE as VALUE,
+ emp.CURRENCY as CURRENCY
+ FROM ORGANIZATION org
+ LEFT OUTER JOIN EMPLOYMENT emp ON org.ORGID = emp.EMPLOYER
+
+
+
+
+
+
+
+ SELECT org.ORGID as orgid,
+ org.NAME as name,
+ emp.EMPLOYER as employer,
+ emp.EMPID as empid,
+ emp.EMPLOYEE as employee,
+ emp.EMPLOYER as employer,
+ emp.STARTDATE as startDate,
+ emp.ENDDATE as endDate,
+ emp.REGIONCODE as regionCode,
+ emp.VALUE as VALUE,
+ emp.CURRENCY as CURRENCY
+ FROM ORGANIZATION org
+ LEFT OUTER JOIN EMPLOYMENT emp ON org.ORGID = emp.EMPLOYER
+
+
+
\ No newline at end of file
diff --git a/test/org/hibernate/test/sql/hand/query/NativeSQLQueriesTest.java b/test/org/hibernate/test/sql/hand/query/NativeSQLQueriesTest.java
new file mode 100644
index 0000000000..826e8430dc
--- /dev/null
+++ b/test/org/hibernate/test/sql/hand/query/NativeSQLQueriesTest.java
@@ -0,0 +1,620 @@
+package org.hibernate.test.sql.hand.query;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import junit.framework.Test;
+
+import org.hibernate.Hibernate;
+import org.hibernate.HibernateException;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.test.sql.hand.Organization;
+import org.hibernate.test.sql.hand.Person;
+import org.hibernate.test.sql.hand.Employment;
+import org.hibernate.test.sql.hand.Product;
+import org.hibernate.test.sql.hand.Order;
+import org.hibernate.test.sql.hand.Dimension;
+import org.hibernate.test.sql.hand.SpaceShip;
+import org.hibernate.test.sql.hand.Speech;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.transform.DistinctRootEntityResultTransformer;
+import org.hibernate.transform.Transformers;
+import org.hibernate.transform.AliasToEntityMapResultTransformer;
+
+/**
+ * Tests of various features of native SQL queries.
+ *
+ * @author Steve Ebersole
+ */
+public class NativeSQLQueriesTest extends FunctionalTestCase {
+
+ public NativeSQLQueriesTest(String x) {
+ super( x );
+ }
+
+ public String[] getMappings() {
+ return new String[] { "sql/hand/query/NativeSQLQueries.hbm.xml" };
+ }
+
+ public void configure(Configuration cfg) {
+ super.configure( cfg );
+ cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( NativeSQLQueriesTest.class );
+ }
+
+ protected String getOrganizationFetchJoinEmploymentSQL() {
+ return "SELECT org.ORGID as {org.id}, " +
+ " org.NAME as {org.name}, " +
+ " emp.EMPLOYER as {emp.key}, " +
+ " emp.EMPID as {emp.element}, " +
+ " {emp.element.*} " +
+ "FROM ORGANIZATION org " +
+ " LEFT OUTER JOIN EMPLOYMENT emp ON org.ORGID = emp.EMPLOYER";
+ }
+
+ protected String getOrganizationJoinEmploymentSQL() {
+ return "SELECT org.ORGID as {org.id}, " +
+ " org.NAME as {org.name}, " +
+ " {emp.*} " +
+ "FROM ORGANIZATION org " +
+ " LEFT OUTER JOIN EMPLOYMENT emp ON org.ORGID = emp.EMPLOYER";
+ }
+
+ protected String getEmploymentSQL() {
+ return "SELECT * FROM EMPLOYMENT";
+ }
+
+ protected String getEmploymentSQLMixedScalarEntity() {
+ return "SELECT e.*, e.employer as employerid FROM EMPLOYMENT e" ;
+ }
+
+ protected String getOrgEmpRegionSQL() {
+ return "select {org.*}, {emp.*}, emp.REGIONCODE " +
+ "from ORGANIZATION org " +
+ " left outer join EMPLOYMENT emp on org.ORGID = emp.EMPLOYER";
+ }
+
+ protected String getOrgEmpPersonSQL() {
+ return "select {org.*}, {emp.*}, {pers.*} " +
+ "from ORGANIZATION org " +
+ " join EMPLOYMENT emp on org.ORGID = emp.EMPLOYER " +
+ " join PERSON pers on pers.PERID = emp.EMPLOYEE ";
+ }
+
+ public void testFailOnNoAddEntityOrScalar() {
+ // Note: this passes, but for the wrong reason.
+ // there is actually an exception thrown, but it is the database
+ // throwing a sql exception because the SQL gets passed
+ // "un-processed"...
+ Session s = openSession();
+ s.beginTransaction();
+ try {
+ String sql = "select {org.*} " +
+ "from organization org";
+ s.createSQLQuery( sql ).list();
+ fail( "Should throw an exception since no addEntity nor addScalar has been performed." );
+ }
+ catch( HibernateException he) {
+ // expected behavior
+ }
+ finally {
+ s.getTransaction().rollback();
+ s.close();
+ }
+ }
+
+ public void testManualSynchronization() {
+ Session s = openSession();
+ s.beginTransaction();
+
+ sfi().getStatistics().clear();
+
+ // create an Organization...
+ Organization jboss = new Organization( "JBoss" );
+ s.persist( jboss );
+
+ // now query on Employment, this should not cause an auto-flush
+ s.createSQLQuery( getEmploymentSQL() ).list();
+ assertEquals( 0, sfi().getStatistics().getEntityInsertCount() );
+
+ // now try to query on Employment but this time add Organization as a synchronized query space...
+ s.createSQLQuery( getEmploymentSQL() ).addSynchronizedEntityClass( Organization.class ).list();
+ assertEquals( 1, sfi().getStatistics().getEntityInsertCount() );
+
+ // clean up
+ s.delete( jboss );
+ s.getTransaction().commit();
+ s.close();
+ }
+
+ public void testSQLQueryInterface() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Organization ifa = new Organization("IFA");
+ Organization jboss = new Organization("JBoss");
+ Person gavin = new Person("Gavin");
+ Employment emp = new Employment(gavin, jboss, "AU");
+
+ s.persist(ifa);
+ s.persist(jboss);
+ s.persist(gavin);
+ s.persist(emp);
+
+ List l = s.createSQLQuery( getOrgEmpRegionSQL() )
+ .addEntity("org", Organization.class)
+ .addJoin("emp", "org.employments")
+ .addScalar("regionCode", Hibernate.STRING)
+ .list();
+ assertEquals( 2, l.size() );
+
+ l = s.createSQLQuery( getOrgEmpPersonSQL() )
+ .addEntity("org", Organization.class)
+ .addJoin("emp", "org.employments")
+ .addJoin("pers", "emp.employee")
+ .list();
+ assertEquals( l.size(), 1 );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ l = s.createSQLQuery( "select {org.*}, {emp.*} " +
+ "from ORGANIZATION org " +
+ " left outer join EMPLOYMENT emp on org.ORGID = emp.EMPLOYER, ORGANIZATION org2" )
+ .addEntity("org", Organization.class)
+ .addJoin("emp", "org.employments")
+ .setResultTransformer(new DistinctRootEntityResultTransformer())
+ .list();
+ assertEquals( l.size(), 2 );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ s.delete(emp);
+ s.delete(gavin);
+ s.delete(ifa);
+ s.delete(jboss);
+
+ t.commit();
+ s.close();
+ }
+
+ public void testResultSetMappingDefinition() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Organization ifa = new Organization("IFA");
+ Organization jboss = new Organization("JBoss");
+ Person gavin = new Person("Gavin");
+ Employment emp = new Employment(gavin, jboss, "AU");
+
+ s.persist(ifa);
+ s.persist(jboss);
+ s.persist(gavin);
+ s.persist(emp);
+
+ List l = s.createSQLQuery( getOrgEmpRegionSQL() )
+ .setResultSetMapping( "org-emp-regionCode" )
+ .list();
+ assertEquals( l.size(), 2 );
+
+ l = s.createSQLQuery( getOrgEmpPersonSQL() )
+ .setResultSetMapping( "org-emp-person" )
+ .list();
+ assertEquals( l.size(), 1 );
+
+ s.delete(emp);
+ s.delete(gavin);
+ s.delete(ifa);
+ s.delete(jboss);
+
+ t.commit();
+ s.close();
+ }
+
+ public void testScalarValues() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Organization ifa = new Organization( "IFA" );
+ Organization jboss = new Organization( "JBoss" );
+
+ Serializable idIfa = s.save( ifa );
+ Serializable idJBoss = s.save( jboss );
+
+ s.flush();
+
+ List result = s.getNamedQuery( "orgNamesOnly" ).list();
+ assertTrue( result.contains( "IFA" ) );
+ assertTrue( result.contains( "JBoss" ) );
+
+ result = s.getNamedQuery( "orgNamesOnly" ).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
+ Map m = (Map) result.get(0);
+ assertEquals( 2, result.size() );
+ assertEquals( 1, m.size() );
+ assertTrue( m.containsKey("NAME") );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ Iterator iter = s.getNamedQuery( "orgNamesAndOrgs" ).list().iterator();
+ Object[] o = ( Object[] ) iter.next();
+ assertEquals( o[0], "IFA" );
+ assertEquals( ( ( Organization ) o[1] ).getName(), "IFA" );
+ o = ( Object[] ) iter.next();
+ assertEquals( o[0], "JBoss" );
+ assertEquals( ( ( Organization ) o[1] ).getName(), "JBoss" );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ // test that the ordering of the results is truly based on the order in which they were defined
+ iter = s.getNamedQuery( "orgsAndOrgNames" ).list().iterator();
+ Object[] row = ( Object[] ) iter.next();
+ assertEquals( "expecting non-scalar result first", Organization.class, row[0].getClass() );
+ assertEquals( "expecting scalar result second", String.class, row[1].getClass() );
+ assertEquals( ( ( Organization ) row[0] ).getName(), "IFA" );
+ assertEquals( row[1], "IFA" );
+ row = ( Object[] ) iter.next();
+ assertEquals( "expecting non-scalar result first", Organization.class, row[0].getClass() );
+ assertEquals( "expecting scalar result second", String.class, row[1].getClass() );
+ assertEquals( ( ( Organization ) row[0] ).getName(), "JBoss" );
+ assertEquals( row[1], "JBoss" );
+ assertFalse( iter.hasNext() );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ iter = s.getNamedQuery( "orgIdsAndOrgNames" ).list().iterator();
+ o = ( Object[] ) iter.next();
+ assertEquals( o[1], "IFA" );
+ assertEquals( o[0], idIfa );
+ o = ( Object[] ) iter.next();
+ assertEquals( o[1], "JBoss" );
+ assertEquals( o[0], idJBoss );
+
+ s.delete( ifa );
+ s.delete( jboss );
+ t.commit();
+ s.close();
+ }
+
+ public void testMappedAliasStrategy() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Organization ifa = new Organization("IFA");
+ Organization jboss = new Organization("JBoss");
+ Person gavin = new Person("Gavin");
+ Employment emp = new Employment(gavin, jboss, "AU");
+ Serializable orgId = s.save(jboss);
+ Serializable orgId2 = s.save(ifa);
+ s.save(gavin);
+ s.save(emp);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Query namedQuery = s.getNamedQuery("AllEmploymentAsMapped");
+ List list = namedQuery.list();
+ assertEquals(1,list.size());
+ Employment emp2 = (Employment) list.get(0);
+ assertEquals(emp2.getEmploymentId(), emp.getEmploymentId() );
+ assertEquals(emp2.getStartDate().getDate(), emp.getStartDate().getDate() );
+ assertEquals(emp2.getEndDate(), emp.getEndDate() );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Query sqlQuery = s.getNamedQuery("EmploymentAndPerson");
+ sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
+ list = sqlQuery.list();
+ assertEquals(1,list.size() );
+ Object res = list.get(0);
+ assertClassAssignability(res.getClass(),Map.class);
+ Map m = (Map) res;
+ assertEquals(2,m.size());
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ sqlQuery = s.getNamedQuery("organizationreturnproperty");
+ sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
+ list = sqlQuery.list();
+ assertEquals(2,list.size() );
+ m = (Map) list.get(0);
+ assertTrue(m.containsKey("org"));
+ assertClassAssignability(m.get("org").getClass(), Organization.class);
+ assertTrue(m.containsKey("emp"));
+ assertClassAssignability(m.get("emp").getClass(), Employment.class);
+ assertEquals(2, m.size());
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ namedQuery = s.getNamedQuery("EmploymentAndPerson");
+ list = namedQuery.list();
+ assertEquals(1,list.size() );
+ Object[] objs = (Object[]) list.get(0);
+ assertEquals(2, objs.length);
+ emp2 = (Employment) objs[0];
+ gavin = (Person) objs[1];
+ s.delete(emp2);
+ s.delete(jboss);
+ s.delete(gavin);
+ s.delete(ifa);
+ t.commit();
+ s.close();
+ }
+
+ /* test for native sql composite id joins which has never been implemented */
+ public void testCompositeIdJoinsFailureExpected() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Person person = new Person();
+ person.setName( "Noob" );
+
+ Product product = new Product();
+ product.setProductId( new Product.ProductId() );
+ product.getProductId().setOrgid( "x" );
+ product.getProductId().setProductnumber( "1234" );
+ product.setName( "Hibernate 3" );
+
+ Order order = new Order();
+ order.setOrderId( new Order.OrderId() );
+ order.getOrderId().setOrdernumber( "1" );
+ order.getOrderId().setOrgid( "y" );
+
+ product.getOrders().add( order );
+ order.setProduct( product );
+ order.setPerson( person );
+
+ s.save( product );
+ s.save( order);
+ s.save( person );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Product p = (Product) s.createQuery( "from Product p join fetch p.orders" ).list().get(0);
+ assertTrue(Hibernate.isInitialized( p.getOrders()));
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Object[] o = (Object[]) s.createSQLQuery( "select\r\n" +
+ " product.orgid as {product.id.orgid}," +
+ " product.productnumber as {product.id.productnumber}," +
+ " {prod_orders}.orgid as orgid3_1_,\r\n" +
+ " {prod_orders}.ordernumber as ordernum2_3_1_,\r\n" +
+ " product.name as {product.name}," +
+ " {prod_orders.element.*}" +
+ /*" orders.PROD_NO as PROD4_3_1_,\r\n" +
+ " orders.person as person3_1_,\r\n" +
+ " orders.PROD_ORGID as PROD3_0__,\r\n" +
+ " orders.PROD_NO as PROD4_0__,\r\n" +
+ " orders.orgid as orgid0__,\r\n" +
+ " orders.ordernumber as ordernum2_0__ \r\n" +*/
+ " from\r\n" +
+ " Product product \r\n" +
+ " inner join\r\n" +
+ " TBL_ORDER {prod_orders} \r\n" +
+ " on product.orgid={prod_orders}.PROD_ORGID \r\n" +
+ " and product.productnumber={prod_orders}.PROD_NO" )
+ .addEntity( "product", Product.class )
+ .addJoin( "prod_orders", "product.orders" )
+ .list().get(0);
+
+ p = (Product) o[0];
+ assertTrue(Hibernate.isInitialized( p.getOrders() ));
+ assertNotNull(p.getOrders().iterator().next());
+ t.commit();
+ s.close();
+ }
+
+ public void testAutoDetectAliasing() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Organization ifa = new Organization("IFA");
+ Organization jboss = new Organization("JBoss");
+ Person gavin = new Person("Gavin");
+ Employment emp = new Employment(gavin, jboss, "AU");
+ Serializable orgId = s.save(jboss);
+ Serializable orgId2 = s.save(ifa);
+ s.save(gavin);
+ s.save(emp);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ List list = s.createSQLQuery( getEmploymentSQL() )
+ .addEntity( Employment.class.getName() )
+ .list();
+ assertEquals( 1,list.size() );
+
+ Employment emp2 = (Employment) list.get(0);
+ assertEquals(emp2.getEmploymentId(), emp.getEmploymentId() );
+ assertEquals(emp2.getStartDate().getDate(), emp.getStartDate().getDate() );
+ assertEquals(emp2.getEndDate(), emp.getEndDate() );
+
+ s.clear();
+
+ list = s.createSQLQuery( getEmploymentSQL() )
+ .addEntity( Employment.class.getName() )
+ .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
+ .list();
+ assertEquals( 1,list.size() );
+ Map m = (Map) list.get(0);
+ assertTrue(m.containsKey("Employment"));
+ assertEquals(1,m.size());
+
+ list = s.createSQLQuery(getEmploymentSQL()).list();
+ assertEquals(1, list.size());
+ Object[] o = (Object[]) list.get(0);
+ assertEquals(8, o.length);
+
+ list = s.createSQLQuery( getEmploymentSQL() ).setResultTransformer( new UpperCasedAliasToEntityMapResultTransformer() ).list();
+ assertEquals(1, list.size());
+ m = (Map) list.get(0);
+ assertTrue(m.containsKey("EMPID"));
+ assertTrue(m.containsKey("VALUE"));
+ assertTrue(m.containsKey("ENDDATE"));
+ assertEquals(8, m.size());
+
+ list = s.createSQLQuery( getEmploymentSQLMixedScalarEntity() ).addScalar( "employerid" ).addEntity( Employment.class ).list();
+ assertEquals(1, list.size());
+ o = (Object[]) list.get(0);
+ assertEquals(2, o.length);
+ assertClassAssignability( o[0].getClass(), Number.class);
+ assertClassAssignability( o[1].getClass(), Employment.class);
+
+
+
+ Query queryWithCollection = s.getNamedQuery("organizationEmploymentsExplicitAliases");
+ queryWithCollection.setLong("id", jboss.getId() );
+ list = queryWithCollection.list();
+ assertEquals(list.size(),1);
+
+ s.clear();
+
+ list = s.createSQLQuery( getOrganizationJoinEmploymentSQL() )
+ .addEntity( "org", Organization.class )
+ .addJoin( "emp", "org.employments" )
+ .list();
+ assertEquals( 2,list.size() );
+
+ s.clear();
+
+ list = s.createSQLQuery( getOrganizationFetchJoinEmploymentSQL() )
+ .addEntity( "org", Organization.class )
+ .addJoin( "emp", "org.employments" )
+ .list();
+ assertEquals( 2,list.size() );
+
+ s.clear();
+
+ // TODO : why twice?
+ s.getNamedQuery( "organizationreturnproperty" ).list();
+ list = s.getNamedQuery( "organizationreturnproperty" ).list();
+ assertEquals( 2,list.size() );
+
+ s.clear();
+
+ list = s.getNamedQuery( "organizationautodetect" ).list();
+ assertEquals( 2,list.size() );
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.delete(emp2);
+
+ s.delete(jboss);
+ s.delete(gavin);
+ s.delete(ifa);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Dimension dim = new Dimension( 3, Integer.MAX_VALUE );
+ s.save( dim );
+ list = s.createSQLQuery( "select d_len * d_width as surface, d_len * d_width * 10 as volume from Dimension" ).list();
+ s.delete( dim );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ SpaceShip enterprise = new SpaceShip();
+ enterprise.setModel( "USS" );
+ enterprise.setName( "Entreprise" );
+ enterprise.setSpeed( 50d );
+ Dimension d = new Dimension(45, 10);
+ enterprise.setDimensions( d );
+ s.save( enterprise );
+ Object[] result = (Object[]) s.getNamedQuery( "spaceship" ).uniqueResult();
+ enterprise = ( SpaceShip ) result[0];
+ assertTrue(50d == enterprise.getSpeed() );
+ assertTrue( 450d == extractDoubleValue( result[1] ) );
+ assertTrue( 4500d == extractDoubleValue( result[2] ) );
+ s.delete( enterprise );
+ t.commit();
+ s.close();
+
+ }
+
+ public void testMixAndMatchEntityScalar() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Speech speech = new Speech();
+ speech.setLength( new Double( 23d ) );
+ speech.setName( "Mine" );
+ s.persist( speech );
+ s.flush();
+ s.clear();
+
+ List l = s.createSQLQuery( "select name, id, flength, name as scalarName from Speech" )
+ .setResultSetMapping( "speech" )
+ .list();
+ assertEquals( l.size(), 1 );
+
+ t.rollback();
+ s.close();
+ }
+
+ private double extractDoubleValue(Object value) {
+ if ( value instanceof BigInteger ) {
+ return ( ( BigInteger ) value ).doubleValue();
+ }
+ else if ( value instanceof BigDecimal ) {
+ return ( ( BigDecimal ) value ).doubleValue();
+ }
+ else {
+ return Double.valueOf( value.toString() ).doubleValue();
+ }
+ }
+
+ private static class UpperCasedAliasToEntityMapResultTransformer extends AliasToEntityMapResultTransformer {
+ public Object transformTuple(Object[] tuple, String[] aliases) {
+ String[] ucAliases = new String[aliases.length];
+ for ( int i = 0; i < aliases.length; i++ ) {
+ ucAliases[i] = aliases[i].toUpperCase();
+ }
+ return super.transformTuple( tuple, ucAliases );
+ }
+ }
+}
diff --git a/test/org/hibernate/test/stateless/Document.hbm.xml b/test/org/hibernate/test/stateless/Document.hbm.xml
new file mode 100755
index 0000000000..bdb145edad
--- /dev/null
+++ b/test/org/hibernate/test/stateless/Document.hbm.xml
@@ -0,0 +1,27 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/test/org/hibernate/test/stateless/Document.java b/test/org/hibernate/test/stateless/Document.java
new file mode 100755
index 0000000000..39bbfc7d98
--- /dev/null
+++ b/test/org/hibernate/test/stateless/Document.java
@@ -0,0 +1,46 @@
+//$Id$
+package org.hibernate.test.stateless;
+
+import java.util.Date;
+
+/**
+ * @author Gavin King
+ */
+public class Document {
+
+ private String text;
+ private String name;
+ private Date lastModified;
+
+ Document() {}
+
+ public Document(String text, String name) {
+ this.text = text;
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getText() {
+ return text;
+ }
+
+ public void setText(String text) {
+ this.text = text;
+ }
+
+ public Date getLastModified() {
+ return lastModified;
+ }
+
+ void setLastModified(Date lastModified) {
+ this.lastModified = lastModified;
+ }
+
+}
diff --git a/test/org/hibernate/test/stateless/Paper.java b/test/org/hibernate/test/stateless/Paper.java
new file mode 100644
index 0000000000..37eef48508
--- /dev/null
+++ b/test/org/hibernate/test/stateless/Paper.java
@@ -0,0 +1,26 @@
+//$Id$
+package org.hibernate.test.stateless;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Paper {
+ private Integer id;
+ private String color;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getColor() {
+ return color;
+ }
+
+ public void setColor(String color) {
+ this.color = color;
+ }
+}
diff --git a/test/org/hibernate/test/stateless/StatelessSessionTest.java b/test/org/hibernate/test/stateless/StatelessSessionTest.java
new file mode 100755
index 0000000000..1eb1e2e836
--- /dev/null
+++ b/test/org/hibernate/test/stateless/StatelessSessionTest.java
@@ -0,0 +1,168 @@
+//$Id$
+package org.hibernate.test.stateless;
+
+import java.util.Date;
+
+import junit.framework.Test;
+
+import org.hibernate.ScrollMode;
+import org.hibernate.ScrollableResults;
+import org.hibernate.StatelessSession;
+import org.hibernate.Transaction;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * @author Gavin King
+ */
+public class StatelessSessionTest extends FunctionalTestCase {
+
+ public StatelessSessionTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "stateless/Document.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( StatelessSessionTest.class );
+ }
+
+ public void testCreateUpdateReadDelete() {
+ StatelessSession ss = getSessions().openStatelessSession();
+ Transaction tx = ss.beginTransaction();
+ Document doc = new Document("blah blah blah", "Blahs");
+ ss.insert(doc);
+ assertNotNull( doc.getName() );
+ Date initVersion = doc.getLastModified();
+ assertNotNull( initVersion );
+ tx.commit();
+
+ tx = ss.beginTransaction();
+ doc.setText("blah blah blah .... blah");
+ ss.update(doc);
+ assertNotNull( doc.getLastModified() );
+ assertNotSame( doc.getLastModified(), initVersion );
+ tx.commit();
+
+ tx = ss.beginTransaction();
+ doc.setText("blah blah blah .... blah blay");
+ ss.update(doc);
+ tx.commit();
+
+ Document doc2 = (Document) ss.get(Document.class.getName(), "Blahs");
+ assertEquals("Blahs", doc2.getName());
+ assertEquals(doc.getText(), doc2.getText());
+
+ doc2 = (Document) ss.createQuery("from Document where text is not null").uniqueResult();
+ assertEquals("Blahs", doc2.getName());
+ assertEquals(doc.getText(), doc2.getText());
+
+ ScrollableResults sr = ss.createQuery("from Document where text is not null")
+ .scroll(ScrollMode.FORWARD_ONLY);
+ sr.next();
+ doc2 = (Document) sr.get(0);
+ sr.close();
+ assertEquals("Blahs", doc2.getName());
+ assertEquals(doc.getText(), doc2.getText());
+
+ doc2 = (Document) ss.createSQLQuery("select * from Document")
+ .addEntity(Document.class)
+ .uniqueResult();
+ assertEquals("Blahs", doc2.getName());
+ assertEquals(doc.getText(), doc2.getText());
+
+ doc2 = (Document) ss.createCriteria(Document.class).uniqueResult();
+ assertEquals("Blahs", doc2.getName());
+ assertEquals(doc.getText(), doc2.getText());
+
+ sr = ss.createCriteria(Document.class).scroll(ScrollMode.FORWARD_ONLY);
+ sr.next();
+ doc2 = (Document) sr.get(0);
+ sr.close();
+ assertEquals("Blahs", doc2.getName());
+ assertEquals(doc.getText(), doc2.getText());
+
+ tx = ss.beginTransaction();
+ ss.delete(doc);
+ tx.commit();
+ ss.close();
+
+ }
+
+ public void testHqlBulk() {
+ StatelessSession ss = getSessions().openStatelessSession();
+ Transaction tx = ss.beginTransaction();
+ Document doc = new Document("blah blah blah", "Blahs");
+ ss.insert(doc);
+ Paper paper = new Paper();
+ paper.setColor( "White" );
+ ss.insert(paper);
+ tx.commit();
+
+ tx = ss.beginTransaction();
+ int count = ss.createQuery( "update Document set name = :newName where name = :oldName" )
+ .setString( "newName", "Foos" )
+ .setString( "oldName", "Blahs" )
+ .executeUpdate();
+ assertEquals( "hql-update on stateless session", 1, count );
+ count = ss.createQuery( "update Paper set color = :newColor" )
+ .setString( "newColor", "Goldenrod" )
+ .executeUpdate();
+ assertEquals( "hql-update on stateless session", 1, count );
+ tx.commit();
+
+ tx = ss.beginTransaction();
+ count = ss.createQuery( "delete Document" ).executeUpdate();
+ assertEquals( "hql-delete on stateless session", 1, count );
+ count = ss.createQuery( "delete Paper" ).executeUpdate();
+ assertEquals( "hql-delete on stateless session", 1, count );
+ tx.commit();
+ ss.close();
+ }
+
+ public void testInitId() {
+ StatelessSession ss = getSessions().openStatelessSession();
+ Transaction tx = ss.beginTransaction();
+ Paper paper = new Paper();
+ paper.setColor( "White" );
+ ss.insert(paper);
+ assertNotNull( paper.getId() );
+ tx.commit();
+
+ tx = ss.beginTransaction();
+ ss.delete( ss.get( Paper.class, paper.getId() ) );
+ tx.commit();
+ ss.close();
+ }
+
+ public void testRefresh() {
+ StatelessSession ss = getSessions().openStatelessSession();
+ Transaction tx = ss.beginTransaction();
+ Paper paper = new Paper();
+ paper.setColor( "whtie" );
+ ss.insert( paper );
+ tx.commit();
+ ss.close();
+
+ ss = getSessions().openStatelessSession();
+ tx = ss.beginTransaction();
+ Paper p2 = ( Paper ) ss.get( Paper.class, paper.getId() );
+ p2.setColor( "White" );
+ ss.update( p2 );
+ tx.commit();
+ ss.close();
+
+ ss = getSessions().openStatelessSession();
+ tx = ss.beginTransaction();
+ assertEquals( "whtie", paper.getColor() );
+ ss.refresh( paper );
+ assertEquals( "White", paper.getColor() );
+ ss.delete( paper );
+ tx.commit();
+ ss.close();
+ }
+
+}
+
diff --git a/test/org/hibernate/test/stats/Continent.hbm.xml b/test/org/hibernate/test/stats/Continent.hbm.xml
new file mode 100644
index 0000000000..a1f9518808
--- /dev/null
+++ b/test/org/hibernate/test/stats/Continent.hbm.xml
@@ -0,0 +1,44 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/org/hibernate/test/stats/Continent.java b/test/org/hibernate/test/stats/Continent.java
new file mode 100644
index 0000000000..b7455c1e60
--- /dev/null
+++ b/test/org/hibernate/test/stats/Continent.java
@@ -0,0 +1,38 @@
+//$Id$
+package org.hibernate.test.stats;
+
+import java.util.Set;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Continent {
+ private Integer id;
+ private String name;
+ private Set countries;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Set getCountries() {
+ return countries;
+ }
+
+ public void setCountries(Set countries) {
+ this.countries = countries;
+ }
+
+}
diff --git a/test/org/hibernate/test/stats/Continent2.hbm.xml b/test/org/hibernate/test/stats/Continent2.hbm.xml
new file mode 100644
index 0000000000..6b446fced5
--- /dev/null
+++ b/test/org/hibernate/test/stats/Continent2.hbm.xml
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/org/hibernate/test/stats/Country.java b/test/org/hibernate/test/stats/Country.java
new file mode 100644
index 0000000000..134c6695de
--- /dev/null
+++ b/test/org/hibernate/test/stats/Country.java
@@ -0,0 +1,41 @@
+//$Id$
+package org.hibernate.test.stats;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Country {
+ private Integer id;
+ private String name;
+
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof Country)) return false;
+
+ final Country country = (Country) o;
+
+ if (!name.equals(country.name)) return false;
+
+ return true;
+ }
+
+ public int hashCode() {
+ return name.hashCode();
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/test/org/hibernate/test/stats/Locality.java b/test/org/hibernate/test/stats/Locality.java
new file mode 100644
index 0000000000..b2e4384244
--- /dev/null
+++ b/test/org/hibernate/test/stats/Locality.java
@@ -0,0 +1,42 @@
+package org.hibernate.test.stats;
+
+/**
+ * @author Steve Ebersole
+ */
+public class Locality {
+ private Long id;
+ private String name;
+ private Country country;
+
+ public Locality() {
+ }
+
+ public Locality(String name, Country country) {
+ this.name = name;
+ this.country = country;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Country getCountry() {
+ return country;
+ }
+
+ public void setCountry(Country country) {
+ this.country = country;
+ }
+}
diff --git a/test/org/hibernate/test/stats/Province.java b/test/org/hibernate/test/stats/Province.java
new file mode 100644
index 0000000000..a3ad6143dd
--- /dev/null
+++ b/test/org/hibernate/test/stats/Province.java
@@ -0,0 +1,7 @@
+package org.hibernate.test.stats;
+
+/**
+ * @author Steve Ebersole
+ */
+public class Province extends Locality {
+}
diff --git a/test/org/hibernate/test/stats/SessionStatsTest.java b/test/org/hibernate/test/stats/SessionStatsTest.java
new file mode 100644
index 0000000000..5af94ceaf5
--- /dev/null
+++ b/test/org/hibernate/test/stats/SessionStatsTest.java
@@ -0,0 +1,75 @@
+//$Id$
+package org.hibernate.test.stats;
+
+import java.util.HashSet;
+
+import junit.framework.Test;
+
+import org.hibernate.Hibernate;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.stat.SessionStatistics;
+import org.hibernate.stat.Statistics;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class SessionStatsTest extends FunctionalTestCase {
+
+ public SessionStatsTest(String x) {
+ super(x);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "stats/Continent2.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( SessionStatsTest.class );
+ }
+
+ public void testSessionStatistics() throws Exception {
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Statistics stats = getSessions().getStatistics();
+ stats.clear();
+ boolean isStats = stats.isStatisticsEnabled();
+ stats.setStatisticsEnabled(true);
+ Continent europe = fillDb(s);
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ SessionStatistics sessionStats = s.getStatistics();
+ assertEquals( 0, sessionStats.getEntityKeys().size() );
+ assertEquals( 0, sessionStats.getEntityCount() );
+ assertEquals( 0, sessionStats.getCollectionKeys().size() );
+ assertEquals( 0, sessionStats.getCollectionCount() );
+ europe = (Continent) s.get( Continent.class, europe.getId() );
+ Hibernate.initialize( europe.getCountries() );
+ Hibernate.initialize( europe.getCountries().iterator().next() );
+ assertEquals( 2, sessionStats.getEntityKeys().size() );
+ assertEquals( 2, sessionStats.getEntityCount() );
+ assertEquals( 1, sessionStats.getCollectionKeys().size() );
+ assertEquals( 1, sessionStats.getCollectionCount() );
+ tx.commit();
+ s.close();
+
+ stats.setStatisticsEnabled( isStats);
+
+ }
+
+ private Continent fillDb(Session s) {
+ Continent europe = new Continent();
+ europe.setName("Europe");
+ Country france = new Country();
+ france.setName("France");
+ europe.setCountries( new HashSet() );
+ europe.getCountries().add(france);
+ s.persist(france);
+ s.persist(europe);
+ return europe;
+ }
+
+}
diff --git a/test/org/hibernate/test/stats/State.java b/test/org/hibernate/test/stats/State.java
new file mode 100644
index 0000000000..fd13914b49
--- /dev/null
+++ b/test/org/hibernate/test/stats/State.java
@@ -0,0 +1,7 @@
+package org.hibernate.test.stats;
+
+/**
+ * @author Steve Ebersole
+ */
+public class State extends Locality {
+}
diff --git a/test/org/hibernate/test/stats/StatsTest.java b/test/org/hibernate/test/stats/StatsTest.java
new file mode 100644
index 0000000000..94d31e8432
--- /dev/null
+++ b/test/org/hibernate/test/stats/StatsTest.java
@@ -0,0 +1,232 @@
+//$Id$
+package org.hibernate.test.stats;
+
+import java.util.HashSet;
+import java.util.Iterator;
+
+import junit.framework.Test;
+
+import org.hibernate.FetchMode;
+import org.hibernate.Hibernate;
+import org.hibernate.ScrollableResults;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.mapping.Collection;
+import org.hibernate.stat.QueryStatistics;
+import org.hibernate.stat.Statistics;
+
+/**
+ * Show the difference between fetch and load
+ *
+ * @author Emmanuel Bernard
+ */
+public class StatsTest extends FunctionalTestCase {
+
+ public StatsTest(String x) {
+ super(x);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "stats/Continent.hbm.xml" };
+ }
+
+ public void configure(Configuration cfg) {
+ super.configure( cfg );
+ cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( StatsTest.class );
+ }
+
+ public void testCollectionFetchVsLoad() throws Exception {
+ Statistics stats = getSessions().getStatistics();
+ stats.clear();
+
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ Continent europe = fillDb(s);
+ tx.commit();
+ s.clear();
+
+ tx = s.beginTransaction();
+ assertEquals(0, stats.getCollectionLoadCount() );
+ assertEquals(0, stats.getCollectionFetchCount() );
+ Continent europe2 = (Continent) s.get( Continent.class, europe.getId() );
+ assertEquals("Lazy true: no collection should be loaded", 0, stats.getCollectionLoadCount() );
+ assertEquals( 0, stats.getCollectionFetchCount() );
+ europe2.getCountries().size();
+ assertEquals( 1, stats.getCollectionLoadCount() );
+ assertEquals("Explicit fetch of the collection state", 1, stats.getCollectionFetchCount() );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ stats.clear();
+ europe = fillDb(s);
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ assertEquals( 0, stats.getCollectionLoadCount() );
+ assertEquals( 0, stats.getCollectionFetchCount() );
+ europe2 = (Continent) s.createQuery(
+ "from " + Continent.class.getName() + " a join fetch a.countries where a.id = " + europe.getId()
+ ).uniqueResult();
+ assertEquals( 1, stats.getCollectionLoadCount() );
+ assertEquals( "collection should be loaded in the same query as its parent", 0, stats.getCollectionFetchCount() );
+ tx.commit();
+ s.close();
+
+ Collection coll = getCfg().getCollectionMapping(Continent.class.getName() + ".countries");
+ coll.setFetchMode(FetchMode.JOIN);
+ coll.setLazy(false);
+ SessionFactory sf = getCfg().buildSessionFactory();
+ stats = sf.getStatistics();
+ stats.clear();
+ stats.setStatisticsEnabled(true);
+ s = sf.openSession();
+ tx = s.beginTransaction();
+ europe = fillDb(s);
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ assertEquals( 0, stats.getCollectionLoadCount() );
+ assertEquals( 0, stats.getCollectionFetchCount() );
+ europe2 = (Continent) s.get( Continent.class, europe.getId() );
+ assertEquals( 1, stats.getCollectionLoadCount() );
+ assertEquals( "Should do direct load, not indirect second load when lazy false and JOIN", 0, stats.getCollectionFetchCount() );
+ tx.commit();
+ s.close();
+ sf.close();
+
+ coll = getCfg().getCollectionMapping(Continent.class.getName() + ".countries");
+ coll.setFetchMode(FetchMode.SELECT);
+ coll.setLazy(false);
+ sf = getCfg().buildSessionFactory();
+ stats = sf.getStatistics();
+ stats.clear();
+ stats.setStatisticsEnabled(true);
+ s = sf.openSession();
+ tx = s.beginTransaction();
+ europe = fillDb(s);
+ tx.commit();
+ s.clear();
+ tx = s.beginTransaction();
+ assertEquals( 0, stats.getCollectionLoadCount() );
+ assertEquals( 0, stats.getCollectionFetchCount() );
+ europe2 = (Continent) s.get( Continent.class, europe.getId() );
+ assertEquals( 1, stats.getCollectionLoadCount() );
+ assertEquals( "Should do explicit collection load, not part of the first one", 1, stats.getCollectionFetchCount() );
+ Iterator countries = europe2.getCountries().iterator();
+ while ( countries.hasNext() ) {
+ s.delete( countries.next() );
+ }
+ cleanDb( s );
+ tx.commit();
+ s.close();
+ }
+
+ public void testQueryStatGathering() {
+ Statistics stats = getSessions().getStatistics();
+ stats.clear();
+
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ fillDb(s);
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ final String continents = "from Continent";
+ int results = s.createQuery( continents ).list().size();
+ QueryStatistics continentStats = stats.getQueryStatistics( continents );
+ assertNotNull( "stats were null", continentStats );
+ assertEquals( "unexpected execution count", 1, continentStats.getExecutionCount() );
+ assertEquals( "unexpected row count", results, continentStats.getExecutionRowCount() );
+ long maxTime = continentStats.getExecutionMaxTime();
+ assertEquals( maxTime, stats.getQueryExecutionMaxTime() );
+// assertEquals( continents, stats.getQueryExecutionMaxTimeQueryString() );
+
+ Iterator itr = s.createQuery( continents ).iterate();
+ // iterate() should increment the execution count
+ assertEquals( "unexpected execution count", 2, continentStats.getExecutionCount() );
+ // but should not effect the cumulative row count
+ assertEquals( "unexpected row count", results, continentStats.getExecutionRowCount() );
+ Hibernate.close( itr );
+
+ ScrollableResults scrollableResults = s.createQuery( continents ).scroll();
+ // same deal with scroll()...
+ assertEquals( "unexpected execution count", 3, continentStats.getExecutionCount() );
+ assertEquals( "unexpected row count", results, continentStats.getExecutionRowCount() );
+ scrollableResults.close();
+ tx.commit();
+ s.close();
+
+ // explicitly check that statistics for "split queries" get collected
+ // under the original query
+ stats.clear();
+ s = openSession();
+ tx = s.beginTransaction();
+ final String localities = "from Locality";
+ results = s.createQuery( localities ).list().size();
+ QueryStatistics localityStats = stats.getQueryStatistics( localities );
+ assertNotNull( "stats were null", localityStats );
+ // ...one for each split query
+ assertEquals( "unexpected execution count", 2, localityStats.getExecutionCount() );
+ assertEquals( "unexpected row count", results, localityStats.getExecutionRowCount() );
+ maxTime = localityStats.getExecutionMaxTime();
+ assertEquals( maxTime, stats.getQueryExecutionMaxTime() );
+// assertEquals( localities, stats.getQueryExecutionMaxTimeQueryString() );
+ tx.commit();
+ s.close();
+ assertFalse( s.isOpen() );
+
+ // native sql queries
+ stats.clear();
+ s = openSession();
+ tx = s.beginTransaction();
+ final String sql = "select id, name from Country";
+ results = s.createSQLQuery( sql ).addEntity( Country.class ).list().size();
+ QueryStatistics sqlStats = stats.getQueryStatistics( sql );
+ assertNotNull( "sql stats were null", sqlStats );
+ assertEquals( "unexpected execution count", 1, sqlStats.getExecutionCount() );
+ assertEquals( "unexpected row count", results, sqlStats.getExecutionRowCount() );
+ maxTime = sqlStats.getExecutionMaxTime();
+ assertEquals( maxTime, stats.getQueryExecutionMaxTime() );
+// assertEquals( sql, stats.getQueryExecutionMaxTimeQueryString() );
+ tx.commit();
+ s.close();
+
+ s = openSession();
+ tx = s.beginTransaction();
+ cleanDb( s );
+ tx.commit();
+ s.close();
+ }
+
+ private Continent fillDb(Session s) {
+ Continent europe = new Continent();
+ europe.setName("Europe");
+ Country france = new Country();
+ france.setName("France");
+ europe.setCountries( new HashSet() );
+ europe.getCountries().add(france);
+ s.persist(france);
+ s.persist(europe);
+ return europe;
+ }
+
+ private void cleanDb(Session s) {
+ s.createQuery( "delete Locality" ).executeUpdate();
+ s.createQuery( "delete Country" ).executeUpdate();
+ s.createQuery( "delete Continent" ).executeUpdate();
+ }
+
+}
diff --git a/test/org/hibernate/test/subclassfilter/Customer.java b/test/org/hibernate/test/subclassfilter/Customer.java
new file mode 100644
index 0000000000..3af166c56d
--- /dev/null
+++ b/test/org/hibernate/test/subclassfilter/Customer.java
@@ -0,0 +1,26 @@
+// $Id$
+package org.hibernate.test.subclassfilter;
+
+/**
+ * Implementation of Customer.
+ *
+ * @author Steve Ebersole
+ */
+public class Customer extends Person {
+ private Employee contactOwner;
+
+ public Customer() {
+ }
+
+ public Customer(String name) {
+ super( name );
+ }
+
+ public Employee getContactOwner() {
+ return contactOwner;
+ }
+
+ public void setContactOwner(Employee contactOwner) {
+ this.contactOwner = contactOwner;
+ }
+}
diff --git a/test/org/hibernate/test/subclassfilter/DiscrimSubclassFilterTest.java b/test/org/hibernate/test/subclassfilter/DiscrimSubclassFilterTest.java
new file mode 100644
index 0000000000..9489bb047d
--- /dev/null
+++ b/test/org/hibernate/test/subclassfilter/DiscrimSubclassFilterTest.java
@@ -0,0 +1,132 @@
+// $Id$
+package org.hibernate.test.subclassfilter;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+
+import junit.framework.Test;
+
+import org.hibernate.Transaction;
+import org.hibernate.classic.Session;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * Implementation of DiscrimSubclassFilterTest.
+ *
+ * @author Steve Ebersole
+ */
+public class DiscrimSubclassFilterTest extends FunctionalTestCase {
+
+ public DiscrimSubclassFilterTest(String name) {
+ super( name );
+ }
+
+ public final String[] getMappings() {
+ return new String[] { "subclassfilter/discrim-subclass.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( DiscrimSubclassFilterTest.class );
+ }
+
+ public void testFiltersWithSubclass() {
+ Session s = openSession();
+ s.enableFilter( "region" ).setParameter( "userRegion", "US" );
+ Transaction t = s.beginTransaction();
+
+ prepareTestData( s );
+ s.clear();
+
+ List results;
+ Iterator itr;
+
+ results = s.createQuery( "from Person" ).list();
+ assertEquals( "Incorrect qry result count", 4, results.size() );
+ s.clear();
+
+ results = s.createQuery( "from Employee" ).list();
+ assertEquals( "Incorrect qry result count", 2, results.size() );
+ s.clear();
+
+ results = new ArrayList( new HashSet( s.createQuery( "from Person as p left join fetch p.minions" ).list() ) );
+ assertEquals( "Incorrect qry result count", 4, results.size() );
+ itr = results.iterator();
+ while ( itr.hasNext() ) {
+ // find john
+ final Person p = ( Person ) itr.next();
+ if ( p.getName().equals( "John Doe" ) ) {
+ Employee john = ( Employee ) p;
+ assertEquals( "Incorrect fecthed minions count", 1, john.getMinions().size() );
+ break;
+ }
+ }
+ s.clear();
+
+ results = new ArrayList( new HashSet( s.createQuery( "from Employee as p left join fetch p.minions" ).list() ) );
+ assertEquals( "Incorrect qry result count", 2, results.size() );
+ itr = results.iterator();
+ while ( itr.hasNext() ) {
+ // find john
+ final Person p = ( Person ) itr.next();
+ if ( p.getName().equals( "John Doe" ) ) {
+ Employee john = ( Employee ) p;
+ assertEquals( "Incorrect fecthed minions count", 1, john.getMinions().size() );
+ break;
+ }
+ }
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery( "delete Customer where contactOwner is not null" ).executeUpdate();
+ s.createQuery( "delete Employee where manager is not null" ).executeUpdate();
+ s.createQuery( "delete Person" ).executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ private void prepareTestData(Session s) {
+ Employee john = new Employee("John Doe");
+ john.setCompany( "JBoss" );
+ john.setDepartment( "hr" );
+ john.setTitle( "hr guru" );
+ john.setRegion( "US" );
+
+ Employee polli = new Employee("Polli Wog");
+ polli.setCompany( "JBoss" );
+ polli.setDepartment( "hr" );
+ polli.setTitle( "hr novice" );
+ polli.setRegion( "US" );
+ polli.setManager( john );
+ john.getMinions().add( polli );
+
+ Employee suzie = new Employee( "Suzie Q" );
+ suzie.setCompany( "JBoss" );
+ suzie.setDepartment( "hr" );
+ suzie.setTitle( "hr novice" );
+ suzie.setRegion( "EMEA" );
+ suzie.setManager( john );
+ john.getMinions().add( suzie );
+
+ Customer cust = new Customer( "John Q Public" );
+ cust.setCompany( "Acme" );
+ cust.setRegion( "US" );
+ cust.setContactOwner( john );
+
+ Person ups = new Person( "UPS guy" );
+ ups.setCompany( "UPS" );
+ ups.setRegion( "US" );
+
+ s.save( john );
+ s.save( cust );
+ s.save( ups );
+
+ s.flush();
+ }
+
+}
diff --git a/test/org/hibernate/test/subclassfilter/Employee.java b/test/org/hibernate/test/subclassfilter/Employee.java
new file mode 100644
index 0000000000..e49fa9e00d
--- /dev/null
+++ b/test/org/hibernate/test/subclassfilter/Employee.java
@@ -0,0 +1,56 @@
+// $Id$
+package org.hibernate.test.subclassfilter;
+
+import java.util.Set;
+import java.util.HashSet;
+
+/**
+ * Implementation of Employee.
+ *
+ * @author Steve Ebersole
+ */
+public class Employee extends Person {
+ private String title;
+ private String department;
+ private Employee manager;
+ private Set minions = new HashSet();
+
+ public Employee() {
+ }
+
+ public Employee(String name) {
+ super( name );
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getDepartment() {
+ return department;
+ }
+
+ public void setDepartment(String department) {
+ this.department = department;
+ }
+
+ public Employee getManager() {
+ return manager;
+ }
+
+ public void setManager(Employee manager) {
+ this.manager = manager;
+ }
+
+ public Set getMinions() {
+ return minions;
+ }
+
+ public void setMinions(Set minions) {
+ this.minions = minions;
+ }
+}
diff --git a/test/org/hibernate/test/subclassfilter/JoinedSubclassFilterTest.java b/test/org/hibernate/test/subclassfilter/JoinedSubclassFilterTest.java
new file mode 100644
index 0000000000..8b343e834f
--- /dev/null
+++ b/test/org/hibernate/test/subclassfilter/JoinedSubclassFilterTest.java
@@ -0,0 +1,143 @@
+// $Id$
+package org.hibernate.test.subclassfilter;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+
+import junit.framework.Test;
+
+import org.hibernate.Transaction;
+import org.hibernate.classic.Session;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * Implementation of JoinedSubclassFilterTest.
+ *
+ * @author Steve Ebersole
+ */
+public class JoinedSubclassFilterTest extends FunctionalTestCase {
+
+ public JoinedSubclassFilterTest(String name) {
+ super( name );
+ }
+
+ public final String[] getMappings() {
+ return new String[] { "subclassfilter/joined-subclass.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( JoinedSubclassFilterTest.class );
+ }
+
+ public void testFiltersWithJoinedSubclass() {
+ Session s = openSession();
+ s.enableFilter( "region" ).setParameter( "userRegion", "US" );
+ Transaction t = s.beginTransaction();
+
+ prepareTestData( s );
+ s.clear();
+
+ List results = s.createQuery( "from Person" ).list();
+ assertEquals( "Incorrect qry result count", 4, results.size() );
+ s.clear();
+
+ results = s.createQuery( "from Employee" ).list();
+ assertEquals( "Incorrect qry result count", 2, results.size() );
+ Iterator itr = results.iterator();
+ while ( itr.hasNext() ) {
+ // find john
+ final Person p = ( Person ) itr.next();
+ if ( p.getName().equals( "John Doe" ) ) {
+ Employee john = ( Employee ) p;
+ assertEquals( "Incorrect fecthed minions count", 2, john.getMinions().size() );
+ break;
+ }
+ }
+ s.clear();
+
+ // TODO : currently impossible to define a collection-level filter w/ joined-subclass elements that will filter based on a superclass column and function correctly in (theta only?) outer joins;
+ // this is consistent with the behaviour of a collection-level where.
+ // this might be one argument for "pulling" the attached class-level filters into collection assocations,
+ // although we'd need some way to apply the appropriate alias in that scenario.
+ results = new ArrayList( new HashSet( s.createQuery( "from Person as p left join fetch p.minions" ).list() ) );
+ assertEquals( "Incorrect qry result count", 4, results.size() );
+ itr = results.iterator();
+ while ( itr.hasNext() ) {
+ // find john
+ final Person p = ( Person ) itr.next();
+ if ( p.getName().equals( "John Doe" ) ) {
+ Employee john = ( Employee ) p;
+ assertEquals( "Incorrect fecthed minions count", 2, john.getMinions().size() );
+ break;
+ }
+ }
+ s.clear();
+
+ results = new ArrayList( new HashSet( s.createQuery( "from Employee as p left join fetch p.minions" ).list() ) );
+ assertEquals( "Incorrect qry result count", 2, results.size() );
+ itr = results.iterator();
+ while ( itr.hasNext() ) {
+ // find john
+ final Person p = ( Person ) itr.next();
+ if ( p.getName().equals( "John Doe" ) ) {
+ Employee john = ( Employee ) p;
+ assertEquals( "Incorrect fecthed minions count", 2, john.getMinions().size() );
+ break;
+ }
+ }
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery( "delete Customer where contactOwner is not null" ).executeUpdate();
+ s.createQuery( "delete Employee where manager is not null" ).executeUpdate();
+ s.createQuery( "delete Person" ).executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ private void prepareTestData(Session s) {
+ Employee john = new Employee("John Doe");
+ john.setCompany( "JBoss" );
+ john.setDepartment( "hr" );
+ john.setTitle( "hr guru" );
+ john.setRegion( "US" );
+
+ Employee polli = new Employee("Polli Wog");
+ polli.setCompany( "JBoss" );
+ polli.setDepartment( "hr" );
+ polli.setTitle( "hr novice" );
+ polli.setRegion( "US" );
+ polli.setManager( john );
+ john.getMinions().add( polli );
+
+ Employee suzie = new Employee( "Suzie Q" );
+ suzie.setCompany( "JBoss" );
+ suzie.setDepartment( "hr" );
+ suzie.setTitle( "hr novice" );
+ suzie.setRegion( "EMEA" );
+ suzie.setManager( john );
+ john.getMinions().add( suzie );
+
+ Customer cust = new Customer( "John Q Public" );
+ cust.setCompany( "Acme" );
+ cust.setRegion( "US" );
+ cust.setContactOwner( john );
+
+ Person ups = new Person( "UPS guy" );
+ ups.setCompany( "UPS" );
+ ups.setRegion( "US" );
+
+ s.save( john );
+ s.save( cust );
+ s.save( ups );
+
+ s.flush();
+ }
+
+}
diff --git a/test/org/hibernate/test/subclassfilter/Person.java b/test/org/hibernate/test/subclassfilter/Person.java
new file mode 100644
index 0000000000..1b308a54ff
--- /dev/null
+++ b/test/org/hibernate/test/subclassfilter/Person.java
@@ -0,0 +1,53 @@
+// $Id$
+package org.hibernate.test.subclassfilter;
+
+/**
+ * Implementation of Person.
+ *
+ * @author Steve Ebersole
+ */
+public class Person {
+ private Long id;
+ private String name;
+ private String company;
+ private String region;
+
+ public Person() {
+ }
+
+ public Person(String name) {
+ this.name = name;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getCompany() {
+ return company;
+ }
+
+ public void setCompany(String company) {
+ this.company = company;
+ }
+
+ public String getRegion() {
+ return region;
+ }
+
+ public void setRegion(String region) {
+ this.region = region;
+ }
+}
diff --git a/test/org/hibernate/test/subclassfilter/UnionSubclassFilterTest.java b/test/org/hibernate/test/subclassfilter/UnionSubclassFilterTest.java
new file mode 100644
index 0000000000..b92f2742b4
--- /dev/null
+++ b/test/org/hibernate/test/subclassfilter/UnionSubclassFilterTest.java
@@ -0,0 +1,130 @@
+// $Id$
+package org.hibernate.test.subclassfilter;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+
+import junit.framework.Test;
+
+import org.hibernate.Transaction;
+import org.hibernate.classic.Session;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * Implementation of DiscrimSubclassFilterTest.
+ *
+ * @author Steve Ebersole
+ */
+public class UnionSubclassFilterTest extends FunctionalTestCase {
+
+ public UnionSubclassFilterTest(String name) {
+ super( name );
+ }
+
+ public final String[] getMappings() {
+ return new String[] { "subclassfilter/union-subclass.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( UnionSubclassFilterTest.class );
+ }
+
+ public void testFiltersWithUnionSubclass() {
+ Session s = openSession();
+ s.enableFilter( "region" ).setParameter( "userRegion", "US" );
+ Transaction t = s.beginTransaction();
+
+ prepareTestData( s );
+ s.clear();
+
+ List results;
+ Iterator itr;
+
+ results = s.createQuery( "from Person" ).list();
+ assertEquals( "Incorrect qry result count", 4, results.size() );
+ s.clear();
+
+ results = s.createQuery( "from Employee" ).list();
+ assertEquals( "Incorrect qry result count", 2, results.size() );
+ s.clear();
+
+ results = new ArrayList( new HashSet( s.createQuery( "from Person as p left join fetch p.minions" ).list() ) );
+ assertEquals( "Incorrect qry result count", 4, results.size() );
+ itr = results.iterator();
+ while ( itr.hasNext() ) {
+ // find john
+ final Person p = ( Person ) itr.next();
+ if ( p.getName().equals( "John Doe" ) ) {
+ Employee john = ( Employee ) p;
+ assertEquals( "Incorrect fecthed minions count", 1, john.getMinions().size() );
+ break;
+ }
+ }
+ s.clear();
+
+ results = new ArrayList( new HashSet( s.createQuery( "from Employee as p left join fetch p.minions" ).list() ) );
+ assertEquals( "Incorrect qry result count", 2, results.size() );
+ itr = results.iterator();
+ while ( itr.hasNext() ) {
+ // find john
+ final Person p = ( Person ) itr.next();
+ if ( p.getName().equals( "John Doe" ) ) {
+ Employee john = ( Employee ) p;
+ assertEquals( "Incorrect fecthed minions count", 1, john.getMinions().size() );
+ break;
+ }
+ }
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.delete( "from Person" );
+ t.commit();
+ s.close();
+
+ }
+
+ private void prepareTestData(Session s) {
+ Employee john = new Employee( "John Doe" );
+ john.setCompany( "JBoss" );
+ john.setDepartment( "hr" );
+ john.setTitle( "hr guru" );
+ john.setRegion( "US" );
+
+ Employee polli = new Employee( "Polli Wog" );
+ polli.setCompany( "JBoss" );
+ polli.setDepartment( "hr" );
+ polli.setTitle( "hr novice" );
+ polli.setRegion( "US" );
+ polli.setManager( john );
+ john.getMinions().add( polli );
+
+ Employee suzie = new Employee( "Suzie Q" );
+ suzie.setCompany( "JBoss" );
+ suzie.setDepartment( "hr" );
+ suzie.setTitle( "hr novice" );
+ suzie.setRegion( "EMEA" );
+ suzie.setManager( john );
+ john.getMinions().add( suzie );
+
+ Customer cust = new Customer( "John Q Public" );
+ cust.setCompany( "Acme" );
+ cust.setRegion( "US" );
+ cust.setContactOwner( john );
+
+ Person ups = new Person( "UPS guy" );
+ ups.setCompany( "UPS" );
+ ups.setRegion( "US" );
+
+ s.save( john );
+ s.save( cust );
+ s.save( ups );
+
+ s.flush();
+ }
+}
diff --git a/test/org/hibernate/test/subclassfilter/discrim-subclass.hbm.xml b/test/org/hibernate/test/subclassfilter/discrim-subclass.hbm.xml
new file mode 100644
index 0000000000..ccbe3f397f
--- /dev/null
+++ b/test/org/hibernate/test/subclassfilter/discrim-subclass.hbm.xml
@@ -0,0 +1,44 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/test/org/hibernate/test/subclassfilter/joined-subclass.hbm.xml b/test/org/hibernate/test/subclassfilter/joined-subclass.hbm.xml
new file mode 100644
index 0000000000..d01cf7cdca
--- /dev/null
+++ b/test/org/hibernate/test/subclassfilter/joined-subclass.hbm.xml
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/test/org/hibernate/test/subclassfilter/union-subclass.hbm.xml b/test/org/hibernate/test/subclassfilter/union-subclass.hbm.xml
new file mode 100644
index 0000000000..ed9c9523e3
--- /dev/null
+++ b/test/org/hibernate/test/subclassfilter/union-subclass.hbm.xml
@@ -0,0 +1,41 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/test/org/hibernate/test/subselect/Alien.java b/test/org/hibernate/test/subselect/Alien.java
new file mode 100755
index 0000000000..f3278cb3cd
--- /dev/null
+++ b/test/org/hibernate/test/subselect/Alien.java
@@ -0,0 +1,37 @@
+//$Id$
+package org.hibernate.test.subselect;
+
+/**
+ * @author Gavin King
+ */
+public class Alien {
+ private Long id;
+ private String identity;
+ private String planet;
+ private String species;
+
+ public void setIdentity(String identity) {
+ this.identity = identity;
+ }
+ public String getIdentity() {
+ return identity;
+ }
+ public void setSpecies(String species) {
+ this.species = species;
+ }
+ public String getSpecies() {
+ return species;
+ }
+ public void setPlanet(String planet) {
+ this.planet = planet;
+ }
+ public String getPlanet() {
+ return planet;
+ }
+ public void setId(Long id) {
+ this.id = id;
+ }
+ public Long getId() {
+ return id;
+ }
+}
diff --git a/test/org/hibernate/test/subselect/Being.java b/test/org/hibernate/test/subselect/Being.java
new file mode 100755
index 0000000000..b0d47af002
--- /dev/null
+++ b/test/org/hibernate/test/subselect/Being.java
@@ -0,0 +1,31 @@
+//$Id$
+package org.hibernate.test.subselect;
+
+/**
+ * @author Gavin King
+ */
+public class Being {
+ private long id;
+ private String identity;
+ private String location;
+ private String species;
+
+ public void setLocation(String location) {
+ this.location = location;
+ }
+ public String getLocation() {
+ return location;
+ }
+ public void setSpecies(String species) {
+ this.species = species;
+ }
+ public String getSpecies() {
+ return species;
+ }
+ public void setIdentity(String identity) {
+ this.identity = identity;
+ }
+ public String getIdentity() {
+ return identity;
+ }
+}
diff --git a/test/org/hibernate/test/subselect/Beings.hbm.xml b/test/org/hibernate/test/subselect/Beings.hbm.xml
new file mode 100755
index 0000000000..e1942cfc52
--- /dev/null
+++ b/test/org/hibernate/test/subselect/Beings.hbm.xml
@@ -0,0 +1,83 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ select bid, name as ident, address as loc, 'human' as species
+ from humans
+ union
+ select bid, ident, planet as loc, species
+ from aliens
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/org/hibernate/test/subselect/Human.java b/test/org/hibernate/test/subselect/Human.java
new file mode 100755
index 0000000000..eb87ece395
--- /dev/null
+++ b/test/org/hibernate/test/subselect/Human.java
@@ -0,0 +1,37 @@
+//$Id$
+package org.hibernate.test.subselect;
+
+/**
+ * @author Gavin King
+ */
+public class Human {
+ private Long id;
+ private String name;
+ private char sex;
+ private String address;
+
+ public void setAddress(String address) {
+ this.address = address;
+ }
+ public String getAddress() {
+ return address;
+ }
+ public void setSex(char sex) {
+ this.sex = sex;
+ }
+ public char getSex() {
+ return sex;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setId(Long id) {
+ this.id = id;
+ }
+ public Long getId() {
+ return id;
+ }
+}
diff --git a/test/org/hibernate/test/subselect/SubselectTest.java b/test/org/hibernate/test/subselect/SubselectTest.java
new file mode 100755
index 0000000000..b22184c81a
--- /dev/null
+++ b/test/org/hibernate/test/subselect/SubselectTest.java
@@ -0,0 +1,72 @@
+//$Id$
+package org.hibernate.test.subselect;
+
+import java.util.Iterator;
+import java.util.List;
+
+import junit.framework.Test;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * @author Gavin King
+ */
+public class SubselectTest extends FunctionalTestCase {
+
+ public SubselectTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "subselect/Beings.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( SubselectTest.class );
+ }
+
+ public void testEntitySubselect() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Human gavin = new Human();
+ gavin.setName( "gavin" );
+ gavin.setSex( 'M' );
+ gavin.setAddress( "Melbourne, Australia" );
+ Alien x23y4 = new Alien();
+ x23y4.setIdentity( "x23y4$$hu%3" );
+ x23y4.setPlanet( "Mars" );
+ x23y4.setSpecies( "martian" );
+ s.save(gavin);
+ s.save(x23y4);
+ s.flush();
+ List beings = s.createQuery("from Being").list();
+ for ( Iterator iter = beings.iterator(); iter.hasNext(); ) {
+ Being b = (Being) iter.next();
+ assertNotNull( b.getLocation() );
+ assertNotNull( b.getIdentity() );
+ assertNotNull( b.getSpecies() );
+ }
+ s.clear();
+ getSessions().evict(Being.class);
+ Being gav = (Being) s.get(Being.class, gavin.getId());
+ assertEquals( gav.getLocation(), gavin.getAddress() );
+ assertEquals( gav.getSpecies(), "human" );
+ assertEquals( gav.getIdentity(), gavin.getName() );
+ s.clear();
+ //test the tag:
+ gavin = (Human) s.get(Human.class, gavin.getId());
+ gavin.setAddress( "Atlanta, GA" );
+ gav = (Being) s.createQuery("from Being b where b.location like '%GA%'").uniqueResult();
+ assertEquals( gav.getLocation(), gavin.getAddress() );
+ s.delete(gavin);
+ s.delete(x23y4);
+ assertTrue( s.createQuery("from Being").list().isEmpty() );
+ t.commit();
+ s.close();
+ }
+
+}
+
diff --git a/test/org/hibernate/test/subselectfetch/Child.java b/test/org/hibernate/test/subselectfetch/Child.java
new file mode 100755
index 0000000000..264c334ebd
--- /dev/null
+++ b/test/org/hibernate/test/subselectfetch/Child.java
@@ -0,0 +1,34 @@
+//$Id$
+package org.hibernate.test.subselectfetch;
+
+import java.util.List;
+
+/**
+ * @author Gavin King
+ */
+public class Child {
+ private String name;
+ private List friends;
+
+ Child() {}
+ public Child(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+ public List getFriends() {
+ return friends;
+ }
+
+ public void setFriends(List friends) {
+ this.friends = friends;
+ }
+
+
+}
diff --git a/test/org/hibernate/test/subselectfetch/Parent.java b/test/org/hibernate/test/subselectfetch/Parent.java
new file mode 100755
index 0000000000..b64054054e
--- /dev/null
+++ b/test/org/hibernate/test/subselectfetch/Parent.java
@@ -0,0 +1,45 @@
+//$Id$
+package org.hibernate.test.subselectfetch;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Gavin King
+ */
+public class Parent {
+ private String name;
+ private List children = new ArrayList();
+ private List moreChildren = new ArrayList();
+
+ Parent() {}
+ public Parent(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public List getChildren() {
+ return children;
+ }
+
+ public void setChildren(List children) {
+ this.children = children;
+ }
+
+ public List getMoreChildren() {
+ return moreChildren;
+ }
+
+ public void setMoreChildren(List moreChildren) {
+ this.moreChildren = moreChildren;
+ }
+
+
+}
diff --git a/test/org/hibernate/test/subselectfetch/ParentChild.hbm.xml b/test/org/hibernate/test/subselectfetch/ParentChild.hbm.xml
new file mode 100755
index 0000000000..0eb64efe58
--- /dev/null
+++ b/test/org/hibernate/test/subselectfetch/ParentChild.hbm.xml
@@ -0,0 +1,31 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/test/org/hibernate/test/subselectfetch/SubselectFetchTest.java b/test/org/hibernate/test/subselectfetch/SubselectFetchTest.java
new file mode 100755
index 0000000000..dc10949aac
--- /dev/null
+++ b/test/org/hibernate/test/subselectfetch/SubselectFetchTest.java
@@ -0,0 +1,384 @@
+//$Id$
+package org.hibernate.test.subselectfetch;
+
+import java.util.List;
+
+import junit.framework.Test;
+
+import org.hibernate.FetchMode;
+import org.hibernate.Hibernate;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.criterion.Order;
+import org.hibernate.criterion.Property;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * @author Gavin King
+ */
+public class SubselectFetchTest extends FunctionalTestCase {
+
+ public SubselectFetchTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "subselectfetch/ParentChild.hbm.xml" };
+ }
+
+ public void configure(Configuration cfg) {
+ cfg.setProperty(Environment.GENERATE_STATISTICS, "true");
+ }
+
+ public String getCacheConcurrencyStrategy() {
+ return null;
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( SubselectFetchTest.class );
+ }
+
+ public void testSubselectFetchHql() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Parent p = new Parent("foo");
+ p.getChildren().add( new Child("foo1") );
+ p.getChildren().add( new Child("foo2") );
+ Parent q = new Parent("bar");
+ q.getChildren().add( new Child("bar1") );
+ q.getChildren().add( new Child("bar2") );
+ q.getMoreChildren().addAll( p.getChildren() );
+ s.persist(p);
+ s.persist(q);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ getSessions().getStatistics().clear();
+
+ List parents = s.createQuery("from Parent where name between 'bar' and 'foo' order by name desc")
+ .list();
+ p = (Parent) parents.get(0);
+ q = (Parent) parents.get(1);
+
+ assertFalse( Hibernate.isInitialized( p.getChildren() ) );
+ assertFalse( Hibernate.isInitialized( q.getChildren() ) );
+
+ assertEquals( p.getChildren().size(), 2 );
+
+ assertTrue( Hibernate.isInitialized( p.getChildren().iterator().next() ) );
+
+ assertTrue( Hibernate.isInitialized( q.getChildren() ) );
+
+ assertEquals( q.getChildren().size(), 2 );
+
+ assertTrue( Hibernate.isInitialized( q.getChildren().iterator().next() ) );
+
+ assertFalse( Hibernate.isInitialized( p.getMoreChildren() ) );
+ assertFalse( Hibernate.isInitialized( q.getMoreChildren() ) );
+
+ assertEquals( p.getMoreChildren().size(), 0 );
+
+ assertTrue( Hibernate.isInitialized( q.getMoreChildren() ) );
+
+ assertEquals( q.getMoreChildren().size(), 2 );
+
+ assertTrue( Hibernate.isInitialized( q.getMoreChildren().iterator().next() ) );
+
+ assertEquals( 3, getSessions().getStatistics().getPrepareStatementCount() );
+
+ Child c = (Child) p.getChildren().get(0);
+ c.getFriends().size();
+
+ s.delete(p);
+ s.delete(q);
+
+ t.commit();
+ s.close();
+ }
+
+ public void testSubselectFetchNamedParam() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Parent p = new Parent("foo");
+ p.getChildren().add( new Child("foo1") );
+ p.getChildren().add( new Child("foo2") );
+ Parent q = new Parent("bar");
+ q.getChildren().add( new Child("bar1") );
+ q.getChildren().add( new Child("bar2") );
+ q.getMoreChildren().addAll( p.getChildren() );
+ s.persist(p);
+ s.persist(q);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ getSessions().getStatistics().clear();
+
+ List parents = s.createQuery("from Parent where name between :bar and :foo order by name desc")
+ .setParameter("bar", "bar")
+ .setParameter("foo", "foo")
+ .list();
+ p = (Parent) parents.get(0);
+ q = (Parent) parents.get(1);
+
+ assertFalse( Hibernate.isInitialized( p.getChildren() ) );
+ assertFalse( Hibernate.isInitialized( q.getChildren() ) );
+
+ assertEquals( p.getChildren().size(), 2 );
+
+ assertTrue( Hibernate.isInitialized( p.getChildren().iterator().next() ) );
+
+ assertTrue( Hibernate.isInitialized( q.getChildren() ) );
+
+ assertEquals( q.getChildren().size(), 2 );
+
+ assertTrue( Hibernate.isInitialized( q.getChildren().iterator().next() ) );
+
+ assertFalse( Hibernate.isInitialized( p.getMoreChildren() ) );
+ assertFalse( Hibernate.isInitialized( q.getMoreChildren() ) );
+
+ assertEquals( p.getMoreChildren().size(), 0 );
+
+ assertTrue( Hibernate.isInitialized( q.getMoreChildren() ) );
+
+ assertEquals( q.getMoreChildren().size(), 2 );
+
+ assertTrue( Hibernate.isInitialized( q.getMoreChildren().iterator().next() ) );
+
+ assertEquals( 3, getSessions().getStatistics().getPrepareStatementCount() );
+
+ Child c = (Child) p.getChildren().get(0);
+ c.getFriends().size();
+
+ s.delete(p);
+ s.delete(q);
+
+ t.commit();
+ s.close();
+ }
+
+ public void testSubselectFetchPosParam() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Parent p = new Parent("foo");
+ p.getChildren().add( new Child("foo1") );
+ p.getChildren().add( new Child("foo2") );
+ Parent q = new Parent("bar");
+ q.getChildren().add( new Child("bar1") );
+ q.getChildren().add( new Child("bar2") );
+ q.getMoreChildren().addAll( p.getChildren() );
+ s.persist(p);
+ s.persist(q);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ getSessions().getStatistics().clear();
+
+ List parents = s.createQuery("from Parent where name between ? and ? order by name desc")
+ .setParameter(0, "bar")
+ .setParameter(1, "foo")
+ .list();
+ p = (Parent) parents.get(0);
+ q = (Parent) parents.get(1);
+
+ assertFalse( Hibernate.isInitialized( p.getChildren() ) );
+ assertFalse( Hibernate.isInitialized( q.getChildren() ) );
+
+ assertEquals( p.getChildren().size(), 2 );
+
+ assertTrue( Hibernate.isInitialized( p.getChildren().iterator().next() ) );
+
+ assertTrue( Hibernate.isInitialized( q.getChildren() ) );
+
+ assertEquals( q.getChildren().size(), 2 );
+
+ assertTrue( Hibernate.isInitialized( q.getChildren().iterator().next() ) );
+
+ assertFalse( Hibernate.isInitialized( p.getMoreChildren() ) );
+ assertFalse( Hibernate.isInitialized( q.getMoreChildren() ) );
+
+ assertEquals( p.getMoreChildren().size(), 0 );
+
+ assertTrue( Hibernate.isInitialized( q.getMoreChildren() ) );
+
+ assertEquals( q.getMoreChildren().size(), 2 );
+
+ assertTrue( Hibernate.isInitialized( q.getMoreChildren().iterator().next() ) );
+
+ assertEquals( 3, getSessions().getStatistics().getPrepareStatementCount() );
+
+ Child c = (Child) p.getChildren().get(0);
+ c.getFriends().size();
+
+ s.delete(p);
+ s.delete(q);
+
+ t.commit();
+ s.close();
+ }
+
+ public void testSubselectFetchWithLimit() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Parent p = new Parent("foo");
+ p.getChildren().add( new Child("foo1") );
+ p.getChildren().add( new Child("foo2") );
+ Parent q = new Parent("bar");
+ q.getChildren().add( new Child("bar1") );
+ q.getChildren().add( new Child("bar2") );
+ Parent r = new Parent("aaa");
+ r.getChildren().add( new Child("aaa1") );
+ s.persist(p);
+ s.persist(q);
+ s.persist(r);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ getSessions().getStatistics().clear();
+
+ List parents = s.createQuery("from Parent order by name desc")
+ .setMaxResults(2)
+ .list();
+ p = (Parent) parents.get(0);
+ q = (Parent) parents.get(1);
+ assertFalse( Hibernate.isInitialized( p.getChildren() ) );
+ assertFalse( Hibernate.isInitialized( p.getMoreChildren() ) );
+ assertFalse( Hibernate.isInitialized( q.getChildren() ) );
+ assertFalse( Hibernate.isInitialized( q.getMoreChildren() ) );
+ assertEquals( p.getMoreChildren().size(), 0 );
+ assertEquals( p.getChildren().size(), 2 );
+ assertTrue( Hibernate.isInitialized( q.getChildren() ) );
+ assertTrue( Hibernate.isInitialized( q.getMoreChildren() ) );
+
+ assertEquals( 3, getSessions().getStatistics().getPrepareStatementCount() );
+
+ r = (Parent) s.get( Parent.class, r.getName() );
+ assertTrue( Hibernate.isInitialized( r.getChildren() ) );
+ assertFalse( Hibernate.isInitialized( r.getMoreChildren() ) );
+ assertEquals( r.getChildren().size(), 1 );
+ assertEquals( r.getMoreChildren().size(), 0 );
+
+ s.delete(p);
+ s.delete(q);
+ s.delete(r);
+
+ t.commit();
+ s.close();
+ }
+
+ public void testManyToManyCriteriaJoin() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Parent p = new Parent("foo");
+ p.getChildren().add( new Child("foo1") );
+ p.getChildren().add( new Child("foo2") );
+ Parent q = new Parent("bar");
+ q.getChildren().add( new Child("bar1") );
+ q.getChildren().add( new Child("bar2") );
+ q.getMoreChildren().addAll( p.getChildren() );
+ s.persist(p);
+ s.persist(q);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ List parents = s.createCriteria(Parent.class)
+ .createCriteria("moreChildren")
+ .createCriteria("friends")
+ .addOrder( Order.desc("name") )
+ .list();
+
+ parents = s.createCriteria(Parent.class)
+ .setFetchMode("moreChildren", FetchMode.JOIN)
+ .setFetchMode("moreChildren.friends", FetchMode.JOIN)
+ .addOrder( Order.desc("name") )
+ .list();
+
+ s.delete( parents.get(0) );
+ s.delete( parents.get(1) );
+
+ t.commit();
+ s.close();
+ }
+
+ public void testSubselectFetchCriteria() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Parent p = new Parent("foo");
+ p.getChildren().add( new Child("foo1") );
+ p.getChildren().add( new Child("foo2") );
+ Parent q = new Parent("bar");
+ q.getChildren().add( new Child("bar1") );
+ q.getChildren().add( new Child("bar2") );
+ q.getMoreChildren().addAll( p.getChildren() );
+ s.persist(p);
+ s.persist(q);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ getSessions().getStatistics().clear();
+
+ List parents = s.createCriteria(Parent.class)
+ .add( Property.forName("name").between("bar", "foo") )
+ .addOrder( Order.desc("name") )
+ .list();
+ p = (Parent) parents.get(0);
+ q = (Parent) parents.get(1);
+
+ assertFalse( Hibernate.isInitialized( p.getChildren() ) );
+ assertFalse( Hibernate.isInitialized( q.getChildren() ) );
+
+ assertEquals( p.getChildren().size(), 2 );
+
+ assertTrue( Hibernate.isInitialized( p.getChildren().iterator().next() ) );
+
+ assertTrue( Hibernate.isInitialized( q.getChildren() ) );
+
+ assertEquals( q.getChildren().size(), 2 );
+
+ assertTrue( Hibernate.isInitialized( q.getChildren().iterator().next() ) );
+
+ assertFalse( Hibernate.isInitialized( p.getMoreChildren() ) );
+ assertFalse( Hibernate.isInitialized( q.getMoreChildren() ) );
+
+ assertEquals( p.getMoreChildren().size(), 0 );
+
+ assertTrue( Hibernate.isInitialized( q.getMoreChildren() ) );
+
+ assertEquals( q.getMoreChildren().size(), 2 );
+
+ assertTrue( Hibernate.isInitialized( q.getMoreChildren().iterator().next() ) );
+
+ assertEquals( 3, getSessions().getStatistics().getPrepareStatementCount() );
+
+ Child c = (Child) p.getChildren().get(0);
+ c.getFriends().size();
+
+ s.delete(p);
+ s.delete(q);
+
+ t.commit();
+ s.close();
+ }
+
+}
+
diff --git a/test/org/hibernate/test/ternary/Employee.java b/test/org/hibernate/test/ternary/Employee.java
new file mode 100755
index 0000000000..31884060b2
--- /dev/null
+++ b/test/org/hibernate/test/ternary/Employee.java
@@ -0,0 +1,47 @@
+//$Id$
+package org.hibernate.test.ternary;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @author Gavin King
+ */
+public class Employee {
+ private String name;
+ private Date hireDate;
+ private Map managerBySite = new HashMap();
+ private Set underlings = new HashSet();
+
+ Employee() {}
+ public Employee(String name) {
+ this.name=name;
+ }
+ public Map getManagerBySite() {
+ return managerBySite;
+ }
+ public void setManagerBySite(Map managerBySite) {
+ this.managerBySite = managerBySite;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+ public Set getUnderlings() {
+ return underlings;
+ }
+ public void setUnderlings(Set underlings) {
+ this.underlings = underlings;
+ }
+ public Date getHireDate() {
+ return hireDate;
+ }
+ public void setHireDate(Date hireDate) {
+ this.hireDate = hireDate;
+ }
+}
diff --git a/test/org/hibernate/test/ternary/Site.java b/test/org/hibernate/test/ternary/Site.java
new file mode 100755
index 0000000000..561e38d5ed
--- /dev/null
+++ b/test/org/hibernate/test/ternary/Site.java
@@ -0,0 +1,44 @@
+//$Id$
+package org.hibernate.test.ternary;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * @author Gavin King
+ */
+public class Site {
+ private String name;
+ private String description;
+ private Set employees = new HashSet();
+ private Set managers = new HashSet();
+
+ Site() {}
+ public Site(String name) {
+ this.name=name;
+ }
+ public Set getManagers() {
+ return managers;
+ }
+ public void setManagers(Set managers) {
+ this.managers = managers;
+ }
+ public String getDescription() {
+ return description;
+ }
+ public void setDescription(String description) {
+ this.description = description;
+ }
+ public Set getEmployees() {
+ return employees;
+ }
+ public void setEmployees(Set employees) {
+ this.employees = employees;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/test/org/hibernate/test/ternary/Ternary.hbm.xml b/test/org/hibernate/test/ternary/Ternary.hbm.xml
new file mode 100755
index 0000000000..50ffa07424
--- /dev/null
+++ b/test/org/hibernate/test/ternary/Ternary.hbm.xml
@@ -0,0 +1,36 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/org/hibernate/test/ternary/TernaryTest.java b/test/org/hibernate/test/ternary/TernaryTest.java
new file mode 100755
index 0000000000..9ab50e4625
--- /dev/null
+++ b/test/org/hibernate/test/ternary/TernaryTest.java
@@ -0,0 +1,116 @@
+//$Id$
+package org.hibernate.test.ternary;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import junit.framework.Test;
+
+import org.hibernate.Hibernate;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * @author Gavin King
+ */
+public class TernaryTest extends FunctionalTestCase {
+
+ public TernaryTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "ternary/Ternary.hbm.xml" };
+ }
+
+ public String getCacheConcurrencyStrategy() {
+ return null;
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( TernaryTest.class );
+ }
+
+ public void testTernary() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Employee bob = new Employee("Bob");
+ Employee tom = new Employee("Tom");
+ Employee jim = new Employee("Jim");
+ Employee tim = new Employee("Tim");
+ Site melb = new Site("Melbourne");
+ Site geel = new Site("Geelong");
+ s.persist(bob);
+ s.persist(tom);
+ s.persist(jim);
+ s.persist(tim);
+ s.persist(melb);
+ s.persist(geel);
+ bob.getManagerBySite().put(melb, tom);
+ bob.getManagerBySite().put(geel, jim);
+ tim.getManagerBySite().put(melb, tom);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ tom = (Employee) s.get(Employee.class, "Tom");
+ assertFalse( Hibernate.isInitialized(tom.getUnderlings()) );
+ assertEquals( tom.getUnderlings().size(), 2 );
+ bob = (Employee) s.get(Employee.class, "Bob");
+ assertFalse( Hibernate.isInitialized(bob.getManagerBySite()) );
+ assertTrue( tom.getUnderlings().contains(bob) );
+ melb = (Site) s.get(Site.class, "Melbourne");
+ assertSame( bob.getManagerBySite().get(melb), tom );
+ assertTrue( melb.getEmployees().contains(bob) );
+ assertTrue( melb.getManagers().contains(tom) );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ List l = s.createQuery("from Employee e join e.managerBySite m where m.name='Bob'").list();
+ assertEquals( l.size(), 0 );
+ l = s.createQuery("from Employee e join e.managerBySite m where m.name='Tom'").list();
+ assertEquals( l.size(), 2 );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ l = s.createQuery("from Employee e left join fetch e.managerBySite").list();
+ assertEquals( l.size(), 5 );
+ Set set = new HashSet(l);
+ assertEquals( set.size(), 4 );
+ Iterator iter = set.iterator();
+ int total=0;
+ while ( iter.hasNext() ) {
+ Map map = ( (Employee) iter.next() ).getManagerBySite();
+ assertTrue( Hibernate.isInitialized(map) );
+ total += map.size();
+ }
+ assertTrue(total==3);
+
+ l = s.createQuery("from Employee e left join e.managerBySite m left join m.managerBySite m2").list();
+
+ // clean up...
+ l = s.createQuery("from Employee e left join fetch e.managerBySite").list();
+ Iterator itr = l.iterator();
+ while ( itr.hasNext() ) {
+ Employee emp = ( Employee ) itr.next();
+ emp.setManagerBySite( new HashMap() );
+ s.delete( emp );
+ }
+ ((org.hibernate.classic.Session)s).delete("from Site");
+ t.commit();
+ s.close();
+ }
+
+}
+
diff --git a/test/org/hibernate/test/timestamp/Person.java b/test/org/hibernate/test/timestamp/Person.java
new file mode 100755
index 0000000000..7145274c5f
--- /dev/null
+++ b/test/org/hibernate/test/timestamp/Person.java
@@ -0,0 +1,37 @@
+//$Id$
+package org.hibernate.test.timestamp;
+
+import java.util.Date;
+
+/**
+ * @author Gavin King
+ */
+public class Person {
+ private String name;
+ private Date dob;
+ private String currentAddress;
+ Person() {}
+ public Person(String name, Date dob, String address) {
+ this.name = name;
+ this.dob = dob;
+ this.currentAddress = address;
+ }
+ public Date getDob() {
+ return dob;
+ }
+ public void setDob(Date dob) {
+ this.dob = dob;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+ public String getCurrentAddress() {
+ return currentAddress;
+ }
+ public void setCurrentAddress(String currentAddress) {
+ this.currentAddress = currentAddress;
+ }
+}
diff --git a/test/org/hibernate/test/timestamp/TimestampTest.java b/test/org/hibernate/test/timestamp/TimestampTest.java
new file mode 100755
index 0000000000..9bfb10ce18
--- /dev/null
+++ b/test/org/hibernate/test/timestamp/TimestampTest.java
@@ -0,0 +1,91 @@
+//$Id$
+package org.hibernate.test.timestamp;
+
+import java.util.Date;
+
+import junit.framework.Test;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * @author Gavin King
+ */
+public class TimestampTest extends FunctionalTestCase {
+
+ public TimestampTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "timestamp/User.hbm.xml" };
+ }
+
+ public void configure(Configuration cfg) {
+ cfg.setProperty(Environment.GENERATE_STATISTICS, "true");
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( TimestampTest.class );
+ }
+
+ public void testUpdateFalse() {
+
+ getSessions().getStatistics().clear();
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ User u = new User( "gavin", "secret", new Person("Gavin King", new Date(), "Karbarook Ave") );
+ s.persist(u);
+ s.flush();
+ u.getPerson().setName("XXXXYYYYY");
+ t.commit();
+ s.close();
+
+ assertEquals( 1, getSessions().getStatistics().getEntityInsertCount() );
+ assertEquals( 0, getSessions().getStatistics().getEntityUpdateCount() );
+
+ s = openSession();
+ t = s.beginTransaction();
+ u = (User) s.get(User.class, "gavin");
+ assertEquals( u.getPerson().getName(), "Gavin King" );
+ s.delete(u);
+ t.commit();
+ s.close();
+
+ assertEquals( 1, getSessions().getStatistics().getEntityDeleteCount() );
+ }
+
+ public void testComponent() {
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ User u = new User( "gavin", "secret", new Person("Gavin King", new Date(), "Karbarook Ave") );
+ s.persist(u);
+ s.flush();
+ u.getPerson().setCurrentAddress("Peachtree Rd");
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ u = (User) s.get(User.class, "gavin");
+ u.setPassword("$ecret");
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ u = (User) s.get(User.class, "gavin");
+ assertEquals( u.getPassword(), "$ecret" );
+ s.delete(u);
+ t.commit();
+ s.close();
+ }
+
+}
+
diff --git a/test/org/hibernate/test/timestamp/User.hbm.xml b/test/org/hibernate/test/timestamp/User.hbm.xml
new file mode 100755
index 0000000000..9611c967d7
--- /dev/null
+++ b/test/org/hibernate/test/timestamp/User.hbm.xml
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/org/hibernate/test/timestamp/User.java b/test/org/hibernate/test/timestamp/User.java
new file mode 100755
index 0000000000..5807584b9d
--- /dev/null
+++ b/test/org/hibernate/test/timestamp/User.java
@@ -0,0 +1,44 @@
+//$Id$
+package org.hibernate.test.timestamp;
+
+import java.util.Date;
+
+/**
+ * @author Gavin King
+ */
+public class User {
+ private String userName;
+ private String password;
+ private Person person;
+ private Date lastModified;
+ User() {}
+ public User(String id, String pw, Person person) {
+ this.userName = id;
+ this.password = pw;
+ this.person = person;
+ }
+ public Date getLastModified() {
+ return lastModified;
+ }
+ public void setLastModified(Date lastModified) {
+ this.lastModified = lastModified;
+ }
+ public String getPassword() {
+ return password;
+ }
+ public void setPassword(String password) {
+ this.password = password;
+ }
+ public Person getPerson() {
+ return person;
+ }
+ public void setPerson(Person person) {
+ this.person = person;
+ }
+ public String getUserName() {
+ return userName;
+ }
+ public void setUserName(String userName) {
+ this.userName = userName;
+ }
+}
diff --git a/test/org/hibernate/test/tm/CMTTest.java b/test/org/hibernate/test/tm/CMTTest.java
new file mode 100755
index 0000000000..999c6588f1
--- /dev/null
+++ b/test/org/hibernate/test/tm/CMTTest.java
@@ -0,0 +1,513 @@
+//$Id$
+package org.hibernate.test.tm;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import javax.transaction.Transaction;
+
+import junit.framework.Test;
+
+import org.hibernate.ConnectionReleaseMode;
+import org.hibernate.EntityMode;
+import org.hibernate.ScrollableResults;
+import org.hibernate.Session;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.criterion.Order;
+import org.hibernate.dialect.SybaseDialect;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.transaction.CMTTransactionFactory;
+import org.hibernate.util.SerializationHelper;
+
+/**
+ * @author Gavin King
+ */
+public class CMTTest extends FunctionalTestCase {
+
+ public CMTTest(String str) {
+ super( str );
+ }
+
+ public String[] getMappings() {
+ return new String[] { "tm/Item.hbm.xml" };
+ }
+
+ public void configure(Configuration cfg) {
+ cfg.setProperty( Environment.CONNECTION_PROVIDER, DummyConnectionProvider.class.getName() );
+ cfg.setProperty( Environment.TRANSACTION_MANAGER_STRATEGY, DummyTransactionManagerLookup.class.getName() );
+ cfg.setProperty( Environment.TRANSACTION_STRATEGY, CMTTransactionFactory.class.getName() );
+ cfg.setProperty( Environment.AUTO_CLOSE_SESSION, "true" );
+ cfg.setProperty( Environment.FLUSH_BEFORE_COMPLETION, "true" );
+ cfg.setProperty( Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.AFTER_STATEMENT.toString() );
+ cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
+ cfg.setProperty( Environment.USE_QUERY_CACHE, "true" );
+ cfg.setProperty( Environment.DEFAULT_ENTITY_MODE, EntityMode.MAP.toString() );
+ }
+
+ public String getCacheConcurrencyStrategy() {
+ return "transactional";
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( CMTTest.class );
+ }
+
+ public void testConcurrent() throws Exception {
+ getSessions().getStatistics().clear();
+
+ DummyTransactionManager.INSTANCE.begin();
+ Session s = openSession();
+ Map foo = new HashMap();
+ foo.put( "name", "Foo" );
+ foo.put( "description", "a big foo" );
+ s.persist( "Item", foo );
+ Map bar = new HashMap();
+ bar.put( "name", "Bar" );
+ bar.put( "description", "a small bar" );
+ s.persist( "Item", bar );
+ DummyTransactionManager.INSTANCE.commit();
+
+ getSessions().evictEntity( "Item" );
+
+ DummyTransactionManager.INSTANCE.begin();
+ Session s1 = openSession();
+ foo = ( Map ) s1.get( "Item", "Foo" );
+ //foo.put("description", "a big red foo");
+ //s1.flush();
+ Transaction tx1 = DummyTransactionManager.INSTANCE.suspend();
+
+ DummyTransactionManager.INSTANCE.begin();
+ Session s2 = openSession();
+ foo = ( Map ) s2.get( "Item", "Foo" );
+ DummyTransactionManager.INSTANCE.commit();
+
+ DummyTransactionManager.INSTANCE.resume( tx1 );
+ tx1.commit();
+
+ getSessions().evictEntity( "Item" );
+
+ DummyTransactionManager.INSTANCE.begin();
+ s1 = openSession();
+ s1.createCriteria( "Item" ).list();
+ //foo.put("description", "a big red foo");
+ //s1.flush();
+ tx1 = DummyTransactionManager.INSTANCE.suspend();
+
+ DummyTransactionManager.INSTANCE.begin();
+ s2 = openSession();
+ s2.createCriteria( "Item" ).list();
+ DummyTransactionManager.INSTANCE.commit();
+
+ DummyTransactionManager.INSTANCE.resume( tx1 );
+ tx1.commit();
+
+ DummyTransactionManager.INSTANCE.begin();
+ s2 = openSession();
+ s2.createCriteria( "Item" ).list();
+ DummyTransactionManager.INSTANCE.commit();
+
+ assertEquals( getSessions().getStatistics().getEntityLoadCount(), 7 );
+ assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 );
+ assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 3 );
+ assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 0 );
+ assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 0 );
+
+ DummyTransactionManager.INSTANCE.begin();
+ s = openSession();
+ s.createQuery( "delete from Item" ).executeUpdate();
+ DummyTransactionManager.INSTANCE.commit();
+ }
+
+ public void testConcurrentCachedQueries() throws Exception {
+
+ DummyTransactionManager.INSTANCE.begin();
+ Session s = openSession();
+ Map foo = new HashMap();
+ foo.put( "name", "Foo" );
+ foo.put( "description", "a big foo" );
+ s.persist( "Item", foo );
+ Map bar = new HashMap();
+ bar.put( "name", "Bar" );
+ bar.put( "description", "a small bar" );
+ s.persist( "Item", bar );
+ DummyTransactionManager.INSTANCE.commit();
+
+ synchronized ( this ) {
+ wait( 1000 );
+ }
+
+ getSessions().getStatistics().clear();
+
+ getSessions().evictEntity( "Item" );
+
+ DummyTransactionManager.INSTANCE.begin();
+ Session s4 = openSession();
+ Transaction tx4 = DummyTransactionManager.INSTANCE.suspend();
+
+ DummyTransactionManager.INSTANCE.begin();
+ Session s1 = openSession();
+ List r1 = s1.createCriteria( "Item" ).addOrder( Order.asc( "description" ) )
+ .setCacheable( true ).list();
+ assertEquals( r1.size(), 2 );
+ Transaction tx1 = DummyTransactionManager.INSTANCE.suspend();
+
+ DummyTransactionManager.INSTANCE.begin();
+ Session s2 = openSession();
+ List r2 = s2.createCriteria( "Item" ).addOrder( Order.asc( "description" ) )
+ .setCacheable( true ).list();
+ assertEquals( r2.size(), 2 );
+ DummyTransactionManager.INSTANCE.commit();
+
+ assertEquals( getSessions().getStatistics().getSecondLevelCacheHitCount(), 2 );
+ assertEquals( getSessions().getStatistics().getSecondLevelCacheMissCount(), 0 );
+ assertEquals( getSessions().getStatistics().getEntityLoadCount(), 2 );
+ assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 );
+ assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 1 );
+ assertEquals( getSessions().getStatistics().getQueryCachePutCount(), 1 );
+ assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 1 );
+ assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 1 );
+
+ DummyTransactionManager.INSTANCE.resume( tx1 );
+ tx1.commit();
+
+ DummyTransactionManager.INSTANCE.begin();
+ Session s3 = openSession();
+ s3.createCriteria( "Item" ).addOrder( Order.asc( "description" ) )
+ .setCacheable( true ).list();
+ DummyTransactionManager.INSTANCE.commit();
+
+ assertEquals( getSessions().getStatistics().getSecondLevelCacheHitCount(), 4 );
+ assertEquals( getSessions().getStatistics().getSecondLevelCacheMissCount(), 0 );
+ assertEquals( getSessions().getStatistics().getEntityLoadCount(), 2 );
+ assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 );
+ assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 1 );
+ assertEquals( getSessions().getStatistics().getQueryCachePutCount(), 1 );
+ assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 2 );
+ assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 1 );
+
+ DummyTransactionManager.INSTANCE.resume( tx4 );
+ List r4 = s4.createCriteria( "Item" ).addOrder( Order.asc( "description" ) )
+ .setCacheable( true ).list();
+ assertEquals( r4.size(), 2 );
+ tx4.commit();
+
+ assertEquals( getSessions().getStatistics().getSecondLevelCacheHitCount(), 6 );
+ assertEquals( getSessions().getStatistics().getSecondLevelCacheMissCount(), 0 );
+ assertEquals( getSessions().getStatistics().getEntityLoadCount(), 2 );
+ assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 );
+ assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 1 );
+ assertEquals( getSessions().getStatistics().getQueryCachePutCount(), 1 );
+ assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 3 );
+ assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 1 );
+
+ DummyTransactionManager.INSTANCE.begin();
+ s = openSession();
+ s.createQuery( "delete from Item" ).executeUpdate();
+ DummyTransactionManager.INSTANCE.commit();
+ }
+
+ public void testConcurrentCachedDirtyQueries() throws Exception {
+ if ( getDialect().doesReadCommittedCauseWritersToBlockReaders() ) {
+ reportSkip( "write locks block readers", "concurrent queries" );
+ return;
+ }
+
+ DummyTransactionManager.INSTANCE.begin();
+ Session s = openSession();
+ Map foo = new HashMap();
+ foo.put( "name", "Foo" );
+ foo.put( "description", "a big foo" );
+ s.persist( "Item", foo );
+ Map bar = new HashMap();
+ bar.put( "name", "Bar" );
+ bar.put( "description", "a small bar" );
+ s.persist( "Item", bar );
+ DummyTransactionManager.INSTANCE.commit();
+
+ synchronized ( this ) {
+ wait( 1000 );
+ }
+
+ getSessions().getStatistics().clear();
+
+ getSessions().evictEntity( "Item" );
+
+ DummyTransactionManager.INSTANCE.begin();
+ Session s4 = openSession();
+ Transaction tx4 = DummyTransactionManager.INSTANCE.suspend();
+
+ DummyTransactionManager.INSTANCE.begin();
+ Session s1 = openSession();
+ List r1 = s1.createCriteria( "Item" ).addOrder( Order.asc( "description" ) )
+ .setCacheable( true ).list();
+ assertEquals( r1.size(), 2 );
+ foo = ( Map ) r1.get( 0 );
+ foo.put( "description", "a big red foo" );
+ s1.flush();
+ Transaction tx1 = DummyTransactionManager.INSTANCE.suspend();
+
+ DummyTransactionManager.INSTANCE.begin();
+ Session s2 = openSession();
+ List r2 = s2.createCriteria( "Item" ).addOrder( Order.asc( "description" ) )
+ .setCacheable( true ).list();
+ assertEquals( r2.size(), 2 );
+ DummyTransactionManager.INSTANCE.commit();
+
+ assertEquals( getSessions().getStatistics().getSecondLevelCacheHitCount(), 0 );
+ assertEquals( getSessions().getStatistics().getSecondLevelCacheMissCount(), 0 );
+ assertEquals( getSessions().getStatistics().getEntityLoadCount(), 4 );
+ assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 );
+ assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 2 );
+ assertEquals( getSessions().getStatistics().getQueryCachePutCount(), 2 );
+ assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 0 );
+ assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 2 );
+
+ DummyTransactionManager.INSTANCE.resume( tx1 );
+ tx1.commit();
+
+ DummyTransactionManager.INSTANCE.begin();
+ Session s3 = openSession();
+ s3.createCriteria( "Item" ).addOrder( Order.asc( "description" ) )
+ .setCacheable( true ).list();
+ DummyTransactionManager.INSTANCE.commit();
+
+ assertEquals( getSessions().getStatistics().getSecondLevelCacheHitCount(), 0 );
+ assertEquals( getSessions().getStatistics().getSecondLevelCacheMissCount(), 0 );
+ assertEquals( getSessions().getStatistics().getEntityLoadCount(), 6 );
+ assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 );
+ assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 3 );
+ assertEquals( getSessions().getStatistics().getQueryCachePutCount(), 3 );
+ assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 0 );
+ assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 3 );
+
+ DummyTransactionManager.INSTANCE.resume( tx4 );
+ List r4 = s4.createCriteria( "Item" ).addOrder( Order.asc( "description" ) )
+ .setCacheable( true ).list();
+ assertEquals( r4.size(), 2 );
+ tx4.commit();
+
+ assertEquals( getSessions().getStatistics().getSecondLevelCacheHitCount(), 2 );
+ assertEquals( getSessions().getStatistics().getSecondLevelCacheMissCount(), 0 );
+ assertEquals( getSessions().getStatistics().getEntityLoadCount(), 6 );
+ assertEquals( getSessions().getStatistics().getEntityFetchCount(), 0 );
+ assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 3 );
+ assertEquals( getSessions().getStatistics().getQueryCachePutCount(), 3 );
+ assertEquals( getSessions().getStatistics().getQueryCacheHitCount(), 1 );
+ assertEquals( getSessions().getStatistics().getQueryCacheMissCount(), 3 );
+
+ DummyTransactionManager.INSTANCE.begin();
+ s = openSession();
+ s.createQuery( "delete from Item" ).executeUpdate();
+ DummyTransactionManager.INSTANCE.commit();
+ }
+
+ public void testCMT() throws Exception {
+ getSessions().getStatistics().clear();
+
+ DummyTransactionManager.INSTANCE.begin();
+ Session s = openSession();
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+ assertFalse( s.isOpen() );
+
+ assertEquals( getSessions().getStatistics().getFlushCount(), 0 );
+
+ DummyTransactionManager.INSTANCE.begin();
+ s = openSession();
+ DummyTransactionManager.INSTANCE.getTransaction().rollback();
+ assertFalse( s.isOpen() );
+
+ DummyTransactionManager.INSTANCE.begin();
+ s = openSession();
+ Map item = new HashMap();
+ item.put( "name", "The Item" );
+ item.put( "description", "The only item we have" );
+ s.persist( "Item", item );
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+ assertFalse( s.isOpen() );
+
+ DummyTransactionManager.INSTANCE.begin();
+ s = openSession();
+ item = ( Map ) s.createQuery( "from Item" ).uniqueResult();
+ assertNotNull( item );
+ s.delete( item );
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+ assertFalse( s.isOpen() );
+
+ assertEquals( getSessions().getStatistics().getTransactionCount(), 4 );
+ assertEquals( getSessions().getStatistics().getSuccessfulTransactionCount(), 3 );
+ assertEquals( getSessions().getStatistics().getEntityDeleteCount(), 1 );
+ assertEquals( getSessions().getStatistics().getEntityInsertCount(), 1 );
+ assertEquals( getSessions().getStatistics().getSessionOpenCount(), 4 );
+ assertEquals( getSessions().getStatistics().getSessionCloseCount(), 4 );
+ assertEquals( getSessions().getStatistics().getQueryExecutionCount(), 1 );
+ assertEquals( getSessions().getStatistics().getFlushCount(), 2 );
+
+ DummyTransactionManager.INSTANCE.begin();
+ s = openSession();
+ s.createQuery( "delete from Item" ).executeUpdate();
+ DummyTransactionManager.INSTANCE.commit();
+
+ }
+
+ public void testCurrentSession() throws Exception {
+ DummyTransactionManager.INSTANCE.begin();
+ Session s = getSessions().getCurrentSession();
+ Session s2 = getSessions().getCurrentSession();
+ assertSame( s, s2 );
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+ assertFalse( s.isOpen() );
+
+ // TODO : would be nice to automate-test that the SF internal map actually gets cleaned up
+ // i verified that is does currently in my debugger...
+ }
+
+ public void testCurrentSessionWithIterate() throws Exception {
+ DummyTransactionManager.INSTANCE.begin();
+ Session s = openSession();
+ Map item1 = new HashMap();
+ item1.put( "name", "Item - 1" );
+ item1.put( "description", "The first item" );
+ s.persist( "Item", item1 );
+
+ Map item2 = new HashMap();
+ item2.put( "name", "Item - 2" );
+ item2.put( "description", "The second item" );
+ s.persist( "Item", item2 );
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+
+ // First, test iterating the partial iterator; iterate to past
+ // the first, but not the second, item
+ DummyTransactionManager.INSTANCE.begin();
+ s = getSessions().getCurrentSession();
+ Iterator itr = s.createQuery( "from Item" ).iterate();
+ if ( !itr.hasNext() ) {
+ fail( "No results in iterator" );
+ }
+ itr.next();
+ if ( !itr.hasNext() ) {
+ fail( "Only one result in iterator" );
+ }
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+
+ // Next, iterate the entire result
+ DummyTransactionManager.INSTANCE.begin();
+ s = getSessions().getCurrentSession();
+ itr = s.createQuery( "from Item" ).iterate();
+ if ( !itr.hasNext() ) {
+ fail( "No results in iterator" );
+ }
+ while ( itr.hasNext() ) {
+ itr.next();
+ }
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+
+ DummyTransactionManager.INSTANCE.begin();
+ s = openSession();
+ s.createQuery( "delete from Item" ).executeUpdate();
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+ }
+
+ public void testCurrentSessionWithScroll() throws Exception {
+ DummyTransactionManager.INSTANCE.begin();
+ Session s = getSessions().getCurrentSession();
+ Map item1 = new HashMap();
+ item1.put( "name", "Item - 1" );
+ item1.put( "description", "The first item" );
+ s.persist( "Item", item1 );
+
+ Map item2 = new HashMap();
+ item2.put( "name", "Item - 2" );
+ item2.put( "description", "The second item" );
+ s.persist( "Item", item2 );
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+
+ // First, test partially scrolling the result with out closing
+ DummyTransactionManager.INSTANCE.begin();
+ s = getSessions().getCurrentSession();
+ ScrollableResults results = s.createQuery( "from Item" ).scroll();
+ results.next();
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+
+ // Next, test partially scrolling the result with closing
+ DummyTransactionManager.INSTANCE.begin();
+ s = getSessions().getCurrentSession();
+ results = s.createQuery( "from Item" ).scroll();
+ results.next();
+ results.close();
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+
+ // Next, scroll the entire result (w/o closing)
+ DummyTransactionManager.INSTANCE.begin();
+ s = getSessions().getCurrentSession();
+ results = s.createQuery( "from Item" ).scroll();
+ while ( !results.isLast() ) {
+ results.next();
+ }
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+
+ // Next, scroll the entire result (closing)
+ DummyTransactionManager.INSTANCE.begin();
+ s = getSessions().getCurrentSession();
+ results = s.createQuery( "from Item" ).scroll();
+ while ( !results.isLast() ) {
+ results.next();
+ }
+ results.close();
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+
+ DummyTransactionManager.INSTANCE.begin();
+ s = getSessions().getCurrentSession();
+ s.createQuery( "delete from Item" ).executeUpdate();
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+ }
+
+ public void testAggressiveReleaseWithExplicitDisconnectReconnect() throws Exception {
+ DummyTransactionManager.INSTANCE.begin();
+ Session s = getSessions().getCurrentSession();
+
+ s.createQuery( "from Item" ).list();
+
+ s.disconnect();
+ byte[] bytes = SerializationHelper.serialize( s );
+ s = ( Session ) SerializationHelper.deserialize( bytes );
+ s.reconnect();
+
+ s.createQuery( "from Item" ).list();
+
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+ }
+
+ public void testAggressiveReleaseWithConnectionRetreival() throws Exception {
+ DummyTransactionManager.INSTANCE.begin();
+ Session s = openSession();
+ Map item1 = new HashMap();
+ item1.put( "name", "Item - 1" );
+ item1.put( "description", "The first item" );
+ s.save( "Item", item1 );
+
+ Map item2 = new HashMap();
+ item2.put( "name", "Item - 2" );
+ item2.put( "description", "The second item" );
+ s.save( "Item", item2 );
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+
+ try {
+ DummyTransactionManager.INSTANCE.begin();
+ s = getSessions().getCurrentSession();
+ s.createQuery( "from Item" ).scroll().next();
+ s.connection();
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+ }
+ finally {
+ DummyTransactionManager.INSTANCE.begin();
+ s = openSession();
+ s.createQuery( "delete from Item" ).executeUpdate();
+ DummyTransactionManager.INSTANCE.getTransaction().commit();
+ }
+ }
+
+}
+
diff --git a/test/org/hibernate/test/tm/DummyConnectionProvider.java b/test/org/hibernate/test/tm/DummyConnectionProvider.java
new file mode 100755
index 0000000000..4ced0f94de
--- /dev/null
+++ b/test/org/hibernate/test/tm/DummyConnectionProvider.java
@@ -0,0 +1,48 @@
+//$Id$
+package org.hibernate.test.tm;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.Properties;
+
+import org.hibernate.HibernateException;
+import org.hibernate.connection.ConnectionProvider;
+import org.hibernate.connection.ConnectionProviderFactory;
+
+/**
+ * @author Gavin King
+ */
+public class DummyConnectionProvider implements ConnectionProvider {
+
+ ConnectionProvider cp;
+ boolean isTransaction;
+
+ public void configure(Properties props) throws HibernateException {
+ cp = ConnectionProviderFactory.newConnectionProvider();
+ }
+
+ public Connection getConnection() throws SQLException {
+ DummyTransactionManager dtm = DummyTransactionManager.INSTANCE;
+ if ( dtm!=null && dtm.getCurrent()!=null && dtm.getCurrent().getConnection()!=null ) {
+ isTransaction = true;
+ return dtm.getCurrent().getConnection();
+ }
+ else {
+ isTransaction = false;
+ return cp.getConnection();
+ }
+ }
+
+ public void closeConnection(Connection conn) throws SQLException {
+ if (!isTransaction) conn.close();
+ }
+
+ public void close() throws HibernateException {
+
+ }
+
+ public boolean supportsAggressiveRelease() {
+ return true;
+ }
+
+}
diff --git a/test/org/hibernate/test/tm/DummyJTAStyleTransationFactory.java b/test/org/hibernate/test/tm/DummyJTAStyleTransationFactory.java
new file mode 100644
index 0000000000..3d368f7cd0
--- /dev/null
+++ b/test/org/hibernate/test/tm/DummyJTAStyleTransationFactory.java
@@ -0,0 +1,138 @@
+package org.hibernate.test.tm;
+
+import org.hibernate.transaction.TransactionFactory;
+import org.hibernate.Transaction;
+import org.hibernate.HibernateException;
+import org.hibernate.ConnectionReleaseMode;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.util.JTAHelper;
+import org.hibernate.jdbc.JDBCContext;
+
+import javax.transaction.SystemException;
+import javax.transaction.Synchronization;
+import java.util.Properties;
+
+/**
+ * todo: describe DummyJTAStyleTransationFactory
+ *
+ * @author Steve Ebersole
+ */
+public class DummyJTAStyleTransationFactory implements TransactionFactory {
+ public Transaction createTransaction(
+ JDBCContext jdbcContext,
+ Context context) throws HibernateException {
+ return new DummyTransactionAdapter();
+ }
+
+ public void configure(Properties props) throws HibernateException {
+ }
+
+ public ConnectionReleaseMode getDefaultReleaseMode() {
+ return ConnectionReleaseMode.AFTER_STATEMENT;
+ }
+
+ public boolean isTransactionManagerRequired() {
+ return true;
+ }
+
+ public boolean areCallbacksLocalToHibernateTransactions() {
+ return false;
+ }
+
+ public boolean isTransactionInProgress(
+ JDBCContext jdbcContext,
+ Context transactionContext,
+ Transaction transaction) {
+ try {
+ return JTAHelper.isTransactionInProgress( DummyTransactionManager.INSTANCE.getCurrent() )
+ && ! JTAHelper.isMarkedForRollback( DummyTransactionManager.INSTANCE.getCurrent() );
+ }
+ catch( SystemException e ) {
+ throw new HibernateException( e );
+ }
+ }
+
+ private static class DummyTransactionAdapter implements Transaction {
+
+ private boolean started;
+ private boolean committed;
+ private boolean rolledback;
+
+ public void begin() throws HibernateException {
+ started = true;
+ committed = false;
+ rolledback = false;
+ try {
+ DummyTransactionManager.INSTANCE.begin();
+ }
+ catch( Throwable t ) {
+ throw new HibernateException( "error on begin()", t );
+ }
+ }
+
+ public void commit() throws HibernateException {
+ if ( !started ) {
+ throw new HibernateException( "not yet started!" );
+ }
+ started = false;
+ rolledback = false;
+ committed = false;
+ try {
+ DummyTransactionManager.INSTANCE.commit();
+ committed = true;
+ }
+ catch( Throwable t ) {
+ throw new HibernateException( "error on commit()", t );
+ }
+ }
+
+ public void rollback() throws HibernateException {
+ if ( !started ) {
+ throw new HibernateException( "not yet started!" );
+ }
+ started = false;
+ rolledback = false;
+ committed = false;
+ try {
+ DummyTransactionManager.INSTANCE.rollback();
+ rolledback = true;
+ }
+ catch( Throwable t ) {
+ throw new HibernateException( "error on rollback()", t );
+ }
+ }
+
+ public boolean wasRolledBack() throws HibernateException {
+ return rolledback;
+ }
+
+ public boolean wasCommitted() throws HibernateException {
+ return committed;
+ }
+
+ public boolean isActive() throws HibernateException {
+ return started;
+ }
+
+ public void registerSynchronization(Synchronization synchronization) throws HibernateException {
+ try {
+ DummyTransactionManager.INSTANCE.getCurrent().registerSynchronization( synchronization );
+ }
+ catch( Throwable t ) {
+ throw new HibernateException( "error on registerSynchronization()", t );
+ }
+ }
+
+ public void setTimeout(int seconds) {
+ // ignore...
+ }
+ }
+
+ public static void setup(Configuration cfg) {
+ cfg.setProperty( Environment.CONNECTION_PROVIDER, DummyConnectionProvider.class.getName() );
+ cfg.setProperty( Environment.TRANSACTION_MANAGER_STRATEGY, DummyTransactionManagerLookup.class.getName() );
+ cfg.setProperty( Environment.TRANSACTION_STRATEGY, DummyJTAStyleTransationFactory.class.getName() );
+ cfg.setProperty( Environment.FLUSH_BEFORE_COMPLETION, "true" );
+ }
+}
diff --git a/test/org/hibernate/test/tm/DummyTransaction.java b/test/org/hibernate/test/tm/DummyTransaction.java
new file mode 100755
index 0000000000..bd3148093a
--- /dev/null
+++ b/test/org/hibernate/test/tm/DummyTransaction.java
@@ -0,0 +1,146 @@
+//$Id$
+package org.hibernate.test.tm;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.transaction.HeuristicMixedException;
+import javax.transaction.HeuristicRollbackException;
+import javax.transaction.RollbackException;
+import javax.transaction.Status;
+import javax.transaction.Synchronization;
+import javax.transaction.SystemException;
+import javax.transaction.Transaction;
+import javax.transaction.xa.XAResource;
+
+/**
+ * @author Gavin King
+ */
+public class DummyTransaction implements Transaction {
+
+ int status;
+ private Connection connection;
+ List synchronizations = new ArrayList();
+ private DummyTransactionManager transactionManager;
+
+ DummyTransaction(DummyTransactionManager transactionManager) {
+ status = Status.STATUS_NO_TRANSACTION;
+ this.transactionManager = transactionManager;
+ }
+
+ public void begin() throws SystemException {
+ try {
+ connection = transactionManager.connections.getConnection();
+ }
+ catch (SQLException sqle) {
+
+ sqle.printStackTrace();
+ throw new SystemException(sqle.toString());
+ }
+ status = Status.STATUS_ACTIVE;
+ }
+
+ public void commit() throws RollbackException, HeuristicMixedException,
+ HeuristicRollbackException, SecurityException,
+ IllegalStateException, SystemException {
+
+ if (status == Status.STATUS_MARKED_ROLLBACK) {
+ rollback();
+ }
+ else {
+ status = Status.STATUS_PREPARING;
+
+ for ( int i=0; i
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/test/org/hibernate/test/tool/Team.hbm.xml b/test/org/hibernate/test/tool/Team.hbm.xml
new file mode 100644
index 0000000000..a0c3946e97
--- /dev/null
+++ b/test/org/hibernate/test/tool/Team.hbm.xml
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
+ TEAM_SEQ
+
+
+
+
+
+
+
+
+ TEAM_SEQ
+
+
+
+
+
+
diff --git a/test/org/hibernate/test/tool/Team.java b/test/org/hibernate/test/tool/Team.java
new file mode 100644
index 0000000000..6d3b71bca2
--- /dev/null
+++ b/test/org/hibernate/test/tool/Team.java
@@ -0,0 +1,20 @@
+package org.hibernate.test.tool;
+
+
+public class Team {
+ private Long id;
+ private String name;
+ public Long getId() {
+ return id;
+ }
+ public void setId(Long id) {
+ this.id = id;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+
+}
diff --git a/test/org/hibernate/test/tool/TestSchemaTools.java b/test/org/hibernate/test/tool/TestSchemaTools.java
new file mode 100644
index 0000000000..12e1f656e1
--- /dev/null
+++ b/test/org/hibernate/test/tool/TestSchemaTools.java
@@ -0,0 +1,226 @@
+package org.hibernate.test.tool;
+
+import java.sql.Connection;
+import java.sql.Statement;
+import java.sql.SQLException;
+
+import junit.framework.Test;
+
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+import org.hibernate.engine.SessionFactoryImplementor;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.HSQLDialect;
+import org.hibernate.junit.functional.DatabaseSpecificFunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.tool.hbm2ddl.SchemaExport;
+import org.hibernate.tool.hbm2ddl.SchemaUpdate;
+import org.hibernate.tool.hbm2ddl.SchemaValidator;
+
+/**
+ * @author Anthony
+ *
+ * Basic smoke test for schemaupdate/validator.
+ * Dependent on schemas, and probably also HQLDB - Not possible to have in the global test suite at the moment.
+ *
+ * WARNING, if you want this test to work, you need to define a default schema = SB
+ * in hibernate global configuration.
+ * This schema should not be the same at the default db user schema and should come after the users schema alphabetically.
+ *
+ */
+public class TestSchemaTools extends DatabaseSpecificFunctionalTestCase {
+
+ public TestSchemaTools(String name) {
+ super( name );
+ }
+
+ public String[] getMappings() {
+ return new String[] { "tool/Team.hbm.xml" };
+ }
+
+ public boolean createSchema() {
+ return false;
+ }
+
+ public void afterSessionFactoryBuilt(SessionFactoryImplementor sfi) {
+ super.afterSessionFactoryBuilt( sfi );
+ Session session = null;
+ try {
+ session = sfi.openSession();
+ Statement stat = session.connection().createStatement();
+ stat.execute("CREATE SCHEMA sb AUTHORIZATION DBA ");
+ stat.execute(" CREATE SCHEMA sa AUTHORIZATION DBA ");
+ stat.execute(" CREATE TABLE \"SA\".\"Team\" (test INTEGER) ");
+ stat.close();
+ }
+ catch ( SQLException e ) {
+ throw new RuntimeException( "could not prepare additional schemas" );
+ }
+ finally {
+ if ( session != null ) {
+ try {
+ session.close();
+ }
+ catch( Throwable ignore ) {
+ }
+ }
+ }
+ }
+
+ protected void prepareTest() throws Exception {
+ super.prepareTest();
+ }
+
+
+ public boolean appliesTo(Dialect dialect) {
+ return dialect instanceof HSQLDialect;
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( TestSchemaTools.class );
+ }
+
+ public void testSchemaTools() throws Exception{
+ // database schema have been created thanks to the setUp method
+ // we have 2 schemas SA et SB, SB must be set as the default schema
+ // used by hibernate hibernate.default_schema SB
+ SchemaExport se = new SchemaExport(getCfg());
+ se.create(true,true);
+
+ // here we modify the generated table in order to test SchemaUpdate
+ Session session = openSession();
+ Connection conn = session.connection();
+ Statement stat = conn.createStatement();
+ stat.execute("ALTER TABLE \"SB\".\"Team\" DROP COLUMN name ");
+
+ // update schema
+ SchemaUpdate su = new SchemaUpdate(getCfg());
+ su.execute(true,true);
+
+ // we can run schema validation. Note that in the setUp method a *wrong* table
+ // has been created with different column names
+ // if schema validator chooses the bad db schema, then the testcase will fail (exception)
+ SchemaValidator sv = new SchemaValidator(getCfg());
+ sv.validate();
+
+ // it's time to clean our database
+ se.drop(true,true);
+
+ // then the schemas and false table.
+
+ stat.execute("DROP TABLE \"SA\".\"Team\" ");
+ stat.execute(" DROP SCHEMA sa ");
+ stat.execute("DROP SCHEMA sb ");
+ stat.close();
+ session.close();
+ }
+
+ public void testSchemaToolsNonQuote() throws Exception{
+ // database schema have been created thanks to the setUp method
+ // we have 2 schemas SA et SB, SB must be set as the default schema
+ // used by hibernate hibernate.default_schema SB
+ SchemaExport se = new SchemaExport(getCfg());
+ se.create(true,true);
+
+ // here we modify the generated table in order to test SchemaUpdate
+ Session session = openSession();
+ Connection conn = session.connection();
+ Statement stat = conn.createStatement();
+ stat.execute("ALTER TABLE \"SB\".\"TEAM\" DROP COLUMN xname ");
+
+ // update schema
+ SchemaUpdate su = new SchemaUpdate(getCfg());
+ su.execute(true,true);
+
+ // we can run schema validation. Note that in the setUp method a *wrong* table
+ // has been created with different column names
+ // if schema validator chooses the bad db schema, then the testcase will fail (exception)
+ SchemaValidator sv = new SchemaValidator(getCfg());
+ sv.validate();
+
+ // it's time to clean our database
+ se.drop(true,true);
+
+ // then the schemas and false table.
+
+ stat.execute("DROP TABLE \"SA\".\"Team\" ");
+ stat.execute(" DROP SCHEMA sa ");
+ stat.execute("DROP SCHEMA sb ");
+ stat.close();
+ session.close();
+ }
+ public void testFailingQuoteValidation() throws Exception{
+ // database schema have been created thanks to the setUp method
+ // we have 2 schemas SA et SB, SB must be set as the default schema
+ // used by hibernate hibernate.default_schema SB
+ SchemaExport se = new SchemaExport(getCfg());
+ se.create(true,true);
+
+ // here we modify the generated table in order to test SchemaUpdate
+ Session session = openSession();
+ Connection conn = session.connection();
+ Statement stat = conn.createStatement();
+ stat.execute("ALTER TABLE \"SB\".\"Team\" DROP COLUMN name ");
+
+ // update schema
+ //SchemaUpdate su = new SchemaUpdate(getCfg());
+ //su.execute(true,true);
+
+ try {
+ SchemaValidator sv = new SchemaValidator(getCfg());
+ sv.validate();
+ fail("should fail since we mutated the current schema.");
+ } catch(HibernateException he) {
+
+ }
+
+ // it's time to clean our database
+ se.drop(true,true);
+
+ // then the schemas and false table.
+
+ stat.execute("DROP TABLE \"SA\".\"Team\" ");
+ stat.execute(" DROP SCHEMA sa ");
+ stat.execute("DROP SCHEMA sb ");
+ stat.close();
+ session.close();
+ }
+
+ public void testFailingNonQuoteValidation() throws Exception{
+ // database schema have been created thanks to the setUp method
+ // we have 2 schemas SA et SB, SB must be set as the default schema
+ // used by hibernate hibernate.default_schema SB
+ SchemaExport se = new SchemaExport(getCfg());
+ se.create(true,true);
+
+ // here we modify the generated table in order to test SchemaUpdate
+ Session session = openSession();
+ Connection conn = session.connection();
+ Statement stat = conn.createStatement();
+ stat.execute("ALTER TABLE \"SB\".\"TEAM\" DROP COLUMN xname ");
+
+ // update schema
+ //SchemaUpdate su = new SchemaUpdate(getCfg());
+ //su.execute(true,true);
+
+ try {
+ SchemaValidator sv = new SchemaValidator(getCfg());
+ sv.validate();
+ fail("should fail since we mutated the current schema.");
+ } catch(HibernateException he) {
+
+ }
+
+ // it's time to clean our database
+ se.drop(true,true);
+
+ // then the schemas and false table.
+
+ stat.execute("DROP TABLE \"SA\".\"Team\" ");
+ stat.execute(" DROP SCHEMA sa ");
+ stat.execute("DROP SCHEMA sb ");
+ stat.close();
+ session.close();
+ }
+
+}
diff --git a/test/org/hibernate/test/typedmanytoone/Address.java b/test/org/hibernate/test/typedmanytoone/Address.java
new file mode 100755
index 0000000000..682f1eb891
--- /dev/null
+++ b/test/org/hibernate/test/typedmanytoone/Address.java
@@ -0,0 +1,55 @@
+//$Id$
+package org.hibernate.test.typedmanytoone;
+
+import java.io.Serializable;
+
+/**
+ * @author Gavin King
+ */
+public class Address implements Serializable {
+
+ private AddressId addressId;
+ private String street;
+ private String city;
+ private String state;
+ private String zip;
+ private Customer customer;
+
+ public Customer getCustomer() {
+ return customer;
+ }
+ public void setCustomer(Customer customer) {
+ this.customer = customer;
+ }
+
+ public String getCity() {
+ return city;
+ }
+ public void setCity(String city) {
+ this.city = city;
+ }
+ public String getState() {
+ return state;
+ }
+ public void setState(String state) {
+ this.state = state;
+ }
+ public String getStreet() {
+ return street;
+ }
+ public void setStreet(String street) {
+ this.street = street;
+ }
+ public String getZip() {
+ return zip;
+ }
+ public void setZip(String zip) {
+ this.zip = zip;
+ }
+ public AddressId getAddressId() {
+ return addressId;
+ }
+ public void setAddressId(AddressId addressId) {
+ this.addressId = addressId;
+ }
+}
diff --git a/test/org/hibernate/test/typedmanytoone/AddressId.java b/test/org/hibernate/test/typedmanytoone/AddressId.java
new file mode 100755
index 0000000000..e69a6ca061
--- /dev/null
+++ b/test/org/hibernate/test/typedmanytoone/AddressId.java
@@ -0,0 +1,45 @@
+//$Id$
+package org.hibernate.test.typedmanytoone;
+
+import java.io.Serializable;
+
+/**
+ * @author Gavin King
+ */
+public class AddressId implements Serializable {
+ private String type;
+ private String addressId;
+
+ public AddressId(String type, String customerId) {
+ this.addressId = customerId;
+ this.type = type;
+ }
+
+ public AddressId() {}
+
+ public String getType() {
+ return type;
+ }
+ public void setType(String type) {
+ this.type = type;
+ }
+ public String getAddressId() {
+ return addressId;
+ }
+ public void setAddressId(String customerId) {
+ this.addressId = customerId;
+ }
+ public boolean equals(Object other) {
+ if ( !(other instanceof AddressId) ) return false;
+ AddressId add = (AddressId) other;
+ return type.equals(add.type) && addressId.equals(add.addressId);
+ }
+ public int hashCode() {
+ return addressId.hashCode() + type.hashCode();
+ }
+
+ public String toString() {
+ return type + '#' + addressId;
+ }
+
+}
diff --git a/test/org/hibernate/test/typedmanytoone/Customer.hbm.xml b/test/org/hibernate/test/typedmanytoone/Customer.hbm.xml
new file mode 100755
index 0000000000..4bcfa87e42
--- /dev/null
+++ b/test/org/hibernate/test/typedmanytoone/Customer.hbm.xml
@@ -0,0 +1,85 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 'BILLING'
+
+
+
+
+ 'SHIPPING'
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/test/org/hibernate/test/typedmanytoone/Customer.java b/test/org/hibernate/test/typedmanytoone/Customer.java
new file mode 100755
index 0000000000..ef16c12f4b
--- /dev/null
+++ b/test/org/hibernate/test/typedmanytoone/Customer.java
@@ -0,0 +1,40 @@
+//$Id$
+package org.hibernate.test.typedmanytoone;
+
+import java.io.Serializable;
+
+/**
+ * @author Gavin King
+ */
+public class Customer implements Serializable {
+
+ private String name;
+ private String customerId;
+ private Address billingAddress;
+ private Address shippingAddress;
+
+ public Address getBillingAddress() {
+ return billingAddress;
+ }
+ public void setBillingAddress(Address billingAddress) {
+ this.billingAddress = billingAddress;
+ }
+ public String getCustomerId() {
+ return customerId;
+ }
+ public void setCustomerId(String customerId) {
+ this.customerId = customerId;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+ public Address getShippingAddress() {
+ return shippingAddress;
+ }
+ public void setShippingAddress(Address shippingAddress) {
+ this.shippingAddress = shippingAddress;
+ }
+}
diff --git a/test/org/hibernate/test/typedmanytoone/TypedManyToOneTest.java b/test/org/hibernate/test/typedmanytoone/TypedManyToOneTest.java
new file mode 100755
index 0000000000..97d11a5219
--- /dev/null
+++ b/test/org/hibernate/test/typedmanytoone/TypedManyToOneTest.java
@@ -0,0 +1,113 @@
+//$Id$
+package org.hibernate.test.typedmanytoone;
+
+import java.util.List;
+
+import junit.framework.Test;
+
+import org.hibernate.Hibernate;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * @author Gavin King
+ */
+public class TypedManyToOneTest extends FunctionalTestCase {
+
+ public TypedManyToOneTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "typedmanytoone/Customer.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( TypedManyToOneTest.class );
+ }
+
+ public void testCreateQuery() {
+ Customer cust = new Customer();
+ cust.setCustomerId("abc123");
+ cust.setName("Matt");
+
+ Address ship = new Address();
+ ship.setStreet("peachtree rd");
+ ship.setState("GA");
+ ship.setCity("ATL");
+ ship.setZip("30326");
+ ship.setAddressId( new AddressId("SHIPPING", "xyz123") );
+ ship.setCustomer(cust);
+
+ Address bill = new Address();
+ bill.setStreet("peachtree rd");
+ bill.setState("GA");
+ bill.setCity("ATL");
+ bill.setZip("30326");
+ bill.setAddressId( new AddressId("BILLING", "xyz123") );
+ bill.setCustomer(cust);
+
+ cust.setBillingAddress(bill);
+ cust.setShippingAddress(ship);
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.persist(cust);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ List results = s.createQuery("from Customer cust left join fetch cust.billingAddress where cust.customerId='abc123'").list();
+ //List results = s.createQuery("from Customer cust left join fetch cust.billingAddress left join fetch cust.shippingAddress").list();
+ cust = (Customer) results.get(0);
+ assertFalse( Hibernate.isInitialized( cust.getShippingAddress() ) );
+ assertTrue( Hibernate.isInitialized( cust.getBillingAddress() ) );
+ assertEquals( "30326", cust.getBillingAddress().getZip() );
+ assertEquals( "30326", cust.getShippingAddress().getZip() );
+ assertEquals( "BILLING", cust.getBillingAddress().getAddressId().getType() );
+ assertEquals( "SHIPPING", cust.getShippingAddress().getAddressId().getType() );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.saveOrUpdate(cust);
+ ship = cust.getShippingAddress();
+ cust.setShippingAddress(null);
+ s.delete("ShippingAddress", ship);
+ s.flush();
+ assertNull( s.get( "ShippingAddress", ship.getAddressId() ) );
+ s.delete( cust );
+ t.commit();
+ s.close();
+ }
+
+ public void testCreateQueryNull() {
+ Customer cust = new Customer();
+ cust.setCustomerId("xyz123");
+ cust.setName("Matt");
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.persist(cust);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ List results = s.createQuery("from Customer cust left join fetch cust.billingAddress where cust.customerId='xyz123'").list();
+ //List results = s.createQuery("from Customer cust left join fetch cust.billingAddress left join fetch cust.shippingAddress").list();
+ cust = (Customer) results.get(0);
+ assertNull( cust.getShippingAddress() );
+ assertNull( cust.getBillingAddress() );
+ s.delete( cust );
+ t.commit();
+ s.close();
+
+ }
+
+}
+
diff --git a/test/org/hibernate/test/typedonetoone/Address.java b/test/org/hibernate/test/typedonetoone/Address.java
new file mode 100755
index 0000000000..2d6523359d
--- /dev/null
+++ b/test/org/hibernate/test/typedonetoone/Address.java
@@ -0,0 +1,55 @@
+//$Id$
+package org.hibernate.test.typedonetoone;
+
+import java.io.Serializable;
+
+/**
+ * @author Gavin King
+ */
+public class Address implements Serializable {
+
+ private AddressId addressId;
+ private String street;
+ private String city;
+ private String state;
+ private String zip;
+ private Customer customer;
+
+ public Customer getCustomer() {
+ return customer;
+ }
+ public void setCustomer(Customer customer) {
+ this.customer = customer;
+ }
+
+ public String getCity() {
+ return city;
+ }
+ public void setCity(String city) {
+ this.city = city;
+ }
+ public String getState() {
+ return state;
+ }
+ public void setState(String state) {
+ this.state = state;
+ }
+ public String getStreet() {
+ return street;
+ }
+ public void setStreet(String street) {
+ this.street = street;
+ }
+ public String getZip() {
+ return zip;
+ }
+ public void setZip(String zip) {
+ this.zip = zip;
+ }
+ public AddressId getAddressId() {
+ return addressId;
+ }
+ public void setAddressId(AddressId addressId) {
+ this.addressId = addressId;
+ }
+}
diff --git a/test/org/hibernate/test/typedonetoone/AddressId.java b/test/org/hibernate/test/typedonetoone/AddressId.java
new file mode 100755
index 0000000000..a1add8987b
--- /dev/null
+++ b/test/org/hibernate/test/typedonetoone/AddressId.java
@@ -0,0 +1,41 @@
+//$Id$
+package org.hibernate.test.typedonetoone;
+
+import java.io.Serializable;
+
+/**
+ * @author Gavin King
+ */
+public class AddressId implements Serializable {
+ private String type;
+ private String customerId;
+
+ public AddressId(String type, String customerId) {
+ this.customerId = customerId;
+ this.type = type;
+ }
+
+ public AddressId() {}
+
+ public String getType() {
+ return type;
+ }
+ public void setType(String type) {
+ this.type = type;
+ }
+ public String getCustomerId() {
+ return customerId;
+ }
+ public void setCustomerId(String customerId) {
+ this.customerId = customerId;
+ }
+ public boolean equals(Object other) {
+ if ( !(other instanceof AddressId) ) return false;
+ AddressId add = (AddressId) other;
+ return type.equals(add.type) && customerId.equals(add.customerId);
+ }
+ public int hashCode() {
+ return customerId.hashCode() + type.hashCode();
+ }
+
+}
diff --git a/test/org/hibernate/test/typedonetoone/Customer.hbm.xml b/test/org/hibernate/test/typedonetoone/Customer.hbm.xml
new file mode 100755
index 0000000000..88f616dbb6
--- /dev/null
+++ b/test/org/hibernate/test/typedonetoone/Customer.hbm.xml
@@ -0,0 +1,85 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/test/org/hibernate/test/typedonetoone/Customer.java b/test/org/hibernate/test/typedonetoone/Customer.java
new file mode 100755
index 0000000000..605c38cd37
--- /dev/null
+++ b/test/org/hibernate/test/typedonetoone/Customer.java
@@ -0,0 +1,40 @@
+//$Id$
+package org.hibernate.test.typedonetoone;
+
+import java.io.Serializable;
+
+/**
+ * @author Gavin King
+ */
+public class Customer implements Serializable {
+
+ private String name;
+ private String customerId;
+ private Address billingAddress;
+ private Address shippingAddress;
+
+ public Address getBillingAddress() {
+ return billingAddress;
+ }
+ public void setBillingAddress(Address billingAddress) {
+ this.billingAddress = billingAddress;
+ }
+ public String getCustomerId() {
+ return customerId;
+ }
+ public void setCustomerId(String customerId) {
+ this.customerId = customerId;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+ public Address getShippingAddress() {
+ return shippingAddress;
+ }
+ public void setShippingAddress(Address shippingAddress) {
+ this.shippingAddress = shippingAddress;
+ }
+}
diff --git a/test/org/hibernate/test/typedonetoone/TypedOneToOneTest.java b/test/org/hibernate/test/typedonetoone/TypedOneToOneTest.java
new file mode 100755
index 0000000000..acbe933dec
--- /dev/null
+++ b/test/org/hibernate/test/typedonetoone/TypedOneToOneTest.java
@@ -0,0 +1,103 @@
+//$Id$
+package org.hibernate.test.typedonetoone;
+
+import java.util.List;
+
+import junit.framework.Test;
+
+import org.hibernate.Hibernate;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * @author Gavin King
+ */
+public class TypedOneToOneTest extends FunctionalTestCase {
+
+ public TypedOneToOneTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "typedonetoone/Customer.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( TypedOneToOneTest.class );
+ }
+
+ public void testCreateQuery() {
+ Customer cust = new Customer();
+ cust.setCustomerId("abc123");
+ cust.setName("Matt");
+
+ Address ship = new Address();
+ ship.setStreet("peachtree rd");
+ ship.setState("GA");
+ ship.setCity("ATL");
+ ship.setZip("30326");
+ ship.setAddressId( new AddressId("SHIPPING", "abc123") );
+ ship.setCustomer(cust);
+
+ Address bill = new Address();
+ bill.setStreet("peachtree rd");
+ bill.setState("GA");
+ bill.setCity("ATL");
+ bill.setZip("30326");
+ bill.setAddressId( new AddressId("BILLING", "abc123") );
+ bill.setCustomer(cust);
+
+ cust.setBillingAddress(bill);
+ cust.setShippingAddress(ship);
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.persist(cust);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ List results = s.createQuery("from Customer cust left join fetch cust.billingAddress where cust.customerId='abc123'").list();
+ //List results = s.createQuery("from Customer cust left join fetch cust.billingAddress left join fetch cust.shippingAddress").list();
+ cust = (Customer) results.get(0);
+ assertTrue( Hibernate.isInitialized( cust.getShippingAddress() ) );
+ assertTrue( Hibernate.isInitialized( cust.getBillingAddress() ) );
+ assertEquals( "30326", cust.getBillingAddress().getZip() );
+ assertEquals( "30326", cust.getShippingAddress().getZip() );
+ assertEquals( "BILLING", cust.getBillingAddress().getAddressId().getType() );
+ assertEquals( "SHIPPING", cust.getShippingAddress().getAddressId().getType() );
+ s.delete( cust );
+ t.commit();
+ s.close();
+
+ }
+
+ public void testCreateQueryNull() {
+ Customer cust = new Customer();
+ cust.setCustomerId("xyz123");
+ cust.setName("Matt");
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.persist(cust);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ List results = s.createQuery("from Customer cust left join fetch cust.billingAddress where cust.customerId='xyz123'").list();
+ //List results = s.createQuery("from Customer cust left join fetch cust.billingAddress left join fetch cust.shippingAddress").list();
+ cust = (Customer) results.get(0);
+ assertNull( cust.getShippingAddress() );
+ assertNull( cust.getBillingAddress() );
+ s.delete(cust);
+ t.commit();
+ s.close();
+
+ }
+
+}
+
diff --git a/test/org/hibernate/test/typeparameters/DefaultValueIntegerType.java b/test/org/hibernate/test/typeparameters/DefaultValueIntegerType.java
new file mode 100644
index 0000000000..69616ce65f
--- /dev/null
+++ b/test/org/hibernate/test/typeparameters/DefaultValueIntegerType.java
@@ -0,0 +1,82 @@
+package org.hibernate.test.typeparameters;
+
+import java.io.Serializable;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.util.Properties;
+
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.HibernateException;
+import org.hibernate.usertype.ParameterizedType;
+import org.hibernate.usertype.UserType;
+
+
+/**
+ * @author Michi
+ */
+public class DefaultValueIntegerType implements UserType, ParameterizedType, Serializable {
+
+ private Integer defaultValue;
+
+ public int[] sqlTypes() {
+ return new int[] {Types.INTEGER};
+ }
+
+ public Class returnedClass() {
+ return int.class;
+ }
+
+ public boolean equals(Object x, Object y) throws HibernateException {
+ if (x==y) return true;
+ if (x==null || y==null) return false;
+ return x.equals(y);
+ }
+
+ public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
+ Number result = (Number) rs.getObject(names[0]);
+ return result==null ? defaultValue : new Integer(result.intValue());
+ }
+
+ public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
+ if (value == null || defaultValue.equals(value) ) {
+ LogFactory.getLog( getClass() ).trace("binding null to parameter: " + index);
+ st.setNull(index, Types.INTEGER);
+ } else {
+ LogFactory.getLog( getClass() ).trace("binding " + value + " to parameter: " + index);
+ st.setInt(index, ((Integer)value).intValue());
+ }
+ }
+
+ public Object deepCopy(Object value) throws HibernateException {
+ return new Integer(((Integer)value).intValue());
+ }
+
+ public boolean isMutable() {
+ return false;
+ }
+
+ public int hashCode(Object x) throws HibernateException {
+ return x.hashCode();
+ }
+
+ public Object assemble(Serializable cached, Object owner)
+ throws HibernateException {
+ return cached;
+ }
+
+ public Serializable disassemble(Object value) throws HibernateException {
+ return (Serializable) value;
+ }
+
+ public Object replace(Object original, Object target, Object owner)
+ throws HibernateException {
+ return original;
+ }
+
+ public void setParameterValues(Properties parameters) {
+ this.defaultValue = Integer.valueOf((String) parameters.get("default"));
+ }
+
+}
diff --git a/test/org/hibernate/test/typeparameters/TypeParameterTest.java b/test/org/hibernate/test/typeparameters/TypeParameterTest.java
new file mode 100644
index 0000000000..2e39956e0f
--- /dev/null
+++ b/test/org/hibernate/test/typeparameters/TypeParameterTest.java
@@ -0,0 +1,122 @@
+//$Id$
+package org.hibernate.test.typeparameters;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+
+import junit.framework.Test;
+
+import org.hibernate.Transaction;
+import org.hibernate.classic.Session;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * Test for parameterizable types.
+ *
+ * @author Michael Gloegl
+ */
+public class TypeParameterTest extends FunctionalTestCase {
+
+ public TypeParameterTest(String name) {
+ super(name);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "typeparameters/Typedef.hbm.xml", "typeparameters/Widget.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( TypeParameterTest.class );
+ }
+
+ public void testSave() throws Exception {
+ deleteData();
+
+ Session s = openSession();
+
+ Transaction t = s.beginTransaction();
+
+ Widget obj = new Widget();
+ obj.setValueThree(5);
+
+ Integer id = (Integer) s.save(obj);
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+
+ Connection connection = s.connection();
+ PreparedStatement statement = connection.prepareStatement("SELECT * FROM STRANGE_TYPED_OBJECT WHERE ID=?");
+ statement.setInt(1, id.intValue());
+ ResultSet resultSet = statement.executeQuery();
+
+ assertTrue("A row should have been returned", resultSet.next());
+ assertTrue("Default value should have been mapped to null", resultSet.getObject("VALUE_ONE") == null);
+ assertTrue("Default value should have been mapped to null", resultSet.getObject("VALUE_TWO") == null);
+ assertEquals("Non-Default value should not be changed", resultSet.getInt("VALUE_THREE"), 5);
+ assertTrue("Default value should have been mapped to null", resultSet.getObject("VALUE_FOUR") == null);
+
+ deleteData();
+ t.commit();
+ s.close();
+ }
+
+ public void testLoading() throws Exception {
+ initData();
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Widget obj = (Widget) s.createQuery("from Widget o where o.string = :string").setString("string", "all-normal").uniqueResult();
+ assertEquals("Non-Default value incorrectly loaded", obj.getValueOne(), 7);
+ assertEquals("Non-Default value incorrectly loaded", obj.getValueTwo(), 8);
+ assertEquals("Non-Default value incorrectly loaded", obj.getValueThree(), 9);
+ assertEquals("Non-Default value incorrectly loaded", obj.getValueFour(), 10);
+
+ obj = (Widget) s.createQuery("from Widget o where o.string = :string").setString("string", "all-default").uniqueResult();
+ assertEquals("Default value incorrectly loaded", obj.getValueOne(), 1);
+ assertEquals("Default value incorrectly loaded", obj.getValueTwo(), 2);
+ assertEquals("Default value incorrectly loaded", obj.getValueThree(), -1);
+ assertEquals("Default value incorrectly loaded", obj.getValueFour(), -5);
+
+ deleteData();
+ t.commit();
+ s.close();
+ }
+
+ private void initData() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Widget obj = new Widget();
+ obj.setValueOne(7);
+ obj.setValueTwo(8);
+ obj.setValueThree(9);
+ obj.setValueFour(10);
+ obj.setString("all-normal");
+ s.save(obj);
+
+ obj = new Widget();
+ obj.setValueOne(1);
+ obj.setValueTwo(2);
+ obj.setValueThree(-1);
+ obj.setValueFour(-5);
+ obj.setString("all-default");
+ s.save(obj);
+
+ t.commit();
+ s.close();
+ }
+
+ private void deleteData() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ s.delete("from Widget");
+ t.commit();
+ s.close();
+ }
+}
\ No newline at end of file
diff --git a/test/org/hibernate/test/typeparameters/Typedef.hbm.xml b/test/org/hibernate/test/typeparameters/Typedef.hbm.xml
new file mode 100644
index 0000000000..f29813d4fb
--- /dev/null
+++ b/test/org/hibernate/test/typeparameters/Typedef.hbm.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+ -1
+
+
+
\ No newline at end of file
diff --git a/test/org/hibernate/test/typeparameters/Widget.hbm.xml b/test/org/hibernate/test/typeparameters/Widget.hbm.xml
new file mode 100644
index 0000000000..23eb5c7046
--- /dev/null
+++ b/test/org/hibernate/test/typeparameters/Widget.hbm.xml
@@ -0,0 +1,31 @@
+
+
+
+
+
+
+ 2
+
+
+
+
+
+
+
+
+ 1
+
+
+
+
+
+
+ -5
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/test/org/hibernate/test/typeparameters/Widget.java b/test/org/hibernate/test/typeparameters/Widget.java
new file mode 100644
index 0000000000..f9cbd6ed11
--- /dev/null
+++ b/test/org/hibernate/test/typeparameters/Widget.java
@@ -0,0 +1,62 @@
+package org.hibernate.test.typeparameters;
+
+/**
+ * @author Michael Gloegl
+ */
+public class Widget {
+
+ private int valueOne = 1;
+ private int valueTwo = 2;
+ private int valueThree = -1;
+ private int valueFour = -5;
+ private Integer id;
+ private String string;
+
+ public int getValueOne() {
+ return valueOne;
+ }
+
+ public void setValueOne(int valueOne) {
+ this.valueOne = valueOne;
+ }
+
+ public int getValueThree() {
+ return valueThree;
+ }
+
+ public void setValueThree(int valueThree) {
+ this.valueThree = valueThree;
+ }
+
+ public int getValueTwo() {
+ return valueTwo;
+ }
+
+ public void setValueTwo(int valueTwo) {
+ this.valueTwo = valueTwo;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getString() {
+ return string;
+ }
+
+ public void setString(String string) {
+ this.string = string;
+ }
+
+ public int getValueFour() {
+ return valueFour;
+ }
+
+ public void setValueFour(int valueFour) {
+ this.valueFour = valueFour;
+ }
+}
diff --git a/test/org/hibernate/test/unconstrained/Employee.java b/test/org/hibernate/test/unconstrained/Employee.java
new file mode 100755
index 0000000000..807b4ab527
--- /dev/null
+++ b/test/org/hibernate/test/unconstrained/Employee.java
@@ -0,0 +1,28 @@
+//$Id$
+package org.hibernate.test.unconstrained;
+
+/**
+ * @author Gavin King
+ */
+public class Employee {
+
+ private String id;
+
+ public Employee() {
+ }
+
+ public Employee(String id) {
+ this.id = id;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+
+}
diff --git a/test/org/hibernate/test/unconstrained/Person.hbm.xml b/test/org/hibernate/test/unconstrained/Person.hbm.xml
new file mode 100755
index 0000000000..63a426026b
--- /dev/null
+++ b/test/org/hibernate/test/unconstrained/Person.hbm.xml
@@ -0,0 +1,31 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/org/hibernate/test/unconstrained/Person.java b/test/org/hibernate/test/unconstrained/Person.java
new file mode 100755
index 0000000000..822f610478
--- /dev/null
+++ b/test/org/hibernate/test/unconstrained/Person.java
@@ -0,0 +1,43 @@
+//$Id$
+package org.hibernate.test.unconstrained;
+
+/**
+ * @author Gavin King
+ */
+public class Person {
+
+ private String name;
+ private String employeeId;
+ private Employee employee;
+
+ public Person() {}
+ public Person(String name) {
+ this.name = name;
+ }
+
+ public Employee getEmployee() {
+ return employee;
+ }
+
+ public void setEmployee(Employee employee) {
+ this.employee = employee;
+ }
+
+ public String getEmployeeId() {
+ return employeeId;
+ }
+
+ public void setEmployeeId(String employeeId) {
+ this.employeeId = employeeId;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+
+}
diff --git a/test/org/hibernate/test/unconstrained/UnconstrainedTest.java b/test/org/hibernate/test/unconstrained/UnconstrainedTest.java
new file mode 100755
index 0000000000..51362442ef
--- /dev/null
+++ b/test/org/hibernate/test/unconstrained/UnconstrainedTest.java
@@ -0,0 +1,127 @@
+//$Id$
+package org.hibernate.test.unconstrained;
+
+import junit.framework.Test;
+
+import org.hibernate.FetchMode;
+import org.hibernate.Hibernate;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.criterion.Restrictions;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * @author Gavin King
+ */
+public class UnconstrainedTest extends FunctionalTestCase {
+
+ public UnconstrainedTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "unconstrained/Person.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( UnconstrainedTest.class );
+ }
+
+ public void testUnconstrainedNoCache() {
+ Session session = openSession();
+ Transaction tx = session.beginTransaction();
+ Person p = new Person("gavin");
+ p.setEmployeeId("123456");
+ session.persist(p);
+ tx.commit();
+ session.close();
+
+ getSessions().evict(Person.class);
+
+ session = openSession();
+ tx = session.beginTransaction();
+ p = (Person) session.get(Person.class, "gavin");
+ assertNull( p.getEmployee() );
+ p.setEmployee( new Employee("123456") );
+ tx.commit();
+ session.close();
+
+ getSessions().evict(Person.class);
+
+ session = openSession();
+ tx = session.beginTransaction();
+ p = (Person) session.get(Person.class, "gavin");
+ assertTrue( Hibernate.isInitialized( p.getEmployee() ) );
+ assertNotNull( p.getEmployee() );
+ session.delete(p);
+ tx.commit();
+ session.close();
+ }
+
+ public void testUnconstrainedOuterJoinFetch() {
+ Session session = openSession();
+ Transaction tx = session.beginTransaction();
+ Person p = new Person("gavin");
+ p.setEmployeeId("123456");
+ session.persist(p);
+ tx.commit();
+ session.close();
+
+ getSessions().evict(Person.class);
+
+ session = openSession();
+ tx = session.beginTransaction();
+ p = (Person) session.createCriteria(Person.class)
+ .setFetchMode("employee", FetchMode.JOIN)
+ .add( Restrictions.idEq("gavin") )
+ .uniqueResult();
+ assertNull( p.getEmployee() );
+ p.setEmployee( new Employee("123456") );
+ tx.commit();
+ session.close();
+
+ getSessions().evict(Person.class);
+
+ session = openSession();
+ tx = session.beginTransaction();
+ p = (Person) session.createCriteria(Person.class)
+ .setFetchMode("employee", FetchMode.JOIN)
+ .add( Restrictions.idEq("gavin") )
+ .uniqueResult();
+ assertTrue( Hibernate.isInitialized( p.getEmployee() ) );
+ assertNotNull( p.getEmployee() );
+ session.delete(p);
+ tx.commit();
+ session.close();
+ }
+
+ public void testUnconstrained() {
+ Session session = openSession();
+ Transaction tx = session.beginTransaction();
+ Person p = new Person("gavin");
+ p.setEmployeeId("123456");
+ session.persist(p);
+ tx.commit();
+ session.close();
+
+ session = openSession();
+ tx = session.beginTransaction();
+ p = (Person) session.get(Person.class, "gavin");
+ assertNull( p.getEmployee() );
+ p.setEmployee( new Employee("123456") );
+ tx.commit();
+ session.close();
+
+ session = openSession();
+ tx = session.beginTransaction();
+ p = (Person) session.get(Person.class, "gavin");
+ assertTrue( Hibernate.isInitialized( p.getEmployee() ) );
+ assertNotNull( p.getEmployee() );
+ session.delete(p);
+ tx.commit();
+ session.close();
+ }
+
+}
+
diff --git a/test/org/hibernate/test/unidir/BackrefTest.java b/test/org/hibernate/test/unidir/BackrefTest.java
new file mode 100755
index 0000000000..d647b769f4
--- /dev/null
+++ b/test/org/hibernate/test/unidir/BackrefTest.java
@@ -0,0 +1,88 @@
+//$Id$
+package org.hibernate.test.unidir;
+
+import junit.framework.Test;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * @author Gavin King
+ */
+public class BackrefTest extends FunctionalTestCase {
+
+ public BackrefTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "unidir/ParentChild.hbm.xml" };
+ }
+
+ public String getCacheConcurrencyStrategy() {
+ return null;
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( BackrefTest.class );
+ }
+
+ public void testBackRef() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Parent p = new Parent("Marc");
+ Parent p2 = new Parent("Nathalie");
+ Child c = new Child("Elvira");
+ Child c2 = new Child("Blase");
+ p.getChildren().add(c);
+ p.getChildren().add(c2);
+ s.persist(p);
+ s.persist(p2);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ c = (Child) s.get(Child.class, "Elvira");
+ c.setAge(2);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ p = (Parent) s.get(Parent.class, "Marc");
+ c = (Child) s.get(Child.class, "Elvira");
+ c.setAge(18);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ p = (Parent) s.get(Parent.class, "Marc");
+ p2 = (Parent) s.get(Parent.class, "Nathalie");
+ c = (Child) s.get(Child.class, "Elvira");
+ assertEquals( p.getChildren().indexOf(c), 0 );
+ p.getChildren().remove(c);
+ p2.getChildren().add(c);
+ t.commit();
+
+ s.close();
+ s = openSession();
+ t = s.beginTransaction();
+ Parent p3 = new Parent("Marion");
+ p3.getChildren().add( new Child("Gavin") );
+ s.merge(p3);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery( "delete from Child" ).executeUpdate();
+ s.createQuery( "delete from Parent" ).executeUpdate();
+ t.commit();
+ s.close();
+ }
+}
+
diff --git a/test/org/hibernate/test/unidir/Child.java b/test/org/hibernate/test/unidir/Child.java
new file mode 100755
index 0000000000..5ec30fb069
--- /dev/null
+++ b/test/org/hibernate/test/unidir/Child.java
@@ -0,0 +1,27 @@
+//$Id$
+package org.hibernate.test.unidir;
+
+
+/**
+ * @author Gavin King
+ */
+public class Child {
+ private String name;
+ private int age;
+ Child() {}
+ public Child(String name) {
+ this.name = name;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+ public int getAge() {
+ return age;
+ }
+ public void setAge(int age) {
+ this.age = age;
+ }
+}
diff --git a/test/org/hibernate/test/unidir/Parent.java b/test/org/hibernate/test/unidir/Parent.java
new file mode 100755
index 0000000000..5a16a74022
--- /dev/null
+++ b/test/org/hibernate/test/unidir/Parent.java
@@ -0,0 +1,29 @@
+//$Id$
+package org.hibernate.test.unidir;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Gavin King
+ */
+public class Parent {
+ private String name;
+ private List children = new ArrayList();
+ Parent() {}
+ public Parent(String name) {
+ this.name = name;
+ }
+ public List getChildren() {
+ return children;
+ }
+ public void setChildren(List children) {
+ this.children = children;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/test/org/hibernate/test/unidir/ParentChild.hbm.xml b/test/org/hibernate/test/unidir/ParentChild.hbm.xml
new file mode 100755
index 0000000000..edbc4af14b
--- /dev/null
+++ b/test/org/hibernate/test/unidir/ParentChild.hbm.xml
@@ -0,0 +1,23 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/org/hibernate/test/unionsubclass/Alien.java b/test/org/hibernate/test/unionsubclass/Alien.java
new file mode 100755
index 0000000000..392294c5a6
--- /dev/null
+++ b/test/org/hibernate/test/unionsubclass/Alien.java
@@ -0,0 +1,38 @@
+//$Id$
+package org.hibernate.test.unionsubclass;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Gavin King
+ */
+public class Alien extends Being {
+ private String species;
+ private Hive hive;
+ private List hivemates = new ArrayList();
+ /**
+ * @return Returns the species.
+ */
+ public String getSpecies() {
+ return species;
+ }
+ /**
+ * @param species The species to set.
+ */
+ public void setSpecies(String species) {
+ this.species = species;
+ }
+ public Hive getHive() {
+ return hive;
+ }
+ public void setHive(Hive hive) {
+ this.hive = hive;
+ }
+ public List getHivemates() {
+ return hivemates;
+ }
+ public void setHivemates(List hivemates) {
+ this.hivemates = hivemates;
+ }
+}
diff --git a/test/org/hibernate/test/unionsubclass/Being.java b/test/org/hibernate/test/unionsubclass/Being.java
new file mode 100755
index 0000000000..fa98d3b9ac
--- /dev/null
+++ b/test/org/hibernate/test/unionsubclass/Being.java
@@ -0,0 +1,72 @@
+//$Id$
+package org.hibernate.test.unionsubclass;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @author Gavin King
+ */
+public abstract class Being {
+ private long id;
+ private String identity;
+ private Location location;
+ private List things = new ArrayList();
+ private Map info = new HashMap();
+ /**
+ * @return Returns the id.
+ */
+ public long getId() {
+ return id;
+ }
+ /**
+ * @param id The id to set.
+ */
+ public void setId(long id) {
+ this.id = id;
+ }
+ /**
+ * @return Returns the identity.
+ */
+ public String getIdentity() {
+ return identity;
+ }
+ /**
+ * @param identity The identity to set.
+ */
+ public void setIdentity(String identity) {
+ this.identity = identity;
+ }
+ /**
+ * @return Returns the location.
+ */
+ public Location getLocation() {
+ return location;
+ }
+ /**
+ * @param location The location to set.
+ */
+ public void setLocation(Location location) {
+ this.location = location;
+ }
+ public String getSpecies() {
+ return null;
+ }
+
+ public List getThings() {
+ return things;
+ }
+ public void setThings(List things) {
+ this.things = things;
+ }
+ public Map getInfo() {
+ return info;
+ }
+
+ public void setInfo(Map info) {
+ this.info = info;
+ }
+
+}
diff --git a/test/org/hibernate/test/unionsubclass/Beings.hbm.xml b/test/org/hibernate/test/unionsubclass/Beings.hbm.xml
new file mode 100755
index 0000000000..987272006d
--- /dev/null
+++ b/test/org/hibernate/test/unionsubclass/Beings.hbm.xml
@@ -0,0 +1,113 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/org/hibernate/test/unionsubclass/Employee.java b/test/org/hibernate/test/unionsubclass/Employee.java
new file mode 100644
index 0000000000..e7bb618479
--- /dev/null
+++ b/test/org/hibernate/test/unionsubclass/Employee.java
@@ -0,0 +1,17 @@
+//$Id$
+package org.hibernate.test.unionsubclass;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class Employee extends Human {
+ private Double salary;
+
+ public Double getSalary() {
+ return salary;
+ }
+
+ public void setSalary(Double salary) {
+ this.salary = salary;
+ }
+}
diff --git a/test/org/hibernate/test/unionsubclass/Hive.java b/test/org/hibernate/test/unionsubclass/Hive.java
new file mode 100755
index 0000000000..d32de51566
--- /dev/null
+++ b/test/org/hibernate/test/unionsubclass/Hive.java
@@ -0,0 +1,32 @@
+//$Id$
+package org.hibernate.test.unionsubclass;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Gavin King
+ */
+public class Hive {
+ private long id;
+ private Location location;
+ private List members = new ArrayList();
+ public List getMembers() {
+ return members;
+ }
+ public void setMembers(List hives) {
+ this.members = hives;
+ }
+ public long getId() {
+ return id;
+ }
+ public void setId(long id) {
+ this.id = id;
+ }
+ public Location getLocation() {
+ return location;
+ }
+ public void setLocation(Location location) {
+ this.location = location;
+ }
+}
diff --git a/test/org/hibernate/test/unionsubclass/Human.java b/test/org/hibernate/test/unionsubclass/Human.java
new file mode 100755
index 0000000000..4a9aa95232
--- /dev/null
+++ b/test/org/hibernate/test/unionsubclass/Human.java
@@ -0,0 +1,26 @@
+//$Id$
+package org.hibernate.test.unionsubclass;
+
+/**
+ * @author Gavin King
+ */
+public class Human extends Being {
+ private char sex;
+
+ /**
+ * @return Returns the sex.
+ */
+ public char getSex() {
+ return sex;
+ }
+ /**
+ * @param sex The sex to set.
+ */
+ public void setSex(char sex) {
+ this.sex = sex;
+ }
+ public String getSpecies() {
+ return "human";
+ }
+
+}
diff --git a/test/org/hibernate/test/unionsubclass/Location.java b/test/org/hibernate/test/unionsubclass/Location.java
new file mode 100755
index 0000000000..2337a2cd3c
--- /dev/null
+++ b/test/org/hibernate/test/unionsubclass/Location.java
@@ -0,0 +1,61 @@
+//$Id$
+package org.hibernate.test.unionsubclass;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+/**
+ * @author Gavin King
+ */
+public class Location {
+ private long id;
+ private String name;
+ private Collection beings = new ArrayList();
+
+ Location() {}
+
+ public Location(String name) {
+ this.name = name;
+ }
+
+ public void addBeing(Being b) {
+ b.setLocation(this);
+ beings.add(b);
+ }
+ /**
+ * @return Returns the id.
+ */
+ public long getId() {
+ return id;
+ }
+ /**
+ * @param id The id to set.
+ */
+ public void setId(long id) {
+ this.id = id;
+ }
+ /**
+ * @return Returns the name.
+ */
+ public String getName() {
+ return name;
+ }
+ /**
+ * @param name The name to set.
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+ /**
+ * @return Returns the beings.
+ */
+ public Collection getBeings() {
+ return beings;
+ }
+ /**
+ * @param beings The beings to set.
+ */
+ public void setBeings(Collection beings) {
+ this.beings = beings;
+ }
+}
diff --git a/test/org/hibernate/test/unionsubclass/Thing.java b/test/org/hibernate/test/unionsubclass/Thing.java
new file mode 100755
index 0000000000..69c80d83e7
--- /dev/null
+++ b/test/org/hibernate/test/unionsubclass/Thing.java
@@ -0,0 +1,47 @@
+//$Id$
+package org.hibernate.test.unionsubclass;
+
+/**
+ * @author Gavin King
+ */
+public class Thing {
+ private long id;
+ private String description;
+ private Being owner;
+ /**
+ * @return Returns the description.
+ */
+ public String getDescription() {
+ return description;
+ }
+ /**
+ * @param description The description to set.
+ */
+ public void setDescription(String description) {
+ this.description = description;
+ }
+ /**
+ * @return Returns the id.
+ */
+ public long getId() {
+ return id;
+ }
+ /**
+ * @param id The id to set.
+ */
+ public void setId(long id) {
+ this.id = id;
+ }
+ /**
+ * @return Returns the owner.
+ */
+ public Being getOwner() {
+ return owner;
+ }
+ /**
+ * @param owner The owner to set.
+ */
+ public void setOwner(Being owner) {
+ this.owner = owner;
+ }
+}
diff --git a/test/org/hibernate/test/unionsubclass/UnionSubclassTest.java b/test/org/hibernate/test/unionsubclass/UnionSubclassTest.java
new file mode 100755
index 0000000000..ef7cab7317
--- /dev/null
+++ b/test/org/hibernate/test/unionsubclass/UnionSubclassTest.java
@@ -0,0 +1,401 @@
+//$Id$
+package org.hibernate.test.unionsubclass;
+
+import java.util.Iterator;
+import java.util.List;
+
+import junit.framework.Test;
+
+import org.hibernate.FetchMode;
+import org.hibernate.Hibernate;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.criterion.Order;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * @author Gavin King
+ */
+public class UnionSubclassTest extends FunctionalTestCase {
+
+ public UnionSubclassTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "unionsubclass/Beings.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( UnionSubclassTest.class );
+ }
+
+ public void testUnionSubclassCollection() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Location mel = new Location("Earth");
+ s.save(mel);
+
+ Human gavin = new Human();
+ gavin.setIdentity("gavin");
+ gavin.setSex('M');
+ gavin.setLocation(mel);
+ mel.addBeing(gavin);
+
+ gavin.getInfo().put("foo", "bar");
+ gavin.getInfo().put("x", "y");
+
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ gavin = (Human) s.createCriteria(Human.class).uniqueResult();
+ assertEquals( gavin.getInfo().size(), 2 );
+ s.delete(gavin);
+ s.delete( gavin.getLocation() );
+ t.commit();
+ s.close();
+ }
+
+ public void testUnionSubclassFetchMode() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Location mel = new Location("Earth");
+ s.save(mel);
+
+ Human gavin = new Human();
+ gavin.setIdentity("gavin");
+ gavin.setSex('M');
+ gavin.setLocation(mel);
+ mel.addBeing(gavin);
+ Human max = new Human();
+ max.setIdentity("max");
+ max.setSex('M');
+ max.setLocation(mel);
+ mel.addBeing(gavin);
+
+ s.flush();
+ s.clear();
+
+ List list = s.createCriteria(Human.class)
+ .setFetchMode("location", FetchMode.JOIN)
+ .setFetchMode("location.beings", FetchMode.JOIN)
+ .list();
+
+ for (int i=0; i
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/org/hibernate/test/unionsubclass2/Person.java b/test/org/hibernate/test/unionsubclass2/Person.java
new file mode 100755
index 0000000000..91b5888833
--- /dev/null
+++ b/test/org/hibernate/test/unionsubclass2/Person.java
@@ -0,0 +1,70 @@
+//$Id$
+package org.hibernate.test.unionsubclass2;
+
+
+/**
+ * @author Gavin King
+ */
+public class Person {
+ private long id;
+ private String name;
+ private char sex;
+ private Address address = new Address();
+ /**
+ * @return Returns the address.
+ */
+ public Address getAddress() {
+ return address;
+ }
+
+ public void setAddress(String string) {
+ this.address.address = string;
+ }
+
+ public void setZip(String string) {
+ this.address.zip = string;
+ }
+
+ public void setCountry(String string) {
+ this.address.country = string;
+ }
+
+
+ /**
+ * @return Returns the sex.
+ */
+ public char getSex() {
+ return sex;
+ }
+ /**
+ * @param sex The sex to set.
+ */
+ public void setSex(char sex) {
+ this.sex = sex;
+ }
+ /**
+ * @return Returns the id.
+ */
+ public long getId() {
+ return id;
+ }
+ /**
+ * @param id The id to set.
+ */
+ public void setId(long id) {
+ this.id = id;
+ }
+ /**
+ * @return Returns the identity.
+ */
+ public String getName() {
+ return name;
+ }
+ /**
+ * @param identity The identity to set.
+ */
+ public void setName(String identity) {
+ this.name = identity;
+ }
+
+}
diff --git a/test/org/hibernate/test/unionsubclass2/UnionSubclassTest.java b/test/org/hibernate/test/unionsubclass2/UnionSubclassTest.java
new file mode 100755
index 0000000000..a0d34bcae0
--- /dev/null
+++ b/test/org/hibernate/test/unionsubclass2/UnionSubclassTest.java
@@ -0,0 +1,153 @@
+//$Id$
+package org.hibernate.test.unionsubclass2;
+
+import java.math.BigDecimal;
+import java.util.Iterator;
+import java.util.List;
+
+import junit.framework.Test;
+
+import org.hibernate.Hibernate;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.criterion.Expression;
+import org.hibernate.criterion.Property;
+import org.hibernate.dialect.HSQLDialect;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * @author Gavin King
+ */
+public class UnionSubclassTest extends FunctionalTestCase {
+
+ public UnionSubclassTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "unionsubclass2/Person.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( UnionSubclassTest.class );
+ }
+
+ public void testUnionSubclass() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ Employee mark = new Employee();
+ mark.setName("Mark");
+ mark.setTitle("internal sales");
+ mark.setSex('M');
+ mark.setAddress("buckhead");
+ mark.setZip("30305");
+ mark.setCountry("USA");
+
+ Customer joe = new Customer();
+ joe.setName("Joe");
+ joe.setAddress("San Francisco");
+ joe.setZip("XXXXX");
+ joe.setCountry("USA");
+ joe.setComments("Very demanding");
+ joe.setSex('M');
+ joe.setSalesperson(mark);
+
+ Person yomomma = new Person();
+ yomomma.setName("mum");
+ yomomma.setSex('F');
+
+ s.save(yomomma);
+ s.save(mark);
+ s.save(joe);
+
+ assertEquals( s.createQuery("from java.io.Serializable").list().size(), 0 );
+
+ assertEquals( s.createQuery("from Person").list().size(), 3 );
+ assertEquals( s.createQuery("from Person p where p.class = Customer").list().size(), 1 );
+ assertEquals( s.createQuery("from Person p where p.class = Person").list().size(), 1 );
+ s.clear();
+
+ List customers = s.createQuery("from Customer c left join fetch c.salesperson").list();
+ for ( Iterator iter = customers.iterator(); iter.hasNext(); ) {
+ Customer c = (Customer) iter.next();
+ assertTrue( Hibernate.isInitialized( c.getSalesperson() ) );
+ assertEquals( c.getSalesperson().getName(), "Mark" );
+ }
+ assertEquals( customers.size(), 1 );
+ s.clear();
+
+ customers = s.createQuery("from Customer").list();
+ for ( Iterator iter = customers.iterator(); iter.hasNext(); ) {
+ Customer c = (Customer) iter.next();
+ assertFalse( Hibernate.isInitialized( c.getSalesperson() ) );
+ assertEquals( c.getSalesperson().getName(), "Mark" );
+ }
+ assertEquals( customers.size(), 1 );
+ s.clear();
+
+
+ mark = (Employee) s.get( Employee.class, new Long( mark.getId() ) );
+ joe = (Customer) s.get( Customer.class, new Long( joe.getId() ) );
+
+ mark.setZip("30306");
+ assertEquals( s.createQuery("from Person p where p.address.zip = '30306'").list().size(), 1 );
+
+ if ( supportsRowValueConstructorSyntaxInInList() ) {
+ s.createCriteria(Person.class).add(
+ Expression.in("address", new Address[] { mark.getAddress(), joe.getAddress() } )
+ ).list();
+ }
+
+ s.delete(mark);
+ s.delete(joe);
+ s.delete(yomomma);
+ assertTrue( s.createQuery("from Person").list().isEmpty() );
+ t.commit();
+ s.close();
+ }
+
+ public void testQuerySubclassAttribute() {
+ if ( getDialect() instanceof HSQLDialect ) {
+ return; // TODO : why??
+ }
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Person p = new Person();
+ p.setName("Emmanuel");
+ p.setSex('M');
+ s.persist(p);
+ Employee q = new Employee();
+ q.setName("Steve");
+ q.setSex('M');
+ q.setTitle("Mr");
+ q.setSalary( new BigDecimal(1000) );
+ s.persist(q);
+
+ List result = s.createQuery("from Person where salary > 100").list();
+ assertEquals( result.size(), 1 );
+ assertSame( result.get(0), q );
+
+ result = s.createQuery("from Person where salary > 100 or name like 'E%'").list();
+ assertEquals( result.size(), 2 );
+
+ result = s.createCriteria(Person.class)
+ .add( Property.forName("salary").gt( new BigDecimal(100) ) )
+ .list();
+ assertEquals( result.size(), 1 );
+ assertSame( result.get(0), q );
+
+ result = s.createQuery("select salary from Person where salary > 100").list();
+ assertEquals( result.size(), 1 );
+ assertEquals( ( (BigDecimal) result.get(0) ).intValue(), 1000 );
+
+ s.delete(p);
+ s.delete(q);
+ t.commit();
+ s.close();
+ }
+
+}
+
diff --git a/test/org/hibernate/test/usercollection/UserCollectionTypeSuite.java b/test/org/hibernate/test/usercollection/UserCollectionTypeSuite.java
new file mode 100644
index 0000000000..e5458a5ee2
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/UserCollectionTypeSuite.java
@@ -0,0 +1,21 @@
+package org.hibernate.test.usercollection;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.hibernate.test.usercollection.basic.UserCollectionTypeTest;
+import org.hibernate.test.usercollection.parameterized.ParameterizedUserCollectionTypeTest;
+
+/**
+ * Suite for testing various aspects of user collection types.
+ *
+ * @author Steve Ebersole
+ */
+public class UserCollectionTypeSuite {
+ public static Test suite() {
+ TestSuite suite = new TestSuite( "user collection type tests" );
+ suite.addTest( UserCollectionTypeTest.suite() );
+ suite.addTest( ParameterizedUserCollectionTypeTest.suite() );
+ return suite;
+ }
+}
diff --git a/test/org/hibernate/test/usercollection/basic/Email.java b/test/org/hibernate/test/usercollection/basic/Email.java
new file mode 100644
index 0000000000..c50f901368
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/basic/Email.java
@@ -0,0 +1,39 @@
+//$Id$
+package org.hibernate.test.usercollection.basic;
+
+/**
+ * @author Gavin King
+ */
+public class Email {
+
+ private Long id;
+ private String address;
+
+ Email() {}
+
+ public String getAddress() {
+ return address;
+ }
+ public void setAddress(String type) {
+ this.address = type;
+ }
+ public Email(String type) {
+ this.address = type;
+ }
+ public boolean equals(Object that) {
+ if ( !(that instanceof Email) ) return false;
+ Email p = (Email) that;
+ return this.address.equals(p.address);
+ }
+ public int hashCode() {
+ return address.hashCode();
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ private void setId(Long id) {
+ this.id = id;
+ }
+}
diff --git a/test/org/hibernate/test/usercollection/basic/IMyList.java b/test/org/hibernate/test/usercollection/basic/IMyList.java
new file mode 100644
index 0000000000..1b2f443e80
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/basic/IMyList.java
@@ -0,0 +1,7 @@
+package org.hibernate.test.usercollection.basic;
+
+import java.util.List;
+
+public interface IMyList extends List {
+
+}
diff --git a/test/org/hibernate/test/usercollection/basic/MyList.java b/test/org/hibernate/test/usercollection/basic/MyList.java
new file mode 100644
index 0000000000..e5cea86242
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/basic/MyList.java
@@ -0,0 +1,14 @@
+package org.hibernate.test.usercollection.basic;
+
+import java.util.ArrayList;
+
+/**
+ * A custom collection class. We extend a java.util.Collection class, but that is not required.
+ * It could be totally non-java-collection type, but then we would need to implement all the PersistentCollection methods.
+ *
+ * @author max
+ *
+ */
+public class MyList extends ArrayList implements IMyList {
+
+}
diff --git a/test/org/hibernate/test/usercollection/basic/MyListType.java b/test/org/hibernate/test/usercollection/basic/MyListType.java
new file mode 100644
index 0000000000..25497f4f79
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/basic/MyListType.java
@@ -0,0 +1,60 @@
+package org.hibernate.test.usercollection.basic;
+
+import java.util.Iterator;
+import java.util.Map;
+
+import org.hibernate.EntityMode;
+import org.hibernate.HibernateException;
+import org.hibernate.collection.PersistentCollection;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.persister.collection.CollectionPersister;
+import org.hibernate.usertype.UserCollectionType;
+
+public class MyListType implements UserCollectionType {
+
+ static int lastInstantiationRequest = -2;
+
+ public PersistentCollection instantiate(SessionImplementor session, CollectionPersister persister) throws HibernateException {
+ return new PersistentMyList(session);
+ }
+
+ public PersistentCollection wrap(SessionImplementor session, Object collection) {
+ if ( session.getEntityMode()==EntityMode.DOM4J ) {
+ throw new IllegalStateException("dom4j not supported");
+ }
+ else {
+ return new PersistentMyList( session, (IMyList) collection );
+ }
+ }
+
+ public Iterator getElementsIterator(Object collection) {
+ return ( (IMyList) collection ).iterator();
+ }
+
+ public boolean contains(Object collection, Object entity) {
+ return ( (IMyList) collection ).contains(entity);
+ }
+
+ public Object indexOf(Object collection, Object entity) {
+ int l = ( (IMyList) collection ).indexOf(entity);
+ if(l<0) {
+ return null;
+ } else {
+ return new Integer(l);
+ }
+ }
+
+ public Object replaceElements(Object original, Object target, CollectionPersister persister, Object owner, Map copyCache, SessionImplementor session) throws HibernateException {
+ IMyList result = (IMyList) target;
+ result.clear();
+ result.addAll((MyList)original);
+ return result;
+ }
+
+ public Object instantiate(int anticipatedSize) {
+ lastInstantiationRequest = anticipatedSize;
+ return new MyList();
+ }
+
+
+}
diff --git a/test/org/hibernate/test/usercollection/basic/PersistentMyList.java b/test/org/hibernate/test/usercollection/basic/PersistentMyList.java
new file mode 100644
index 0000000000..abf5bb87b6
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/basic/PersistentMyList.java
@@ -0,0 +1,18 @@
+package org.hibernate.test.usercollection.basic;
+
+import org.hibernate.collection.PersistentList;
+import org.hibernate.engine.SessionImplementor;
+
+public class PersistentMyList extends PersistentList implements IMyList {
+
+ public PersistentMyList(SessionImplementor session) {
+ super(session);
+ }
+
+ public PersistentMyList(SessionImplementor session, IMyList list) {
+ super(session, list);
+ }
+
+
+
+}
diff --git a/test/org/hibernate/test/usercollection/basic/User.java b/test/org/hibernate/test/usercollection/basic/User.java
new file mode 100644
index 0000000000..de146a04e0
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/basic/User.java
@@ -0,0 +1,39 @@
+//$Id$
+package org.hibernate.test.usercollection.basic;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @author Gavin King
+ */
+public class User {
+ private String userName;
+ private IMyList emailAddresses = new MyList();
+ private Map sessionData = new HashMap();
+
+ User() {}
+ public User(String name) {
+ userName = name;
+ }
+
+ public String getUserName() {
+ return userName;
+ }
+ public void setUserName(String userName) {
+ this.userName = userName;
+ }
+ public List getEmailAddresses() {
+ return emailAddresses;
+ }
+ public void setEmailAddresses(IMyList emailAddresses) {
+ this.emailAddresses = emailAddresses;
+ }
+ public Map getSessionData() {
+ return sessionData;
+ }
+ public void setSessionData(Map sessionData) {
+ this.sessionData = sessionData;
+ }
+}
diff --git a/test/org/hibernate/test/usercollection/basic/UserCollectionTypeTest.java b/test/org/hibernate/test/usercollection/basic/UserCollectionTypeTest.java
new file mode 100644
index 0000000000..0517de6683
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/basic/UserCollectionTypeTest.java
@@ -0,0 +1,63 @@
+//$Id$
+package org.hibernate.test.usercollection.basic;
+
+import junit.framework.Test;
+
+import org.hibernate.Hibernate;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * @author Max Rydahl Andersen
+ */
+public class UserCollectionTypeTest extends FunctionalTestCase {
+
+ public UserCollectionTypeTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "usercollection/basic/UserPermissions.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( UserCollectionTypeTest.class );
+ }
+
+ public void testBasicOperation() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ User u = new User("max");
+ u.getEmailAddresses().add( new Email("max@hibernate.org") );
+ u.getEmailAddresses().add( new Email("max.andersen@jboss.com") );
+ s.persist(u);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ User u2 = (User) s.createCriteria(User.class).uniqueResult();
+ assertTrue( Hibernate.isInitialized( u2.getEmailAddresses() ) );
+ assertEquals( u2.getEmailAddresses().size(), 2 );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ u2 = ( User ) s.get( User.class, u.getUserName() );
+ u2.getEmailAddresses().size();
+ assertEquals( 2, MyListType.lastInstantiationRequest );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.delete( u );
+ t.commit();
+ s.close();
+ }
+
+}
+
diff --git a/test/org/hibernate/test/usercollection/basic/UserPermissions.hbm.xml b/test/org/hibernate/test/usercollection/basic/UserPermissions.hbm.xml
new file mode 100644
index 0000000000..2a8f7eb765
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/basic/UserPermissions.hbm.xml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/org/hibernate/test/usercollection/parameterized/DefaultableList.java b/test/org/hibernate/test/usercollection/parameterized/DefaultableList.java
new file mode 100644
index 0000000000..f37d950c4a
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/parameterized/DefaultableList.java
@@ -0,0 +1,13 @@
+package org.hibernate.test.usercollection.parameterized;
+
+import java.util.List;
+
+/**
+ * Our specialized collection contract
+ *
+ * @author Holger Brands
+ * @author Steve Ebersole
+ */
+public interface DefaultableList extends List {
+ public String getDefaultValue();
+}
diff --git a/test/org/hibernate/test/usercollection/parameterized/DefaultableListImpl.java b/test/org/hibernate/test/usercollection/parameterized/DefaultableListImpl.java
new file mode 100644
index 0000000000..5e6c2254c1
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/parameterized/DefaultableListImpl.java
@@ -0,0 +1,28 @@
+package org.hibernate.test.usercollection.parameterized;
+
+import java.util.ArrayList;
+
+/**
+ * Implementation of our specialized collection contract
+ *
+ * @author Holger Brands
+ * @author Steve Ebersole
+ */
+public class DefaultableListImpl extends ArrayList implements DefaultableList {
+ private String defaultValue;
+
+ public DefaultableListImpl() {
+ }
+
+ public DefaultableListImpl(int anticipatedSize) {
+ super( anticipatedSize + ( int ) Math.ceil( anticipatedSize * .75f ) );
+ }
+
+ public String getDefaultValue() {
+ return defaultValue;
+ }
+
+ public void setDefaultValue(String defaultValue) {
+ this.defaultValue = defaultValue;
+ }
+}
diff --git a/test/org/hibernate/test/usercollection/parameterized/DefaultableListType.java b/test/org/hibernate/test/usercollection/parameterized/DefaultableListType.java
new file mode 100644
index 0000000000..fd8783ecbe
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/parameterized/DefaultableListType.java
@@ -0,0 +1,75 @@
+package org.hibernate.test.usercollection.parameterized;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.List;
+
+import org.hibernate.usertype.UserCollectionType;
+import org.hibernate.usertype.ParameterizedType;
+import org.hibernate.collection.PersistentCollection;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.persister.collection.CollectionPersister;
+import org.hibernate.EntityMode;
+
+/**
+ * Our Hibernate type-system extension for defining our specialized collection
+ * contract.
+ *
+ * @author Holger Brands
+ * @author Steve Ebersole
+ */
+public class DefaultableListType implements UserCollectionType, ParameterizedType {
+ private String defaultValue;
+
+ public Object instantiate(int anticipatedSize) {
+ DefaultableListImpl list = anticipatedSize < 0 ? new DefaultableListImpl() : new DefaultableListImpl( anticipatedSize );
+ list.setDefaultValue( defaultValue );
+ return list;
+ }
+
+ public PersistentCollection instantiate(
+ SessionImplementor session,
+ CollectionPersister persister) {
+ return new PersistentDefaultableList( session );
+ }
+
+ public PersistentCollection wrap(SessionImplementor session, Object collection) {
+ if ( session.getEntityMode() == EntityMode.DOM4J ) {
+ throw new IllegalStateException( "dom4j not supported" );
+ }
+ else {
+ return new PersistentDefaultableList( session, ( List ) collection );
+ }
+ }
+
+ public Iterator getElementsIterator(Object collection) {
+ return ( ( DefaultableList ) collection ).iterator();
+ }
+
+ public boolean contains(Object collection, Object entity) {
+ return ( ( DefaultableList ) collection ).contains( entity );
+ }
+
+ public Object indexOf(Object collection, Object entity) {
+ int index = ( ( DefaultableList ) collection ).indexOf( entity );
+ return index >= 0 ? new Integer( index ) : null;
+ }
+
+ public Object replaceElements(
+ Object original,
+ Object target,
+ CollectionPersister persister,
+ Object owner,
+ Map copyCache,
+ SessionImplementor session) {
+ DefaultableList result = ( DefaultableList ) target;
+ result.clear();
+ result.addAll( ( DefaultableList ) original );
+ return result;
+ }
+
+ public void setParameterValues(Properties parameters) {
+ defaultValue = parameters.getProperty( "default" );
+ }
+}
diff --git a/test/org/hibernate/test/usercollection/parameterized/Entity.java b/test/org/hibernate/test/usercollection/parameterized/Entity.java
new file mode 100644
index 0000000000..631d272759
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/parameterized/Entity.java
@@ -0,0 +1,33 @@
+package org.hibernate.test.usercollection.parameterized;
+
+import java.util.List;
+import java.util.ArrayList;
+
+/**
+ * Our test entity
+ *
+ * @author Steve Ebersole
+ */
+public class Entity {
+ private String name;
+ private List values = new ArrayList();
+
+ public Entity() {
+ }
+
+ public Entity(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public List getValues() {
+ return values;
+ }
+
+ public void setValues(List values) {
+ this.values = values;
+ }
+}
diff --git a/test/org/hibernate/test/usercollection/parameterized/Mapping.hbm.xml b/test/org/hibernate/test/usercollection/parameterized/Mapping.hbm.xml
new file mode 100644
index 0000000000..a01a233958
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/parameterized/Mapping.hbm.xml
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+ Hello
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/test/org/hibernate/test/usercollection/parameterized/ParameterizedUserCollectionTypeTest.java b/test/org/hibernate/test/usercollection/parameterized/ParameterizedUserCollectionTypeTest.java
new file mode 100644
index 0000000000..f379053ecd
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/parameterized/ParameterizedUserCollectionTypeTest.java
@@ -0,0 +1,49 @@
+package org.hibernate.test.usercollection.parameterized;
+
+import junit.framework.Test;
+
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.Hibernate;
+
+/**
+ * Tes for parameterized user collection types.
+ *
+ * @author Holger Brands
+ * @author Steve Ebersole
+ */
+public class ParameterizedUserCollectionTypeTest extends FunctionalTestCase {
+ public ParameterizedUserCollectionTypeTest(String string) {
+ super( string );
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( ParameterizedUserCollectionTypeTest.class );
+ }
+
+ public String[] getMappings() {
+ return new String[] { "usercollection/parameterized/Mapping.hbm.xml" };
+ }
+
+ public void testBasicOperation() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Entity entity = new Entity( "tester" );
+ entity.getValues().add( "value-1" );
+ s.persist( entity );
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ entity = ( Entity ) s.get( Entity.class, "tester" );
+ assertTrue( Hibernate.isInitialized( entity.getValues() ) );
+ assertEquals( 1, entity.getValues().size() );
+ assertEquals( "Hello", ( ( DefaultableList ) entity.getValues() ).getDefaultValue() );
+ s.delete( entity );
+ t.commit();
+ s.close();
+ }
+}
diff --git a/test/org/hibernate/test/usercollection/parameterized/PersistentDefaultableList.java b/test/org/hibernate/test/usercollection/parameterized/PersistentDefaultableList.java
new file mode 100644
index 0000000000..a57b8893dc
--- /dev/null
+++ b/test/org/hibernate/test/usercollection/parameterized/PersistentDefaultableList.java
@@ -0,0 +1,29 @@
+package org.hibernate.test.usercollection.parameterized;
+
+import java.util.List;
+
+import org.hibernate.collection.PersistentList;
+import org.hibernate.engine.SessionImplementor;
+
+/**
+ * The "persistent wrapper" around our specialized collection contract
+ *
+ * @author Holger Brands
+ * @author Steve Ebersole
+ */
+public class PersistentDefaultableList extends PersistentList implements DefaultableList {
+ public PersistentDefaultableList(SessionImplementor session) {
+ super( session );
+ }
+
+ public PersistentDefaultableList(SessionImplementor session, List list) {
+ super( session, list );
+ }
+
+ public PersistentDefaultableList() {
+ }
+
+ public String getDefaultValue() {
+ return ( ( DefaultableList ) this.list ).getDefaultValue();
+ }
+}
diff --git a/test/org/hibernate/test/util/PropertiesHelperTest.java b/test/org/hibernate/test/util/PropertiesHelperTest.java
new file mode 100644
index 0000000000..f0795d4bc9
--- /dev/null
+++ b/test/org/hibernate/test/util/PropertiesHelperTest.java
@@ -0,0 +1,109 @@
+package org.hibernate.test.util;
+
+import java.util.Properties;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.hibernate.junit.UnitTestCase;
+import org.hibernate.util.PropertiesHelper;
+
+/**
+ * @author Steve Ebersole
+ */
+public class PropertiesHelperTest extends UnitTestCase {
+
+ private Properties props;
+
+ public PropertiesHelperTest(String string) {
+ super( string );
+ }
+
+ public static Test suite() {
+ return new TestSuite( PropertiesHelperTest.class );
+ }
+
+ protected void setUp() throws Exception {
+ props = new Properties();
+
+ props.setProperty( "my.nonexistent.prop", "${}" );
+
+ props.setProperty( "my.string.prop", "${test.my.sys.string.prop}" );
+ System.setProperty( "test.my.sys.string.prop", "string" );
+
+ props.setProperty( "my.boolean.prop", "${test.my.sys.boolean.prop}" );
+ System.setProperty( "test.my.sys.boolean.prop", "true" );
+
+ props.setProperty( "my.int.prop", "${test.my.sys.int.prop}" );
+ System.setProperty( "test.my.sys.int.prop", "1" );
+
+ props.setProperty( "my.integer.prop", "${test.my.sys.integer.prop}" );
+ System.setProperty( "test.my.sys.integer.prop", "1" );
+
+ props.setProperty( "partial.prop1", "${somedir}/middle/dir/${somefile}" );
+ props.setProperty( "partial.prop2", "basedir/${somedir}/myfile.txt" );
+ System.setProperty( "somedir", "tmp" );
+ System.setProperty( "somefile", "tmp.txt" );
+
+ props.setProperty( "parse.error", "steve" );
+ }
+
+ public void testPlaceholderReplacement() {
+ PropertiesHelper.resolvePlaceHolders( props );
+
+ String str = PropertiesHelper.getString( "my.nonexistent.prop", props, "did.not.exist" );
+ assertEquals( "did.not.exist", str );
+ str = PropertiesHelper.getString( "my.nonexistent.prop", props, null );
+ assertNull( str );
+ str = PropertiesHelper.getString( "my.string.prop", props, "na" );
+ assertEquals( "replacement did not occur", "string", str );
+ str = PropertiesHelper.getString( "my.string.prop", props, "did.not.exist" );
+ assertEquals( "replacement did not occur", "string", str );
+
+ boolean bool = PropertiesHelper.getBoolean( "my.nonexistent.prop", props );
+ assertFalse( "non-exists as boolean", bool );
+ bool = PropertiesHelper.getBoolean( "my.nonexistent.prop", props, false );
+ assertFalse( "non-exists as boolean", bool );
+ bool = PropertiesHelper.getBoolean( "my.nonexistent.prop", props, true );
+ assertTrue( "non-exists as boolean", bool );
+ bool = PropertiesHelper.getBoolean( "my.boolean.prop", props );
+ assertTrue( "boolean replacement did not occur", bool );
+ bool = PropertiesHelper.getBoolean( "my.boolean.prop", props, false );
+ assertTrue( "boolean replacement did not occur", bool );
+
+ int i = PropertiesHelper.getInt( "my.nonexistent.prop", props, -1 );
+ assertEquals( -1, i );
+ i = PropertiesHelper.getInt( "my.int.prop", props, 100 );
+ assertEquals( 1, i );
+
+ Integer I = PropertiesHelper.getInteger( "my.nonexistent.prop", props );
+ assertNull( I );
+ I = PropertiesHelper.getInteger( "my.integer.prop", props );
+ assertEquals( I, new Integer( 1 ) );
+
+ str = props.getProperty( "partial.prop1" );
+ assertEquals( "partial replacement (ends)", "tmp/middle/dir/tmp.txt", str );
+
+ str = props.getProperty( "partial.prop2" );
+ assertEquals( "partial replacement (midst)", "basedir/tmp/myfile.txt", str );
+ }
+
+ public void testParseExceptions() {
+ boolean b = PropertiesHelper.getBoolean( "parse.error", props );
+ assertFalse( "parse exception case - boolean", b );
+
+ try {
+ PropertiesHelper.getInt( "parse.error", props, 20 );
+ fail( "parse exception case - int" );
+ }
+ catch( NumberFormatException expected ) {
+ }
+
+ try {
+ PropertiesHelper.getInteger( "parse.error", props );
+ fail( "parse exception case - Integer" );
+ }
+ catch( NumberFormatException expected ) {
+ }
+ }
+}
diff --git a/test/org/hibernate/test/util/StringHelperTest.java b/test/org/hibernate/test/util/StringHelperTest.java
new file mode 100644
index 0000000000..811ca5f68b
--- /dev/null
+++ b/test/org/hibernate/test/util/StringHelperTest.java
@@ -0,0 +1,32 @@
+package org.hibernate.test.util;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.hibernate.junit.UnitTestCase;
+import org.hibernate.util.StringHelper;
+
+/**
+ * @author Steve Ebersole
+ */
+public class StringHelperTest extends UnitTestCase {
+
+ public StringHelperTest(String string) {
+ super( string );
+ }
+
+ public static Test suite() {
+ return new TestSuite( StringHelperTest.class );
+ }
+
+ public void testAliasGeneration() {
+ assertSimpleAlias( "xyz", "xyz_" );
+ assertSimpleAlias( "_xyz", "xyz_" );
+ assertSimpleAlias( "!xyz", "xyz_" );
+ assertSimpleAlias( "abcdefghijklmnopqrstuvwxyz", "abcdefghij_" );
+ }
+
+ private void assertSimpleAlias(String source, String expected) {
+ assertEquals( expected, StringHelper.generateAlias( source ) );
+ }
+}
diff --git a/test/org/hibernate/test/util/UtilSuite.java b/test/org/hibernate/test/util/UtilSuite.java
new file mode 100644
index 0000000000..5fc39a2aba
--- /dev/null
+++ b/test/org/hibernate/test/util/UtilSuite.java
@@ -0,0 +1,20 @@
+package org.hibernate.test.util;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+import org.hibernate.test.util.dtd.EntityResolverTest;
+
+/**
+ * todo: describe UtilSuite
+ *
+ * @author Steve Ebersole
+ */
+public class UtilSuite {
+ public static Test suite() {
+ TestSuite suite = new TestSuite( "Utility package tests" );
+ suite.addTest( PropertiesHelperTest.suite() );
+ suite.addTest( EntityResolverTest.suite() );
+ suite.addTest( StringHelperTest.suite() );
+ return suite;
+ }
+}
diff --git a/test/org/hibernate/test/util/dtd/Child.java b/test/org/hibernate/test/util/dtd/Child.java
new file mode 100644
index 0000000000..7238a48bea
--- /dev/null
+++ b/test/org/hibernate/test/util/dtd/Child.java
@@ -0,0 +1,36 @@
+package org.hibernate.test.util.dtd;
+
+/**
+ * The Child class.
+ *
+ * @author Steve Ebersole
+ */
+public class Child {
+ private Long id;
+ private int age;
+ private Parent parent;
+
+ public Child() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public Parent getParent() {
+ return parent;
+ }
+
+ public int getAge() {
+ return age;
+ }
+
+ public void setAge(int age) {
+ this.age = age;
+ }
+
+
+ /*package*/ void injectParent(Parent parent) {
+ this.parent = parent;
+ }
+}
diff --git a/test/org/hibernate/test/util/dtd/EntityResolverTest.java b/test/org/hibernate/test/util/dtd/EntityResolverTest.java
new file mode 100644
index 0000000000..928acb2db2
--- /dev/null
+++ b/test/org/hibernate/test/util/dtd/EntityResolverTest.java
@@ -0,0 +1,32 @@
+package org.hibernate.test.util.dtd;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.hibernate.cfg.Configuration;
+import org.hibernate.junit.UnitTestCase;
+
+
+/**
+ * @author Steve Ebersole
+ */
+public class EntityResolverTest extends UnitTestCase {
+
+ public EntityResolverTest(String name) {
+ super( name );
+ }
+
+ public static Test suite() {
+ return new TestSuite( EntityResolverTest.class );
+ }
+
+ public void testEntityIncludeResolution() {
+ // Parent.hbm.xml contains the following entity include:
+ //
+ // which we are expecting the Hibernate custom entity resolver to be able to resolve
+ // locally via classpath lookup.
+ Configuration cfg = new Configuration();
+ cfg.addResource( "org/hibernate/test/util/dtd/Parent.hbm.xml" );
+ cfg.buildMappings();
+ }
+}
diff --git a/test/org/hibernate/test/util/dtd/Parent.hbm.xml b/test/org/hibernate/test/util/dtd/Parent.hbm.xml
new file mode 100644
index 0000000000..0e58fc9e29
--- /dev/null
+++ b/test/org/hibernate/test/util/dtd/Parent.hbm.xml
@@ -0,0 +1,24 @@
+
+
+]>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ &child;
+
+
diff --git a/test/org/hibernate/test/util/dtd/Parent.java b/test/org/hibernate/test/util/dtd/Parent.java
new file mode 100644
index 0000000000..061f825ee3
--- /dev/null
+++ b/test/org/hibernate/test/util/dtd/Parent.java
@@ -0,0 +1,33 @@
+package org.hibernate.test.util.dtd;
+
+import java.util.Set;
+import java.util.HashSet;
+import java.util.Iterator;
+
+/**
+ * The Parent class.
+ *
+ * @author Steve Ebersole
+ */
+public class Parent {
+ private Long id;
+ private Set children = new HashSet();
+
+ public Long getId() {
+ return id;
+ }
+
+ public Iterator getChildren() {
+ return children.iterator();
+ }
+
+ public Child newChild() {
+ Child child = new Child();
+ child.setAge( 0 );
+
+ child.injectParent( this );
+ this.children.add( child );
+
+ return child;
+ }
+}
diff --git a/test/org/hibernate/test/util/dtd/child.xml b/test/org/hibernate/test/util/dtd/child.xml
new file mode 100644
index 0000000000..23b2d1740f
--- /dev/null
+++ b/test/org/hibernate/test/util/dtd/child.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/test/org/hibernate/test/version/Person.java b/test/org/hibernate/test/version/Person.java
new file mode 100755
index 0000000000..4f647cf2ea
--- /dev/null
+++ b/test/org/hibernate/test/version/Person.java
@@ -0,0 +1,43 @@
+//$Id$
+package org.hibernate.test.version;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Person {
+ private String name;
+ private List things;
+ private List tasks;
+ private int version;
+
+ Person() {}
+ public Person(String name) {
+ this.name = name;
+ this.things = new ArrayList();
+ this.tasks = new ArrayList();
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+ public List getThings() {
+ return things;
+ }
+ public void setThings(List things) {
+ this.things = things;
+ }
+ public int getVersion() {
+ return version;
+ }
+ public void setVersion(int version) {
+ this.version = version;
+ }
+ public List getTasks() {
+ return tasks;
+ }
+ public void setTasks(List tasks) {
+ this.tasks = tasks;
+ }
+}
diff --git a/test/org/hibernate/test/version/PersonThing.hbm.xml b/test/org/hibernate/test/version/PersonThing.hbm.xml
new file mode 100755
index 0000000000..1cfc4791d7
--- /dev/null
+++ b/test/org/hibernate/test/version/PersonThing.hbm.xml
@@ -0,0 +1,45 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/org/hibernate/test/version/Task.java b/test/org/hibernate/test/version/Task.java
new file mode 100755
index 0000000000..30f05fdad9
--- /dev/null
+++ b/test/org/hibernate/test/version/Task.java
@@ -0,0 +1,33 @@
+//$Id$
+package org.hibernate.test.version;
+
+public class Task {
+ private String description;
+ private Person person;
+ private int version;
+
+ public int getVersion() {
+ return version;
+ }
+ public void setVersion(int version) {
+ this.version = version;
+ }
+ Task() {}
+ public Task(String description, Person person) {
+ this.description = description;
+ this.person = person;
+ person.getTasks().add(this);
+ }
+ public String getDescription() {
+ return description;
+ }
+ public void setDescription(String description) {
+ this.description = description;
+ }
+ public Person getPerson() {
+ return person;
+ }
+ public void setPerson(Person person) {
+ this.person = person;
+ }
+}
diff --git a/test/org/hibernate/test/version/Thing.java b/test/org/hibernate/test/version/Thing.java
new file mode 100755
index 0000000000..35fddedfd7
--- /dev/null
+++ b/test/org/hibernate/test/version/Thing.java
@@ -0,0 +1,40 @@
+//$Id$
+package org.hibernate.test.version;
+
+public class Thing {
+ private String description;
+ private Person person;
+ private int version;
+ private String longDescription;
+
+ public int getVersion() {
+ return version;
+ }
+ public void setVersion(int version) {
+ this.version = version;
+ }
+ Thing() {}
+ public Thing(String description, Person person) {
+ this.description = description;
+ this.person = person;
+ person.getThings().add(this);
+ }
+ public String getDescription() {
+ return description;
+ }
+ public void setDescription(String description) {
+ this.description = description;
+ }
+ public Person getPerson() {
+ return person;
+ }
+ public void setPerson(Person person) {
+ this.person = person;
+ }
+ public String getLongDescription() {
+ return longDescription;
+ }
+ public void setLongDescription(String longDescription) {
+ this.longDescription = longDescription;
+ }
+}
diff --git a/test/org/hibernate/test/version/VersionTest.java b/test/org/hibernate/test/version/VersionTest.java
new file mode 100755
index 0000000000..a2bbdf8c10
--- /dev/null
+++ b/test/org/hibernate/test/version/VersionTest.java
@@ -0,0 +1,135 @@
+//$Id$
+package org.hibernate.test.version;
+
+import junit.framework.Test;
+
+import org.hibernate.Hibernate;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * @author Max Rydahl Andersen
+ */
+public class VersionTest extends FunctionalTestCase {
+
+ public VersionTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "version/PersonThing.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( VersionTest.class );
+ }
+
+ public void testVersionShortCircuitFlush() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Person gavin = new Person("Gavin");
+ new Thing("Passport", gavin);
+ s.persist(gavin);
+ t.commit();
+ s.close();
+
+ s = openSession();
+ t = s.beginTransaction();
+ Thing passp = (Thing) s.get(Thing.class, "Passport");
+ passp.setLongDescription("blah blah blah");
+ s.createQuery("from Person").list();
+ s.createQuery("from Person").list();
+ s.createQuery("from Person").list();
+ t.commit();
+ s.close();
+
+ assertEquals( passp.getVersion(), 1 );
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.createQuery("delete from Thing").executeUpdate();
+ s.createQuery("delete from Person").executeUpdate();
+ t.commit();
+ s.close();
+ }
+
+ public void testCollectionVersion() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Person gavin = new Person("Gavin");
+ new Thing("Passport", gavin);
+ s.persist(gavin);
+ t.commit();
+ s.close();
+
+ assertEquals(0, gavin.getVersion());
+
+ s = openSession();
+ t = s.beginTransaction();
+ gavin = (Person) s.createCriteria(Person.class).uniqueResult();
+ new Thing("Laptop", gavin);
+ t.commit();
+ s.close();
+
+ assertEquals(1, gavin.getVersion());
+ assertFalse( Hibernate.isInitialized( gavin.getThings() ) );
+
+ s = openSession();
+ t = s.beginTransaction();
+ gavin = (Person) s.createCriteria(Person.class).uniqueResult();
+ gavin.getThings().clear();
+ t.commit();
+ s.close();
+
+ assertEquals(2, gavin.getVersion());
+ assertTrue( Hibernate.isInitialized( gavin.getThings() ) );
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.delete(gavin);
+ t.commit();
+ s.close();
+ }
+
+ public void testCollectionNoVersion() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ Person gavin = new Person("Gavin");
+ new Task("Code", gavin);
+ s.persist(gavin);
+ t.commit();
+ s.close();
+
+ assertEquals(0, gavin.getVersion());
+
+ s = openSession();
+ t = s.beginTransaction();
+ gavin = (Person) s.createCriteria(Person.class).uniqueResult();
+ new Task("Document", gavin);
+ t.commit();
+ s.close();
+
+ assertEquals(0, gavin.getVersion());
+ assertFalse( Hibernate.isInitialized( gavin.getTasks() ) );
+
+ s = openSession();
+ t = s.beginTransaction();
+ gavin = (Person) s.createCriteria(Person.class).uniqueResult();
+ gavin.getTasks().clear();
+ t.commit();
+ s.close();
+
+ assertEquals(0, gavin.getVersion());
+ assertTrue( Hibernate.isInitialized( gavin.getTasks() ) );
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.delete(gavin);
+ t.commit();
+ s.close();
+ }
+
+}
+
diff --git a/test/org/hibernate/test/version/db/DbVersionTest.java b/test/org/hibernate/test/version/db/DbVersionTest.java
new file mode 100644
index 0000000000..d0a792bbaf
--- /dev/null
+++ b/test/org/hibernate/test/version/db/DbVersionTest.java
@@ -0,0 +1,119 @@
+// $Id$
+package org.hibernate.test.version.db;
+
+import java.sql.Timestamp;
+
+import junit.framework.Test;
+
+import org.hibernate.Hibernate;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * Implementation of DbVersionTest.
+ *
+ * @author Steve Ebersole
+ */
+public class DbVersionTest extends FunctionalTestCase {
+ public DbVersionTest(String x) {
+ super( x );
+ }
+
+
+ public String[] getMappings() {
+ return new String[] { "version/db/User.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( DbVersionTest.class );
+ }
+
+ public void testCollectionVersion() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ User steve = new User( "steve" );
+ s.persist( steve );
+ Group admin = new Group( "admin" );
+ s.persist( admin );
+ t.commit();
+ s.close();
+
+ Timestamp steveTimestamp = steve.getTimestamp();
+
+ // For dialects (Oracle8 for example) which do not return "true
+ // timestamps" sleep for a bit to allow the db date-time increment...
+ Thread.sleep( 1500 );
+
+ s = openSession();
+ t = s.beginTransaction();
+ steve = ( User ) s.get( User.class, steve.getId() );
+ admin = ( Group ) s.get( Group.class, admin.getId() );
+ steve.getGroups().add( admin );
+ admin.getUsers().add( steve );
+ t.commit();
+ s.close();
+
+ assertFalse( "owner version not incremented", Hibernate.TIMESTAMP.isEqual( steveTimestamp, steve.getTimestamp() ) );
+
+ steveTimestamp = steve.getTimestamp();
+ Thread.sleep( 1500 );
+
+ s = openSession();
+ t = s.beginTransaction();
+ steve = ( User ) s.get( User.class, steve.getId() );
+ steve.getGroups().clear();
+ t.commit();
+ s.close();
+
+ assertFalse( "owner version not incremented", Hibernate.TIMESTAMP.isEqual( steveTimestamp, steve.getTimestamp() ) );
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.delete( s.load( User.class, steve.getId() ) );
+ s.delete( s.load( Group.class, admin.getId() ) );
+ t.commit();
+ s.close();
+ }
+
+
+ public void testCollectionNoVersion() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ User steve = new User( "steve" );
+ s.persist( steve );
+ Permission perm = new Permission( "silly", "user", "rw" );
+ s.persist( perm );
+ t.commit();
+ s.close();
+
+ Timestamp steveTimestamp = ( Timestamp ) steve.getTimestamp();
+
+ s = openSession();
+ t = s.beginTransaction();
+ steve = ( User ) s.get( User.class, steve.getId() );
+ perm = ( Permission ) s.get( Permission.class, perm.getId() );
+ steve.getPermissions().add( perm );
+ t.commit();
+ s.close();
+
+ assertTrue( "owner version was incremented", Hibernate.TIMESTAMP.isEqual( steveTimestamp, steve.getTimestamp() ) );
+
+ s = openSession();
+ t = s.beginTransaction();
+ steve = ( User ) s.get( User.class, steve.getId() );
+ steve.getPermissions().clear();
+ t.commit();
+ s.close();
+
+ assertTrue( "owner version was incremented", Hibernate.TIMESTAMP.isEqual( steveTimestamp, steve.getTimestamp() ) );
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.delete( s.load( User.class, steve.getId() ) );
+ s.delete( s.load( Permission.class, perm.getId() ) );
+ t.commit();
+ s.close();
+ }
+}
\ No newline at end of file
diff --git a/test/org/hibernate/test/version/db/Group.java b/test/org/hibernate/test/version/db/Group.java
new file mode 100644
index 0000000000..ed8066c12d
--- /dev/null
+++ b/test/org/hibernate/test/version/db/Group.java
@@ -0,0 +1,56 @@
+// $Id$
+package org.hibernate.test.version.db;
+
+import java.util.Date;
+import java.util.Set;
+
+/**
+ * Implementation of Group.
+ *
+ * @author Steve Ebersole
+ */
+public class Group {
+ private Long id;
+ private Date timestamp;
+ private String name;
+ private Set users;
+
+ public Group() {
+ }
+
+ public Group(String name) {
+ this.name = name;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Date getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(Date timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Set getUsers() {
+ return users;
+ }
+
+ public void setUsers(Set users) {
+ this.users = users;
+ }
+}
diff --git a/test/org/hibernate/test/version/db/Permission.java b/test/org/hibernate/test/version/db/Permission.java
new file mode 100644
index 0000000000..3f89576f52
--- /dev/null
+++ b/test/org/hibernate/test/version/db/Permission.java
@@ -0,0 +1,66 @@
+// $Id$
+package org.hibernate.test.version.db;
+
+import java.util.Date;
+
+/**
+ * Implementation of Permission.
+ *
+ * @author Steve Ebersole
+ */
+public class Permission {
+ private Long id;
+ private Date timestamp;
+ private String name;
+ private String context;
+ private String access;
+
+ public Permission() {
+ }
+
+ public Permission(String name, String context, String access) {
+ this.name = name;
+ this.context = context;
+ this.access = access;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Date getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(Date timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getContext() {
+ return context;
+ }
+
+ public void setContext(String context) {
+ this.context = context;
+ }
+
+ public String getAccess() {
+ return access;
+ }
+
+ public void setAccess(String access) {
+ this.access = access;
+ }
+}
diff --git a/test/org/hibernate/test/version/db/User.hbm.xml b/test/org/hibernate/test/version/db/User.hbm.xml
new file mode 100644
index 0000000000..3acd512ca6
--- /dev/null
+++ b/test/org/hibernate/test/version/db/User.hbm.xml
@@ -0,0 +1,55 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/org/hibernate/test/version/db/User.java b/test/org/hibernate/test/version/db/User.java
new file mode 100644
index 0000000000..b79cac282b
--- /dev/null
+++ b/test/org/hibernate/test/version/db/User.java
@@ -0,0 +1,65 @@
+// $Id$
+package org.hibernate.test.version.db;
+
+import java.util.Set;
+import java.sql.Timestamp;
+
+/**
+ * Implementation of User.
+ *
+ * @author Steve Ebersole
+ */
+public class User {
+ private Long id;
+ private Timestamp timestamp;
+ private String username;
+ private Set groups;
+ private Set permissions;
+
+ public User() {
+ }
+
+ public User(String username) {
+ this.username = username;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Timestamp getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(Timestamp timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ public Set getGroups() {
+ return groups;
+ }
+
+ public void setGroups(Set groups) {
+ this.groups = groups;
+ }
+
+ public Set getPermissions() {
+ return permissions;
+ }
+
+ public void setPermissions(Set permissions) {
+ this.permissions = permissions;
+ }
+}
diff --git a/test/org/hibernate/test/version/sybase/Group.java b/test/org/hibernate/test/version/sybase/Group.java
new file mode 100644
index 0000000000..0aa38764dc
--- /dev/null
+++ b/test/org/hibernate/test/version/sybase/Group.java
@@ -0,0 +1,56 @@
+// $Id$
+package org.hibernate.test.version.sybase;
+
+import java.util.Date;
+import java.util.Set;
+
+/**
+ * Implementation of Group.
+ *
+ * @author Steve Ebersole
+ */
+public class Group {
+ private Long id;
+ private Date timestamp;
+ private String name;
+ private Set users;
+
+ public Group() {
+ }
+
+ public Group(String name) {
+ this.name = name;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Date getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(Date timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Set getUsers() {
+ return users;
+ }
+
+ public void setUsers(Set users) {
+ this.users = users;
+ }
+}
diff --git a/test/org/hibernate/test/version/sybase/Permission.java b/test/org/hibernate/test/version/sybase/Permission.java
new file mode 100644
index 0000000000..525e8cd1c0
--- /dev/null
+++ b/test/org/hibernate/test/version/sybase/Permission.java
@@ -0,0 +1,66 @@
+// $Id$
+package org.hibernate.test.version.sybase;
+
+import java.util.Date;
+
+/**
+ * Implementation of Permission.
+ *
+ * @author Steve Ebersole
+ */
+public class Permission {
+ private Long id;
+ private Date timestamp;
+ private String name;
+ private String context;
+ private String access;
+
+ public Permission() {
+ }
+
+ public Permission(String name, String context, String access) {
+ this.name = name;
+ this.context = context;
+ this.access = access;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Date getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(Date timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getContext() {
+ return context;
+ }
+
+ public void setContext(String context) {
+ this.context = context;
+ }
+
+ public String getAccess() {
+ return access;
+ }
+
+ public void setAccess(String access) {
+ this.access = access;
+ }
+}
diff --git a/test/org/hibernate/test/version/sybase/SybaseTimestampVersioningTest.java b/test/org/hibernate/test/version/sybase/SybaseTimestampVersioningTest.java
new file mode 100644
index 0000000000..3e2e0780d9
--- /dev/null
+++ b/test/org/hibernate/test/version/sybase/SybaseTimestampVersioningTest.java
@@ -0,0 +1,202 @@
+// $Id$
+package org.hibernate.test.version.sybase;
+
+import junit.framework.Test;
+
+import org.hibernate.Hibernate;
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.SybaseDialect;
+import org.hibernate.junit.functional.DatabaseSpecificFunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * Implementation of VersionTest.
+ *
+ * @author Steve Ebersole
+ */
+public class SybaseTimestampVersioningTest extends DatabaseSpecificFunctionalTestCase {
+
+ public SybaseTimestampVersioningTest(String x) {
+ super( x );
+ }
+
+ public String[] getMappings() {
+ return new String[] { "version/sybase/User.hbm.xml" };
+ }
+
+ public boolean appliesTo(Dialect dialect) {
+ return dialect instanceof SybaseDialect;
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( SybaseTimestampVersioningTest.class );
+ }
+
+ public void testLocking() throws Throwable {
+ // First, create the needed row...
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ User steve = new User( "steve" );
+ s.persist( steve );
+ t.commit();
+ s.close();
+
+ // next open two sessions, and try to update from each "simultaneously"...
+ Session s1 = null;
+ Session s2 = null;
+ Transaction t1 = null;
+ Transaction t2 = null;
+ try {
+ s1 = getSessions().openSession();
+ t1 = s1.beginTransaction();
+ s2 = getSessions().openSession();
+ t2 = s2.beginTransaction();
+
+ User user1 = ( User ) s1.get( User.class, steve.getId() );
+ User user2 = ( User ) s2.get( User.class, steve.getId() );
+
+ user1.setUsername( "se" );
+ t1.commit();
+ t1 = null;
+
+ user2.setUsername( "steve-e" );
+ try {
+ t2.commit();
+ fail( "optimistic lock check did not fail" );
+ }
+ catch( HibernateException e ) {
+ // expected...
+ try {
+ t2.rollback();
+ }
+ catch( Throwable ignore ) {
+ }
+ }
+ }
+ catch( Throwable error ) {
+ if ( t1 != null ) {
+ try {
+ t1.rollback();
+ }
+ catch( Throwable ignore ) {
+ }
+ }
+ if ( t2 != null ) {
+ try {
+ t2.rollback();
+ }
+ catch( Throwable ignore ) {
+ }
+ }
+ throw error;
+ }
+ finally {
+ if ( s1 != null ) {
+ try {
+ s1.close();
+ }
+ catch( Throwable ignore ) {
+ }
+ }
+ if ( s2 != null ) {
+ try {
+ s2.close();
+ }
+ catch( Throwable ignore ) {
+ }
+ }
+ }
+
+ // lastly, clean up...
+ s = openSession();
+ t = s.beginTransaction();
+ s.delete( s.load( User.class, steve.getId() ) );
+ t.commit();
+ s.close();
+ }
+
+ public void testCollectionVersion() throws Exception {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ User steve = new User( "steve" );
+ s.persist( steve );
+ Group admin = new Group( "admin" );
+ s.persist( admin );
+ t.commit();
+ s.close();
+
+ byte[] steveTimestamp = steve.getTimestamp();
+
+ s = openSession();
+ t = s.beginTransaction();
+ steve = ( User ) s.get( User.class, steve.getId() );
+ admin = ( Group ) s.get( Group.class, admin.getId() );
+ steve.getGroups().add( admin );
+ admin.getUsers().add( steve );
+ t.commit();
+ s.close();
+
+ assertFalse( "owner version not incremented", Hibernate.BINARY.isEqual( steveTimestamp, steve.getTimestamp() ) );
+
+ steveTimestamp = steve.getTimestamp();
+
+ s = openSession();
+ t = s.beginTransaction();
+ steve = ( User ) s.get( User.class, steve.getId() );
+ steve.getGroups().clear();
+ t.commit();
+ s.close();
+
+ assertFalse( "owner version not incremented", Hibernate.BINARY.isEqual( steveTimestamp, steve.getTimestamp() ) );
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.delete( s.load( User.class, steve.getId() ) );
+ s.delete( s.load( Group.class, admin.getId() ) );
+ t.commit();
+ s.close();
+ }
+
+
+ public void testCollectionNoVersion() {
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+ User steve = new User( "steve" );
+ s.persist( steve );
+ Permission perm = new Permission( "silly", "user", "rw" );
+ s.persist( perm );
+ t.commit();
+ s.close();
+
+ byte[] steveTimestamp = steve.getTimestamp();
+
+ s = openSession();
+ t = s.beginTransaction();
+ steve = ( User ) s.get( User.class, steve.getId() );
+ perm = ( Permission ) s.get( Permission.class, perm.getId() );
+ steve.getPermissions().add( perm );
+ t.commit();
+ s.close();
+
+ assertTrue( "owner version was incremented", Hibernate.BINARY.isEqual( steveTimestamp, steve.getTimestamp() ) );
+
+ s = openSession();
+ t = s.beginTransaction();
+ steve = ( User ) s.get( User.class, steve.getId() );
+ steve.getPermissions().clear();
+ t.commit();
+ s.close();
+
+ assertTrue( "owner version was incremented", Hibernate.BINARY.isEqual( steveTimestamp, steve.getTimestamp() ) );
+
+ s = openSession();
+ t = s.beginTransaction();
+ s.delete( s.load( User.class, steve.getId() ) );
+ s.delete( s.load( Permission.class, perm.getId() ) );
+ t.commit();
+ s.close();
+ }
+}
\ No newline at end of file
diff --git a/test/org/hibernate/test/version/sybase/User.hbm.xml b/test/org/hibernate/test/version/sybase/User.hbm.xml
new file mode 100644
index 0000000000..53a3f30f44
--- /dev/null
+++ b/test/org/hibernate/test/version/sybase/User.hbm.xml
@@ -0,0 +1,52 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/org/hibernate/test/version/sybase/User.java b/test/org/hibernate/test/version/sybase/User.java
new file mode 100644
index 0000000000..0dda398f8d
--- /dev/null
+++ b/test/org/hibernate/test/version/sybase/User.java
@@ -0,0 +1,65 @@
+// $Id$
+package org.hibernate.test.version.sybase;
+
+import java.util.Set;
+import java.sql.Timestamp;
+
+/**
+ * Implementation of User.
+ *
+ * @author Steve Ebersole
+ */
+public class User {
+ private Long id;
+ private byte[] timestamp;
+ private String username;
+ private Set groups;
+ private Set permissions;
+
+ public User() {
+ }
+
+ public User(String username) {
+ this.username = username;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public byte[] getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(byte[] timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ public Set getGroups() {
+ return groups;
+ }
+
+ public void setGroups(Set groups) {
+ this.groups = groups;
+ }
+
+ public Set getPermissions() {
+ return permissions;
+ }
+
+ public void setPermissions(Set permissions) {
+ this.permissions = permissions;
+ }
+}
diff --git a/test/org/hibernate/test/where/File.hbm.xml b/test/org/hibernate/test/where/File.hbm.xml
new file mode 100755
index 0000000000..0a70d5bc93
--- /dev/null
+++ b/test/org/hibernate/test/where/File.hbm.xml
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/org/hibernate/test/where/File.java b/test/org/hibernate/test/where/File.java
new file mode 100755
index 0000000000..9458f08d6b
--- /dev/null
+++ b/test/org/hibernate/test/where/File.java
@@ -0,0 +1,52 @@
+//$Id$
+package org.hibernate.test.where;
+
+import java.util.Set;
+
+public class File {
+ private long id;
+ private String name;
+ private File parent;
+ private boolean deleted;
+ private Set children;
+
+ public Set getChildren() {
+ return children;
+ }
+ public void setChildren(Set children) {
+ this.children = children;
+ }
+
+ public File(String name, File parent) {
+ this.name = name;
+ this.parent = parent;
+ }
+
+ File() {}
+
+ public boolean isDeleted() {
+ return deleted;
+ }
+ public void setDeleted(boolean deleted) {
+ this.deleted = deleted;
+ }
+ public long getId() {
+ return id;
+ }
+ public void setId(long id) {
+ this.id = id;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+ public File getParent() {
+ return parent;
+ }
+ public void setParent(File parent) {
+ this.parent = parent;
+ }
+
+}
diff --git a/test/org/hibernate/test/where/NumericTrueFalseType.java b/test/org/hibernate/test/where/NumericTrueFalseType.java
new file mode 100644
index 0000000000..56115d6a00
--- /dev/null
+++ b/test/org/hibernate/test/where/NumericTrueFalseType.java
@@ -0,0 +1,53 @@
+package org.hibernate.test.where;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.PreparedStatement;
+import java.sql.Types;
+
+import org.hibernate.type.BooleanType;
+import org.hibernate.dialect.Dialect;
+
+/**
+ * Maps int db values to boolean java values. Zero is considered false; any
+ * non-zero value is considered true.
+ *
+ * @author Steve Ebersole
+ */
+public class NumericTrueFalseType extends BooleanType {
+
+ public Object get(ResultSet rs, String name) throws SQLException {
+ int value = rs.getInt( name );
+ if ( rs.wasNull() ) {
+ return getDefaultValue();
+ }
+ else if ( value == 0 ) {
+ return Boolean.FALSE;
+ }
+ else {
+ return Boolean.TRUE;
+ }
+ }
+
+ public void set(PreparedStatement st, Object value, int index) throws SQLException {
+ if ( value == null ) {
+ st.setNull( index, Types.INTEGER );
+ }
+ else {
+ boolean bool = ( ( Boolean ) value ).booleanValue();
+ st.setInt( index, bool ? 1 : 0 );
+ }
+ }
+
+ public String objectToSQLString(Object value, Dialect dialect) throws Exception {
+ return ( ( Boolean ) value ).booleanValue() ? "1" : "0";
+ }
+
+ public int sqlType() {
+ return Types.INTEGER;
+ }
+
+ public String getName() {
+ return "numeric_boolean";
+ }
+}
diff --git a/test/org/hibernate/test/where/WhereTest.java b/test/org/hibernate/test/where/WhereTest.java
new file mode 100755
index 0000000000..493f001618
--- /dev/null
+++ b/test/org/hibernate/test/where/WhereTest.java
@@ -0,0 +1,57 @@
+//$Id$
+package org.hibernate.test.where;
+
+import junit.framework.Test;
+
+import org.hibernate.FetchMode;
+import org.hibernate.Session;
+import org.hibernate.criterion.Restrictions;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * @author Max Rydahl Andersen
+ */
+public class WhereTest extends FunctionalTestCase {
+
+ public WhereTest(String str) {
+ super(str);
+ }
+
+ public String[] getMappings() {
+ return new String[] { "where/File.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( WhereTest.class );
+ }
+
+ public void testWhere() {
+ Session s = openSession();
+ s.getTransaction().begin();
+ File parent = new File("parent", null);
+ s.persist( parent );
+ s.persist( new File("child", parent) );
+ File deletedChild = new File("deleted child", parent);
+ deletedChild.setDeleted(true);
+ s.persist( deletedChild );
+ File deletedParent = new File("deleted parent", null);
+ deletedParent.setDeleted(true);
+ s.persist( deletedParent );
+ s.flush();
+ s.clear();
+ parent = (File) s.createCriteria(File.class)
+ .setFetchMode("children", FetchMode.JOIN)
+ .add( Restrictions.isNull("parent") )
+ .uniqueResult();
+ assertEquals( parent.getChildren().size(), 1 );
+ s.clear();
+ parent = (File) s.createQuery("from File f left join fetch f.children where f.parent is null")
+ .uniqueResult();
+ assertEquals( parent.getChildren().size(), 1 );
+ s.getTransaction().commit();
+ s.close();
+ }
+
+}
+