Hibernate SVN: r17967 - in sandbox/trunk/new-metadata: src and 8 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2009-11-12 15:52:13 -0500 (Thu, 12 Nov 2009)
New Revision: 17967
Added:
sandbox/trunk/new-metadata/build.gradle
sandbox/trunk/new-metadata/settings.gradle
sandbox/trunk/new-metadata/src/
sandbox/trunk/new-metadata/src/main/
sandbox/trunk/new-metadata/src/main/java/
sandbox/trunk/new-metadata/src/main/java/org/
sandbox/trunk/new-metadata/src/main/java/org/hibernate/
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/java/
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/java/Nature.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/java/package.html
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/mapping/
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/mapping/DatatypeMapping.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/mapping/package.html
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/AbstractColumn.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/AbstractColumnConstraint.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/AbstractTable.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Column.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Constraint.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Datatype.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/DerivedColumn.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Exportable.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/ForeignKey.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Index.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/LogicalTable.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/PhysicalColumn.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/PhysicalTable.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/PrimaryKey.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Table.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/UniqueKey.java
sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/package.html
Modified:
sandbox/trunk/new-metadata/
Log:
selective move from local working
Property changes on: sandbox/trunk/new-metadata
___________________________________________________________________
Name: svn:ignore
- target
local
*.ipr
*.iws
*.iml
.classpath
.project
.nbattrs
*.log
*.properties
.clover
.idea
+ target
build
local
*.ipr
*.iws
*.iml
.classpath
.project
.nbattrs
*.log
*.properties
.clover
.idea
Added: sandbox/trunk/new-metadata/build.gradle
===================================================================
--- sandbox/trunk/new-metadata/build.gradle (rev 0)
+++ sandbox/trunk/new-metadata/build.gradle 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,40 @@
+usePlugin('java')
+
+defaultTasks 'classes'
+
+repositories {
+ mavenCentral()
+ mavenRepo name: "jboss", urls: "http://repository.jboss.org/maven2/"
+ mavenRepo name: "jboss-snapshots", urls: "http://snapshots.jboss.org/maven2/"
+}
+
+group = 'org.hibernate.sandbox'
+version = '1.0.0-SNAPSHOT'
+
+dependencies {
+ hibernateVersion = '3.3.2.GA'
+ slf4jVersion = '1.5.8'
+ jtaVersion = '1.1'
+ javassistVersion = '3.9.0.GA'
+
+ junitVersion = '3.8.2'
+
+ h2Version = '1.0.79'
+
+ compile(
+ [group: 'org.slf4j', name: 'slf4j-api', version: slf4jVersion],
+ [group: 'org.hibernate', name: 'hibernate-core', version: hibernateVersion]
+ )
+ testCompile(
+ [group: 'junit', name: 'junit', version: junitVersion]
+ )
+ testRuntime(
+ [group: 'org.slf4j', name: 'jcl-over-slf4j', version: slf4jVersion],
+ [group: 'org.slf4j', name: 'slf4j-log4j12', version: slf4jVersion],
+ [group: 'javassist', name:'javassist', version: javassistVersion],
+ [group: "com.h2database", name: "h2", version: h2Version]
+ )
+}
+
+targetCompatibility = "1.4"
+sourceCompatibility = "1.4"
Added: sandbox/trunk/new-metadata/settings.gradle
===================================================================
--- sandbox/trunk/new-metadata/settings.gradle (rev 0)
+++ sandbox/trunk/new-metadata/settings.gradle 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1 @@
+rootProject.name = 'hibernate-new-metadata'
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/java/Nature.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/java/Nature.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/java/Nature.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,78 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.java;
+
+import java.io.Serializable;
+import java.util.HashMap;
+
+/**
+ * Enumerations of the various types or natures of attributes.
+ *
+ * @author Steve Ebersole
+ */
+public class Nature implements Serializable {
+ private static final HashMap INSTANCES = new HashMap();
+
+ public static final Nature VALUE = new Nature( "VALUE" );
+ public static final Nature COMPONENT = new Nature( "COMPONENT" );
+ public static final Nature ANY = new Nature( "ANY", true );
+ public static final Nature ENTITY = new Nature( "ENTITY", true );
+ public static final Nature COLLECTION = new Nature( "COLLECTION", true );
+
+ static {
+ INSTANCES.put( VALUE.name, VALUE );
+ INSTANCES.put( COMPONENT.name, COMPONENT );
+ INSTANCES.put( ANY.name, ANY );
+ INSTANCES.put( ENTITY.name, ENTITY );
+ INSTANCES.put( COLLECTION.name, COLLECTION );
+ }
+
+ private final String name;
+ private final boolean association;
+
+ private Nature(String name, boolean association) {
+ this.name = name;
+ this.association = association;
+ }
+
+ private Nature(String name) {
+ this( name, false );
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean isAssociation() {
+ return association;
+ }
+
+ public String toString() {
+ return super.toString() + "[" + getName() + "]";
+ }
+
+ private Object readResolve() {
+ return INSTANCES.get( name );
+ }
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/java/package.html
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/java/package.html (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/java/package.html 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,31 @@
+<!--
+ ~ Hibernate, Relational Persistence for Idiomatic Java
+ ~
+ ~ Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ ~ third-party contributors as indicated by either @author tags or express
+ ~ copyright attribution statements applied by the authors. All
+ ~ third-party contributions are distributed under license by Red Hat Inc.
+ ~
+ ~ This copyrighted material is made available to anyone wishing to use, modify,
+ ~ copy, or redistribute it subject to the terms and conditions of the GNU
+ ~ Lesser General Public License, as published by the Free Software Foundation.
+ ~
+ ~ This program is distributed in the hope that it will be useful,
+ ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ ~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ ~ for more details.
+ ~
+ ~ You should have received a copy of the GNU Lesser General Public License
+ ~ along with this distribution; if not, write to:
+ ~ Free Software Foundation, Inc.
+ ~ 51 Franklin Street, Fifth Floor
+ ~ Boston, MA 02110-1301 USA
+ -->
+
+<html>
+<body>
+<p>
+ This package defines metadata modeling of a Java domain model.
+</p>
+</body>
+</html>
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/mapping/DatatypeMapping.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/mapping/DatatypeMapping.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/mapping/DatatypeMapping.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,47 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.mapping;
+
+import org.hibernate.metadata.schema.Datatype;
+
+/**
+ * Represents the structural information pertaining to mapping between a Java type and an SQL <tt>datatype</tt>.
+ *
+ * @author Steve Ebersole
+ */
+public interface DatatypeMapping {
+ /**
+ * Retrieve the Java type described by this mapping.
+ *
+ * @return The Java class.
+ */
+ public Class getJavaType();
+
+ /**
+ * Retrieve the metadata about the contained SQL datatypes.
+ *
+ * @return The SQL datatype metadata.
+ */
+ public Datatype getSqlDatatypes();
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/mapping/package.html
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/mapping/package.html (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/mapping/package.html 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,34 @@
+<!--
+ ~ Hibernate, Relational Persistence for Idiomatic Java
+ ~
+ ~ Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ ~ third-party contributors as indicated by either @author tags or express
+ ~ copyright attribution statements applied by the authors. All
+ ~ third-party contributions are distributed under license by Red Hat Inc.
+ ~
+ ~ This copyrighted material is made available to anyone wishing to use, modify,
+ ~ copy, or redistribute it subject to the terms and conditions of the GNU
+ ~ Lesser General Public License, as published by the Free Software Foundation.
+ ~
+ ~ This program is distributed in the hope that it will be useful,
+ ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ ~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ ~ for more details.
+ ~
+ ~ You should have received a copy of the GNU Lesser General Public License
+ ~ along with this distribution; if not, write to:
+ ~ Free Software Foundation, Inc.
+ ~ 51 Franklin Street, Fifth Floor
+ ~ Boston, MA 02110-1301 USA
+ -->
+
+<html>
+<body>
+<p>
+ This package builds upon the {@link org.hibernate.metadata.schema} package providing
+ metadata modeling of Java entities to that RDBMS schema.
+</p>
+@see org.hibernate.metadata.schema
+@see org.hibernate.metadata.java
+</body>
+</html>
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/AbstractColumn.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/AbstractColumn.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/AbstractColumn.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,44 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+/**
+ * Basic support for {@link Column} implementations.
+ *
+ * @author Steve Ebersole
+ */
+public abstract class AbstractColumn implements Column {
+ private final Table table;
+
+ protected AbstractColumn(Table table) {
+ this.table = table;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Table getTable() {
+ return table;
+ }
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/AbstractColumnConstraint.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/AbstractColumnConstraint.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/AbstractColumnConstraint.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,59 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+import java.util.List;
+import java.util.ArrayList;
+
+/**
+ * Support for contraints which specifically apply to a column or series of columns.
+ *
+ * @author Steve Ebersole
+ */
+public abstract class AbstractColumnConstraint implements Constraint {
+ private final Table table;
+ private final String name;
+ private List/*<Column>*/ columns = new ArrayList();
+
+ protected AbstractColumnConstraint(Table table, String name) {
+ this.table = table;
+ this.name = name;
+ }
+
+ public Table getTable() {
+ return table;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public List/*<Column>*/ getColumns() {
+ return columns;
+ }
+
+ public void addColumn(Column column) {
+ columns.add( column );
+ }
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/AbstractTable.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/AbstractTable.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/AbstractTable.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,49 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public abstract class AbstractTable implements Table {
+ private PrimaryKey primaryKey = new PrimaryKey( this );
+ private final LinkedHashSet columns = new LinkedHashSet();
+
+ public void addColumn(Column column) {
+ columns.add( column );
+ }
+
+ public PrimaryKey getPrimaryKey() {
+ return primaryKey;
+ }
+
+ public Iterator iterateColumns() {
+ return columns.iterator();
+ }
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Column.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Column.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Column.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,40 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+/**
+ * Models a column within a {@link Table}.
+ *
+ * @author Steve Ebersole
+ */
+public interface Column {
+ /**
+ * Retrieve the table that owns this column.
+ *
+ * @return The owning table.
+ */
+ public Table getTable();
+
+ public String toDebugString();
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Constraint.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Constraint.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Constraint.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,42 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+import java.util.List;
+
+/**
+ * Basic contract for the types of constraints we fully support as metdata constructs:<ul>
+ * <li>primary key contraint</li>
+ * <li>foreign key constraint</li>
+ * <li>unique constraint</li>
+ * </ul>
+ *
+ * @author Steve Ebersole
+ */
+public interface Constraint {
+ public Table getTable();
+ public String getName();
+
+ public List/*<Column>*/ getColumns();
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Datatype.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Datatype.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Datatype.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,54 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+/**
+ * Models a SQL DATATYPE.
+ *
+ * @author Steve Ebersole
+ */
+public class Datatype {
+ private final int typeCode;
+ private final String typeName;
+ private final Class javaType;
+
+ public Datatype(int typeCode, String typeName, Class javaType) {
+ this.typeCode = typeCode;
+ this.typeName = typeName;
+ this.javaType = javaType;
+ }
+
+ public int getTypeCode() {
+ return typeCode;
+ }
+
+ public String getTypeName() {
+ return typeName;
+ }
+
+ public Class getJavaType() {
+ return javaType;
+ }
+
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/DerivedColumn.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/DerivedColumn.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/DerivedColumn.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,42 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+/**
+ * A derived column is the result of a <tt>formula</tt> mapping.
+ *
+ * @author Steve Ebersole
+ */
+public class DerivedColumn extends AbstractColumn implements Column {
+ public DerivedColumn(Table table) {
+ super( table );
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String toDebugString() {
+ return getTable().toDebugString() + ".{derived-column}";
+ }
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Exportable.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Exportable.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Exportable.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,39 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+/**
+ * Contract for entities (in the ERD sense) which can be exported via <tt>CREATE</tt>, <tt>ALTER</tt>, etc
+ * statements.
+ *
+ * @author Steve Ebersole
+ */
+public interface Exportable {
+ /**
+ * Get a uniqueing identifier to make sure we are not exporting the same database structure multiple times.
+ *
+ * @return The exporting identifier.
+ */
+ public String getExportIdentifier();
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/ForeignKey.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/ForeignKey.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/ForeignKey.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,115 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+import java.util.List;
+import java.util.ArrayList;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public class ForeignKey implements Constraint {
+ private static final Logger log = LoggerFactory.getLogger( ForeignKey.class );
+
+ private final Table sourceTable;
+ private final Table targetTable;
+ private final String name;
+
+ private List/*<Column>*/ sourceColumns = new ArrayList();
+ private List/*<Column>*/ targetColumns;
+
+ public ForeignKey(Table sourceTable, Table targetTable, String name) {
+ this.sourceTable = sourceTable;
+ this.targetTable = targetTable;
+ this.name = name;
+ }
+
+ public ForeignKey(Table sourceTable, Table targetTable) {
+ this( sourceTable, targetTable, null );
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Table getTable() {
+ return getSourceTable();
+ }
+
+ public Table getSourceTable() {
+ return sourceTable;
+ }
+
+ public Table getTargetTable() {
+ return targetTable;
+ }
+
+ public List/*<Column>*/ getColumns() {
+ return getSourceColumns();
+ }
+
+ public List getSourceColumns() {
+ return sourceColumns;
+ }
+
+ public List getTargetColumns() {
+ return targetColumns == null
+ ? getTargetTable().getPrimaryKey().getColumns()
+ : targetColumns;
+ }
+
+ public void addColumnMapping(Column sourceColumn, Column targetColumn) {
+ if ( targetColumn == null ) {
+ if ( targetColumns != null ) {
+ if ( log.isWarnEnabled() ) {
+ log.warn(
+ "Attempt to map column [" + sourceColumn.toDebugString()
+ + "] to no target column after explicit target column(s) named for FK [name="
+ + getName() + "]"
+ );
+ }
+ }
+ }
+ else {
+ if ( targetColumns == null ) {
+ if ( !sourceColumns.isEmpty() ) {
+ log.warn(
+ "Column mapping mismatch as part of FK [table=" + getTable().toDebugString()
+ + ", name=" + getName() + "] while adding source column ["
+ + sourceColumn.toDebugString() + "]"
+ );
+ }
+ targetColumns = new ArrayList();
+ }
+ targetColumns.add( targetColumn );
+ }
+ sourceColumns.add( sourceColumn );
+ }
+
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Index.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Index.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Index.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,35 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public class Index extends AbstractColumnConstraint implements Constraint {
+ protected Index(Table table, String name) {
+ super( table, name );
+ }
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/LogicalTable.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/LogicalTable.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/LogicalTable.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,57 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+import java.util.Set;
+import java.util.HashSet;
+
+/**
+ * A <tt>data container</tt> defined by a <tt>SELECT</tt> statement. This translates into an inline view in the
+ * SQL statements: <code>select ... from (select ... from logical_table_table ...) ...</code>
+ *
+ * @author Steve Ebersole
+ */
+public class LogicalTable extends AbstractTable implements Table {
+ private final String select;
+ private Set synchronizedTableSpaces = java.util.Collections.EMPTY_SET;
+
+ public LogicalTable(String select) {
+ this.select = select;
+ }
+
+ public void addSynchronizedTableSpace(String space) {
+ if ( synchronizedTableSpaces == java.util.Collections.EMPTY_SET ) {
+ synchronizedTableSpaces = new HashSet();
+ }
+ synchronizedTableSpaces.add( space );
+ }
+
+ public Set getSpaces() {
+ return synchronizedTableSpaces;
+ }
+
+ public String toDebugString() {
+ return "{inline-view}";
+ }
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/PhysicalColumn.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/PhysicalColumn.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/PhysicalColumn.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,46 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public class PhysicalColumn extends AbstractColumn implements Column {
+ private final String name;
+
+ protected PhysicalColumn(Table table, String name) {
+ super( table );
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String toDebugString() {
+ return getTable().toDebugString() + '.' + getName();
+ }
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/PhysicalTable.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/PhysicalTable.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/PhysicalTable.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,58 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+import java.util.Set;
+
+/**
+ * Models the concept of a relational <tt>TABLE</tt> (or <tt>VIEW</tt>) database to which we map information.
+ *
+ * @author Gavin King
+ * @author Steve Ebersole
+ */
+public class PhysicalTable extends AbstractTable implements Table, Exportable {
+ private final String explicitSchema;
+ private final String explicitCatalog;
+ private final String name;
+ private final Set spaces;
+
+ public PhysicalTable(String explicitSchema, String explicitCatalog, String name) {
+ this.explicitSchema = explicitSchema;
+ this.explicitCatalog = explicitCatalog;
+ this.name = name;
+ this.spaces = java.util.Collections.singleton( name );
+ }
+
+ public String getExportIdentifier() {
+ return name;
+ }
+
+ public Set getSpaces() {
+ return spaces;
+ }
+
+ public String toDebugString() {
+ return name;
+ }
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/PrimaryKey.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/PrimaryKey.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/PrimaryKey.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,53 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+
+/**
+ * Models a table's primary key.
+ * <p/>
+ * NOTE : This need not be a physical primary key; we just mean a column or columns which uniquely identify rows in
+ * the table. Of course it is recommended to define proper integrity constraints, including primary keys.
+ *
+ * @author Steve Ebersole
+ */
+public class PrimaryKey extends AbstractColumnConstraint implements Constraint {
+ // IMPL NOTE : I override the name behavior here because:
+ // (1) primary keys are not required to be named.
+ // (2) because a primary key is required for each table, it is easier to allow setting the constraint name
+ // later in terms of building the metamodel
+ private String name;
+
+ public PrimaryKey(Table table) {
+ super( table, null );
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Table.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Table.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/Table.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,44 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+import java.util.Iterator;
+import java.util.Set;
+
+/**
+ * Contract for data containers (what the ANSI SQL spec calls "table specifications") to which we can map
+ * entity state.
+ *
+ * @author Steve Ebersole
+ */
+public interface Table {
+ public PrimaryKey getPrimaryKey();
+
+ public void addColumn(Column column);
+
+ public Iterator iterateColumns();
+ public Set getSpaces();
+
+ public String toDebugString();
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/UniqueKey.java
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/UniqueKey.java (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/UniqueKey.java 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,35 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.metadata.schema;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public class UniqueKey extends AbstractColumnConstraint implements Constraint {
+ protected UniqueKey(Table table, String name) {
+ super( table, name );
+ }
+}
Added: sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/package.html
===================================================================
--- sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/package.html (rev 0)
+++ sandbox/trunk/new-metadata/src/main/java/org/hibernate/metadata/schema/package.html 2009-11-12 20:52:13 UTC (rev 17967)
@@ -0,0 +1,31 @@
+<!--
+ ~ Hibernate, Relational Persistence for Idiomatic Java
+ ~
+ ~ Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ ~ third-party contributors as indicated by either @author tags or express
+ ~ copyright attribution statements applied by the authors. All
+ ~ third-party contributions are distributed under license by Red Hat Inc.
+ ~
+ ~ This copyrighted material is made available to anyone wishing to use, modify,
+ ~ copy, or redistribute it subject to the terms and conditions of the GNU
+ ~ Lesser General Public License, as published by the Free Software Foundation.
+ ~
+ ~ This program is distributed in the hope that it will be useful,
+ ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ ~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ ~ for more details.
+ ~
+ ~ You should have received a copy of the GNU Lesser General Public License
+ ~ along with this distribution; if not, write to:
+ ~ Free Software Foundation, Inc.
+ ~ 51 Franklin Street, Fifth Floor
+ ~ Boston, MA 02110-1301 USA
+ -->
+
+<html>
+<body>
+<p>
+ This package defines metadata modeling of a RDBMS schema.
+</p>
+</body>
+</html>
15 years, 1 month
Hibernate SVN: r17966 - sandbox/trunk/new-metadata.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2009-11-12 14:55:38 -0500 (Thu, 12 Nov 2009)
New Revision: 17966
Modified:
sandbox/trunk/new-metadata/
Log:
svn ignores
Property changes on: sandbox/trunk/new-metadata
___________________________________________________________________
Name: svn:ignore
+ target
local
*.ipr
*.iws
*.iml
.classpath
.project
.nbattrs
*.log
*.properties
.clover
.idea
15 years, 1 month
Hibernate SVN: r17965 - in core/branches/Branch_3_3: testsuite/src/test/java/org/hibernate/test/cfg and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2009-11-12 14:46:51 -0500 (Thu, 12 Nov 2009)
New Revision: 17965
Added:
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationSerializationTest.java
core/branches/Branch_3_3/testsuite/src/test/perf/org/hibernate/test/perf/ConfigurationPerformanceTest.java
Removed:
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationPerformanceTest.java
Modified:
core/branches/Branch_3_3/core/src/main/java/org/hibernate/cfg/Configuration.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/CacheableFileTest.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/ListenerTest.java
Log:
HHH-4569 - Split focus of ConfigurationPerformanceTest
Modified: core/branches/Branch_3_3/core/src/main/java/org/hibernate/cfg/Configuration.java
===================================================================
--- core/branches/Branch_3_3/core/src/main/java/org/hibernate/cfg/Configuration.java 2009-11-12 19:46:04 UTC (rev 17964)
+++ core/branches/Branch_3_3/core/src/main/java/org/hibernate/cfg/Configuration.java 2009-11-12 19:46:51 UTC (rev 17965)
@@ -384,70 +384,85 @@
* the non-cached file.
*/
public Configuration addCacheableFile(File xmlFile) throws MappingException {
+ File cachedFile = determineCachedDomFile( xmlFile );
+
try {
- File cachedFile = new File( xmlFile.getAbsolutePath() + ".bin" );
- org.dom4j.Document doc = null;
+ return addCacheableFileStrictly( xmlFile );
+ }
+ catch ( SerializationException e ) {
+ log.warn( "Could not deserialize cache file: " + cachedFile.getPath() + " : " + e );
+ }
+ catch ( FileNotFoundException e ) {
+ log.warn( "I/O reported cached file could not be found : " + cachedFile.getPath() + " : " + e );
+ }
- final boolean useCachedFile = xmlFile.exists() &&
- cachedFile.exists() &&
- xmlFile.lastModified() < cachedFile.lastModified();
+ if ( !xmlFile.exists() ) {
+ throw new MappingNotFoundException( "file", xmlFile.toString() );
+ }
- if ( useCachedFile ) {
- try {
- log.info( "Reading mappings from cache file: " + cachedFile );
- doc = ( org.dom4j.Document ) SerializationHelper.deserialize( new FileInputStream( cachedFile ) );
- }
- catch ( SerializationException e ) {
- log.warn( "Could not deserialize cache file: " + cachedFile.getPath(), e );
- }
- catch ( FileNotFoundException e ) {
- log.warn( "I/O reported cached file could not be found : " + cachedFile.getPath(), e );
- }
+ log.info( "Reading mappings from file: " + xmlFile );
+ List errors = new ArrayList();
+ try {
+ org.dom4j.Document doc = xmlHelper.createSAXReader( xmlFile.getAbsolutePath(), errors, entityResolver ).read( xmlFile );
+ if ( errors.size() != 0 ) {
+ throw new MappingException( "invalid mapping", ( Throwable ) errors.get( 0 ) );
}
- // if doc is null, then for whatever reason, the cached file cannot be used...
- if ( doc == null ) {
- if ( !xmlFile.exists() ) {
- throw new MappingNotFoundException( "file", xmlFile.toString() );
- }
-
- log.info( "Reading mappings from file: " + xmlFile );
- List errors = new ArrayList();
- try {
- doc = xmlHelper.createSAXReader( xmlFile.getAbsolutePath(), errors, entityResolver ).read( xmlFile );
- if ( errors.size() != 0 ) {
- throw new MappingException( "invalid mapping", ( Throwable ) errors.get( 0 ) );
- }
- }
- catch( DocumentException e){
- throw new MappingException( "invalid mapping", e );
- }
-
- try {
- log.debug( "Writing cache file for: " + xmlFile + " to: " + cachedFile );
- SerializationHelper.serialize( ( Serializable ) doc, new FileOutputStream( cachedFile ) );
- }
- catch ( SerializationException e ) {
- log.warn( "Could not write cached file: " + cachedFile, e );
- }
- catch ( FileNotFoundException e ) {
- log.warn( "I/O reported error writing cached file : " + cachedFile.getPath(), e );
- }
+ try {
+ log.debug( "Writing cache file for: " + xmlFile + " to: " + cachedFile );
+ SerializationHelper.serialize( ( Serializable ) doc, new FileOutputStream( cachedFile ) );
}
+ catch ( SerializationException e ) {
+ log.warn( "Could not write cached file: " + cachedFile, e );
+ }
+ catch ( FileNotFoundException e ) {
+ log.warn( "I/O reported error writing cached file : " + cachedFile.getPath(), e );
+ }
add( doc );
- return this;
-
}
- catch ( InvalidMappingException e ) {
- throw e;
+ catch( DocumentException e){
+ throw new MappingException( "invalid mapping", e );
}
- catch ( MappingNotFoundException e ) {
- throw e;
+
+ return this;
+ }
+
+ private File determineCachedDomFile(File xmlFile) {
+ return new File( xmlFile.getAbsolutePath() + ".bin" );
+ }
+
+ /**
+ * <b>INTENDED FOR TESTSUITE USE ONLY!</b>
+ * <p/>
+ * Much like {@link addCacheableFile(File)} except that here we will fail immediately if
+ * the cache version cannot be found or used for whatever reason
+ *
+ * @param xmlFile The xml file, not the bin!
+ *
+ * @return The dom "deserialized" from the cached file.
+ *
+ * @throws MappingException Indicates a problem in the underlyiong call to {@link #add(org.dom4j.Document)}
+ * @throws SerializationException Indicates a problem deserializing the cached dom tree
+ * @throws FileNotFoundException Indicates that the cached file was not found or was not usable.
+ */
+ public Configuration addCacheableFileStrictly(File xmlFile)
+ throws MappingException, SerializationException, FileNotFoundException {
+ final File cachedFile = determineCachedDomFile( xmlFile );
+
+ final boolean useCachedFile = xmlFile.exists()
+ && cachedFile.exists()
+ && xmlFile.lastModified() < cachedFile.lastModified();
+
+ if ( ! useCachedFile ) {
+ throw new FileNotFoundException( "Cached file could not be found or could not be used" );
}
- catch ( Exception e ) {
- throw new InvalidMappingException( "file", xmlFile.toString(), e );
- }
+
+ log.info( "Reading mappings from cache file: " + cachedFile );
+ org.dom4j.Document document =
+ ( org.dom4j.Document ) SerializationHelper.deserialize( new FileInputStream( cachedFile ) );
+ add( document );
+ return this;
}
/**
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/CacheableFileTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/CacheableFileTest.java 2009-11-12 19:46:04 UTC (rev 17964)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/CacheableFileTest.java 2009-11-12 19:46:51 UTC (rev 17965)
@@ -1,3 +1,26 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
package org.hibernate.test.cfg;
import java.io.File;
@@ -4,17 +27,18 @@
import org.hibernate.cfg.Configuration;
import org.hibernate.junit.UnitTestCase;
+import org.hibernate.util.SerializationHelper;
/**
- * {@inheritDoc}
+ * Tests using of cacheable configuration files.
*
* @author Steve Ebersole
*/
public class CacheableFileTest extends UnitTestCase {
-
public static final String MAPPING = "org/hibernate/test/cfg/Cacheable.hbm.xml";
private File mappingFile;
+ private File mappingBinFile;
public CacheableFileTest(String string) {
super( string );
@@ -24,21 +48,31 @@
super.setUp();
mappingFile = new File( getClass().getClassLoader().getResource( MAPPING ).toURI() );
assertTrue( mappingFile.exists() );
- File cached = new File( mappingFile.getParentFile(), mappingFile.getName() + ".bin" );
- if ( cached.exists() ) {
- cached.delete();
+ mappingBinFile = new File( mappingFile.getParentFile(), mappingFile.getName() + ".bin" );
+ if ( mappingBinFile.exists() ) {
+ //noinspection ResultOfMethodCallIgnored
+ mappingBinFile.delete();
}
}
protected void tearDown() throws Exception {
+ if ( mappingBinFile != null && mappingBinFile.exists() ) {
+ // be nice
+ //noinspection ResultOfMethodCallIgnored
+ mappingBinFile.delete();
+ }
+ mappingBinFile = null;
mappingFile = null;
super.tearDown();
}
- public void testCachedFiles() {
- Configuration cfg = new Configuration();
- cfg.addCacheableFile( mappingFile );
- Configuration cfg2 = new Configuration();
- cfg2.addCacheableFile( mappingFile );
+ public void testCachedFiles() throws Exception {
+ assertFalse( mappingBinFile.exists() );
+ // This call should create the cached file
+ new Configuration().addCacheableFile( mappingFile );
+ assertTrue( mappingBinFile.exists() );
+
+ Configuration cfg = new Configuration().addCacheableFileStrictly( mappingFile );
+ SerializationHelper.clone( cfg );
}
}
Deleted: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationPerformanceTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationPerformanceTest.java 2009-11-12 19:46:04 UTC (rev 17964)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationPerformanceTest.java 2009-11-12 19:46:51 UTC (rev 17965)
@@ -1,353 +0,0 @@
-/*
- * Copyright (c) 2007, Red Hat Middleware, LLC. All rights reserved.
- *
- * This copyrighted material is made available to anyone wishing to use, modify,
- * copy, or redistribute it subject to the terms and conditions of the GNU
- * Lesser General Public License, v. 2.1. This program is distributed in the
- * hope that it will be useful, but WITHOUT A WARRANTY; without even the implied
- * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details. You should have received a
- * copy of the GNU Lesser General Public License, v.2.1 along with this
- * distribution; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Red Hat Author(s): Max Andersen, Steve Ebersole
- */
-package org.hibernate.test.cfg;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.PrintWriter;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-import junit.textui.TestRunner;
-
-import org.hibernate.SessionFactory;
-import org.hibernate.cfg.Configuration;
-import org.hibernate.cfg.Environment;
-import org.hibernate.classic.Session;
-import org.hibernate.junit.UnitTestCase;
-
-/**
- * Test of configuration, specifically "cacheable files".
- *
- * @author Max Andersen
- * @author Steve Ebersole
- */
-public class ConfigurationPerformanceTest extends UnitTestCase {
-
- private final String workPackageName = "org.hibernate.test.cfg.work";
- private File compilationBaseDir;
- private File mappingBaseDir;
- private File workPackageDir;
-
- protected void setUp() throws Exception {
- compilationBaseDir = getTestComplileDirectory();
- mappingBaseDir = new File( compilationBaseDir, "org/hibernate/test" );
- workPackageDir = new File( compilationBaseDir, workPackageName.replace( '.', '/' ) );
- if ( workPackageDir.exists() ) {
- //noinspection ResultOfMethodCallIgnored
- workPackageDir.delete();
- }
- boolean created = workPackageDir.mkdirs();
- if ( !created ) {
- System.err.println( "Unable to create workPackageDir during setup" );
- }
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- private static final String[] FILES = new String[] {
- "legacy/ABC.hbm.xml",
- "legacy/ABCExtends.hbm.xml",
- "legacy/Baz.hbm.xml",
- "legacy/Blobber.hbm.xml",
- "legacy/Broken.hbm.xml",
- "legacy/Category.hbm.xml",
- "legacy/Circular.hbm.xml",
- "legacy/Commento.hbm.xml",
- "legacy/ComponentNotNullMaster.hbm.xml",
- "legacy/Componentizable.hbm.xml",
- "legacy/Container.hbm.xml",
- "legacy/Custom.hbm.xml",
- "legacy/CustomSQL.hbm.xml",
- "legacy/Eye.hbm.xml",
- "legacy/Fee.hbm.xml",
- "legacy/Fo.hbm.xml",
- "legacy/FooBar.hbm.xml",
- "legacy/Fum.hbm.xml",
- "legacy/Fumm.hbm.xml",
- "legacy/Glarch.hbm.xml",
- "legacy/Holder.hbm.xml",
- "legacy/IJ2.hbm.xml",
- "legacy/Immutable.hbm.xml",
- "legacy/Location.hbm.xml",
- "legacy/Many.hbm.xml",
- "legacy/Map.hbm.xml",
- "legacy/Marelo.hbm.xml",
- "legacy/MasterDetail.hbm.xml",
- "legacy/Middle.hbm.xml",
- "legacy/Multi.hbm.xml",
- "legacy/MultiExtends.hbm.xml",
- "legacy/Nameable.hbm.xml",
- "legacy/One.hbm.xml",
- "legacy/ParentChild.hbm.xml",
- "legacy/Qux.hbm.xml",
- "legacy/Simple.hbm.xml",
- "legacy/SingleSeveral.hbm.xml",
- "legacy/Stuff.hbm.xml",
- "legacy/UpDown.hbm.xml",
- "legacy/Vetoer.hbm.xml",
- "legacy/WZ.hbm.xml",
- };
-
- public ConfigurationPerformanceTest(String string) {
- super( string );
- }
-
- public static Test suite() {
- return new TestSuite( ConfigurationPerformanceTest.class );
- }
-
- public static void main(String[] args) throws Exception {
- TestRunner.run( suite() );
- }
-
- public void testLoadingAndSerializationOfConfiguration() throws Throwable {
- final File cachedCfgFile = new File( workPackageDir, "hibernate.cfg.bin" );
- try {
- System.err.println( "#### Preparing serialized configuration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" );
- prepareSerializedConfiguration( mappingBaseDir, FILES, cachedCfgFile );
- System.err.println( "#### Preparing serialized configuration complete ~~~~~~~~~~~~~~~~~~~~~~~~" );
-
- // now make sure we can reload the serialized configuration...
- System.err.println( "#### Reading serialized configuration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" );
- readSerializedConfiguration( cachedCfgFile );
- System.err.println( "#### Reading serialized configuration complete ~~~~~~~~~~~~~~~~~~~~~~~~~~" );
- }
- finally {
- System.err.println( "###CLEANING UP###" );
- if ( ! cachedCfgFile.delete() ) {
- System.err.println( "Unable to cleanup file " + cachedCfgFile.getAbsolutePath() );
- }
-
- //noinspection ForLoopReplaceableByForEach
- for ( int i = 0; i < FILES.length; i++ ) {
- File file = new File( mappingBaseDir, FILES[i] + ".bin" );
- if ( ! file.delete() ) {
- System.err.println( "Unable to cleanup file " + file.getAbsolutePath() );
- }
- }
- }
- }
-
- public void testSessionFactoryCreationTime() throws Throwable {
- generateTestFiles();
- if ( !workPackageDir.exists() ) {
- System.err.println( workPackageDir.getAbsoluteFile() + " not found" );
- return;
- }
-
- long start = System.currentTimeMillis();
- Configuration configuration = buildConfigurationFromCacheableFiles(
- workPackageDir,
- workPackageDir.list(
- new FilenameFilter() {
- public boolean accept(File dir, String name) {
- return name.endsWith( ".hbm.xml" );
- }
- }
- )
- );
- SessionFactory factory = configuration.buildSessionFactory();
- long initial = System.currentTimeMillis() - start;
- factory.close();
-
- start = System.currentTimeMillis();
- configuration = buildConfigurationFromCacheableFiles(
- workPackageDir,
- workPackageDir.list(
- new FilenameFilter() {
- public boolean accept(File dir, String name) {
- return name.endsWith( ".hbm.xml" );
- }
- }
- )
- );
- factory = configuration.buildSessionFactory();
- long subsequent = System.currentTimeMillis() - start;
-
- // Let's make sure the mappings were read in correctly (in termas of they are operational).
- Session session = factory.openSession();
- session.beginTransaction();
- session.createQuery( "from Test1" ).list();
- session.getTransaction().commit();
- session.close();
- factory.close();
-
- System.err.println( "Initial SessionFactory load time : " + initial );
- System.err.println( "Subsequent SessionFactory load time : " + subsequent );
- }
-
- private void prepareSerializedConfiguration(
- File mappingFileBase,
- String[] files,
- File cachedCfgFile) throws IOException {
- Configuration cfg = buildConfigurationFromCacheableFiles( mappingFileBase, files );
-
- ObjectOutputStream os = new ObjectOutputStream( new FileOutputStream( cachedCfgFile ) );
- os.writeObject( cfg ); // need to serialize Configuration *before* building sf since it would require non-mappings and cfg types to be serializable
- os.flush();
- os.close();
-
- timeBuildingSessionFactory( cfg );
- }
-
- private Configuration buildConfigurationFromCacheableFiles(File mappingFileBase, String[] files) {
- long start = System.currentTimeMillis();
- Configuration cfg = new Configuration();
- cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
- System.err.println(
- "Created configuration: " + ( System.currentTimeMillis() - start ) / 1000.0 + " sec."
- );
-
- start = System.currentTimeMillis();
- //noinspection ForLoopReplaceableByForEach
- for ( int i = 0; i < files.length; i++ ) {
- cfg.addCacheableFile( new File( mappingFileBase, files[i] ) );
- }
- System.err.println(
- "Added " + ( files.length ) + " resources: " +
- ( System.currentTimeMillis() - start ) / 1000.0 + " sec."
- );
- return cfg;
- }
-
- private void timeBuildingSessionFactory(Configuration configuration) {
- long start = System.currentTimeMillis();
- System.err.println( "Start build of session factory" );
- SessionFactory factory = configuration.buildSessionFactory();
- System.err.println( "Built session factory :" + ( System.currentTimeMillis() - start ) / 1000.0 + " sec." );
- factory.close();
- }
-
- private void readSerializedConfiguration(File cachedCfgFile) throws ClassNotFoundException, IOException {
- long start = System.currentTimeMillis();
- ObjectInputStream is = new ObjectInputStream( new FileInputStream( cachedCfgFile ) );
- Configuration cfg = ( Configuration ) is.readObject();
- is.close();
- System.err.println(
- "Loaded serializable configuration :" +
- ( System.currentTimeMillis() - start ) / 1000.0 + " sec."
- );
-
- timeBuildingSessionFactory( cfg );
- }
-
- public void generateTestFiles() throws Throwable {
- String filesToCompile = "";
- for ( int count = 0; count < 100; count++ ) {
- String name = "Test" + count;
- File javaFile = new File( workPackageDir, name + ".java" );
- File hbmFile = new File( workPackageDir, name + ".hbm.xml" );
- filesToCompile += ( javaFile.getAbsolutePath() + " " );
-
- System.out.println( "Generating " + javaFile.getAbsolutePath() );
- PrintWriter javaWriter = null;
- PrintWriter hbmWriter = null;
- try {
- javaWriter = new PrintWriter( new FileWriter( javaFile ) );
- hbmWriter = new PrintWriter( new FileWriter( hbmFile ) );
-
- javaWriter.println( "package " + workPackageName + ";" );
- hbmWriter.println(
- "<?xml version=\"1.0\"?>\r\n" +
- "<!DOCTYPE hibernate-mapping PUBLIC \r\n" +
- " \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\r\n" +
- " \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\r\n"
- );
-
- hbmWriter.println( "<hibernate-mapping package=\"" + workPackageName + "\">" );
-
- javaWriter.println( "public class " + name + " {" );
- javaWriter.println( " static { System.out.println(\"" + name + " initialized!\"); }" );
- hbmWriter.println( "<class name=\"" + name + "\">" );
-
- hbmWriter.println( "<id type=\"long\"><generator class=\"assigned\"/></id>" );
- for ( int propCount = 0; propCount < 100; propCount++ ) {
- String propName = "Prop" + propCount;
-
- writeJavaProperty( javaWriter, propName );
-
- hbmWriter.println( "<property name=\"" + propName + "\" type=\"string\"/>" );
-
- }
- hbmWriter.println( "</class>" );
- javaWriter.println( "}" );
- hbmWriter.println( "</hibernate-mapping>" );
- }
- finally {
- if ( javaWriter != null ) {
- javaWriter.flush();
- javaWriter.close();
- }
- if ( hbmWriter != null ) {
- hbmWriter.flush();
- hbmWriter.close();
- }
- }
- }
-
- String javac = "javac -version -d " + compilationBaseDir + " " + filesToCompile;
- System.err.println( "JAVAC : " + javac );
- Process process = Runtime.getRuntime().exec( javac );
- process.waitFor();
- System.err.println( "********************* JAVAC OUTPUT **********************" );
- pullStream( process.getInputStream() );
- System.err.println( "---------------------------------------------------------" );
- pullStream( process.getErrorStream() );
- System.err.println( "*********************************************************" );
- }
-
- private void pullStream(InputStream stream) throws IOException {
- if ( stream == null || stream.available() <= 0 ) {
- return;
- }
- byte[] buffer = new byte[256];
- while ( true ) {
- int read = stream.read( buffer );
- if ( read == -1 ) {
- break;
- }
- System.err.write( buffer, 0, read );
- }
-// System.err.println( "" );
- }
-
- private void writeJavaProperty(PrintWriter javaWriter, String propName) {
- javaWriter.println( " String " + propName + ";" );
- javaWriter.println( " String get" + propName + "() { return " + propName + "; }" );
- javaWriter.println( " void set" + propName + "(String newVal) { " + propName + "=newVal; }" );
- }
-
- private File getTestComplileDirectory() {
- String resourceName = "org/hibernate/test/legacy/ABC.hbm.xml";
- String prefix = getClass().getClassLoader().getResource( resourceName ).getFile();
- prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // ABC.hbm.xml
- prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // legacy/
- prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // test/
- prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // hibernate/
- prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // org/
- return new File( prefix + '/' );
- }
-}
Added: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationSerializationTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationSerializationTest.java (rev 0)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationSerializationTest.java 2009-11-12 19:46:51 UTC (rev 17965)
@@ -0,0 +1,106 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.cfg;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.hibernate.junit.UnitTestCase;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.util.SerializationHelper;
+import org.hibernate.SessionFactory;
+
+/**
+ * Copied over mostly from ConfigurationPerformanceTest
+ *
+ * @author Steve Ebersole
+ * @author Max Andersen
+ */
+public class ConfigurationSerializationTest extends UnitTestCase {
+ public ConfigurationSerializationTest(String string) {
+ super( string );
+ }
+
+ public static Test suite() {
+ return new TestSuite( ConfigurationSerializationTest.class );
+ }
+
+ private static final String[] FILES = new String[] {
+ "legacy/ABC.hbm.xml",
+ "legacy/ABCExtends.hbm.xml",
+ "legacy/Baz.hbm.xml",
+ "legacy/Blobber.hbm.xml",
+ "legacy/Broken.hbm.xml",
+ "legacy/Category.hbm.xml",
+ "legacy/Circular.hbm.xml",
+ "legacy/Commento.hbm.xml",
+ "legacy/ComponentNotNullMaster.hbm.xml",
+ "legacy/Componentizable.hbm.xml",
+ "legacy/Container.hbm.xml",
+ "legacy/Custom.hbm.xml",
+ "legacy/CustomSQL.hbm.xml",
+ "legacy/Eye.hbm.xml",
+ "legacy/Fee.hbm.xml",
+ "legacy/Fo.hbm.xml",
+ "legacy/FooBar.hbm.xml",
+ "legacy/Fum.hbm.xml",
+ "legacy/Fumm.hbm.xml",
+ "legacy/Glarch.hbm.xml",
+ "legacy/Holder.hbm.xml",
+ "legacy/IJ2.hbm.xml",
+ "legacy/Immutable.hbm.xml",
+ "legacy/Location.hbm.xml",
+ "legacy/Many.hbm.xml",
+ "legacy/Map.hbm.xml",
+ "legacy/Marelo.hbm.xml",
+ "legacy/MasterDetail.hbm.xml",
+ "legacy/Middle.hbm.xml",
+ "legacy/Multi.hbm.xml",
+ "legacy/MultiExtends.hbm.xml",
+ "legacy/Nameable.hbm.xml",
+ "legacy/One.hbm.xml",
+ "legacy/ParentChild.hbm.xml",
+ "legacy/Qux.hbm.xml",
+ "legacy/Simple.hbm.xml",
+ "legacy/SingleSeveral.hbm.xml",
+ "legacy/Stuff.hbm.xml",
+ "legacy/UpDown.hbm.xml",
+ "legacy/Vetoer.hbm.xml",
+ "legacy/WZ.hbm.xml",
+ };
+
+ public void testConfiguraionSerializability() {
+ Configuration cfg = new Configuration();
+ for ( String file : FILES ) {
+ cfg.addResource( "org/hibernate/test/" + file );
+ }
+
+ byte[] bytes = SerializationHelper.serialize( cfg );
+ cfg = ( Configuration ) SerializationHelper.deserialize( bytes );
+
+ // try to build SF
+ SessionFactory factory = cfg.buildSessionFactory();
+ factory.close();
+ }
+}
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/ListenerTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/ListenerTest.java 2009-11-12 19:46:04 UTC (rev 17964)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/ListenerTest.java 2009-11-12 19:46:51 UTC (rev 17965)
@@ -1,3 +1,26 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
package org.hibernate.test.cfg;
import java.util.Set;
Copied: core/branches/Branch_3_3/testsuite/src/test/perf/org/hibernate/test/perf/ConfigurationPerformanceTest.java (from rev 16994, core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationPerformanceTest.java)
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/perf/org/hibernate/test/perf/ConfigurationPerformanceTest.java (rev 0)
+++ core/branches/Branch_3_3/testsuite/src/test/perf/org/hibernate/test/perf/ConfigurationPerformanceTest.java 2009-11-12 19:46:51 UTC (rev 17965)
@@ -0,0 +1,248 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.perf;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+import junit.textui.TestRunner;
+
+import org.hibernate.SessionFactory;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.classic.Session;
+import org.hibernate.junit.UnitTestCase;
+
+/**
+ * Test of configuration, specifically "cacheable files".
+ *
+ * @author Max Andersen
+ * @author Steve Ebersole
+ */
+public class ConfigurationPerformanceTest extends UnitTestCase {
+
+ private final String workPackageName = "org.hibernate.test.cfg.work";
+ private File compilationBaseDir;
+ private File workPackageDir;
+
+ protected void setUp() throws Exception {
+ compilationBaseDir = getTestComplileDirectory();
+ workPackageDir = new File( compilationBaseDir, workPackageName.replace( '.', '/' ) );
+ if ( workPackageDir.exists() ) {
+ //noinspection ResultOfMethodCallIgnored
+ workPackageDir.delete();
+ }
+ boolean created = workPackageDir.mkdirs();
+ if ( !created ) {
+ System.err.println( "Unable to create workPackageDir during setup" );
+ }
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public ConfigurationPerformanceTest(String string) {
+ super( string );
+ }
+
+ public static Test suite() {
+ return new TestSuite( ConfigurationPerformanceTest.class );
+ }
+
+ public static void main(String[] args) throws Exception {
+ TestRunner.run( suite() );
+ }
+
+ public void testSessionFactoryCreationTime() throws Throwable {
+ generateTestFiles();
+ if ( !workPackageDir.exists() ) {
+ System.err.println( workPackageDir.getAbsoluteFile() + " not found" );
+ return;
+ }
+
+ long start = System.currentTimeMillis();
+ Configuration configuration = buildConfigurationFromCacheableFiles(
+ workPackageDir,
+ workPackageDir.list(
+ new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return name.endsWith( ".hbm.xml" );
+ }
+ }
+ )
+ );
+ SessionFactory factory = configuration.buildSessionFactory();
+ long initial = System.currentTimeMillis() - start;
+ factory.close();
+
+ start = System.currentTimeMillis();
+ configuration = buildConfigurationFromCacheableFiles(
+ workPackageDir,
+ workPackageDir.list(
+ new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return name.endsWith( ".hbm.xml" );
+ }
+ }
+ )
+ );
+ factory = configuration.buildSessionFactory();
+ long subsequent = System.currentTimeMillis() - start;
+
+ // Let's make sure the mappings were read in correctly (in termas of they are operational).
+ Session session = factory.openSession();
+ session.beginTransaction();
+ session.createQuery( "from Test1" ).list();
+ session.getTransaction().commit();
+ session.close();
+ factory.close();
+
+ System.err.println( "Initial SessionFactory load time : " + initial );
+ System.err.println( "Subsequent SessionFactory load time : " + subsequent );
+ }
+
+ private Configuration buildConfigurationFromCacheableFiles(File mappingFileBase, String[] files) {
+ long start = System.currentTimeMillis();
+ Configuration cfg = new Configuration();
+ cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
+ System.err.println(
+ "Created configuration: " + ( System.currentTimeMillis() - start ) / 1000.0 + " sec."
+ );
+
+ start = System.currentTimeMillis();
+ //noinspection ForLoopReplaceableByForEach
+ for ( int i = 0; i < files.length; i++ ) {
+ cfg.addCacheableFile( new File( mappingFileBase, files[i] ) );
+ }
+ System.err.println(
+ "Added " + ( files.length ) + " resources: " +
+ ( System.currentTimeMillis() - start ) / 1000.0 + " sec."
+ );
+ return cfg;
+ }
+
+ public void generateTestFiles() throws Throwable {
+ String filesToCompile = "";
+ for ( int count = 0; count < 100; count++ ) {
+ String name = "Test" + count;
+ File javaFile = new File( workPackageDir, name + ".java" );
+ File hbmFile = new File( workPackageDir, name + ".hbm.xml" );
+ filesToCompile += ( javaFile.getAbsolutePath() + " " );
+
+ System.out.println( "Generating " + javaFile.getAbsolutePath() );
+ PrintWriter javaWriter = null;
+ PrintWriter hbmWriter = null;
+ try {
+ javaWriter = new PrintWriter( new FileWriter( javaFile ) );
+ hbmWriter = new PrintWriter( new FileWriter( hbmFile ) );
+
+ javaWriter.println( "package " + workPackageName + ";" );
+ hbmWriter.println(
+ "<?xml version=\"1.0\"?>\r\n" +
+ "<!DOCTYPE hibernate-mapping PUBLIC \r\n" +
+ " \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\r\n" +
+ " \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\r\n"
+ );
+
+ hbmWriter.println( "<hibernate-mapping package=\"" + workPackageName + "\">" );
+
+ javaWriter.println( "public class " + name + " {" );
+ javaWriter.println( " static { System.out.println(\"" + name + " initialized!\"); }" );
+ hbmWriter.println( "<class name=\"" + name + "\">" );
+
+ hbmWriter.println( "<id type=\"long\"><generator class=\"assigned\"/></id>" );
+ for ( int propCount = 0; propCount < 100; propCount++ ) {
+ String propName = "Prop" + propCount;
+
+ writeJavaProperty( javaWriter, propName );
+
+ hbmWriter.println( "<property name=\"" + propName + "\" type=\"string\"/>" );
+
+ }
+ hbmWriter.println( "</class>" );
+ javaWriter.println( "}" );
+ hbmWriter.println( "</hibernate-mapping>" );
+ }
+ finally {
+ if ( javaWriter != null ) {
+ javaWriter.flush();
+ javaWriter.close();
+ }
+ if ( hbmWriter != null ) {
+ hbmWriter.flush();
+ hbmWriter.close();
+ }
+ }
+ }
+
+ String javac = "javac -version -d " + compilationBaseDir + " " + filesToCompile;
+ System.err.println( "JAVAC : " + javac );
+ Process process = Runtime.getRuntime().exec( javac );
+ process.waitFor();
+ System.err.println( "********************* JAVAC OUTPUT **********************" );
+ pullStream( process.getInputStream() );
+ System.err.println( "---------------------------------------------------------" );
+ pullStream( process.getErrorStream() );
+ System.err.println( "*********************************************************" );
+ }
+
+ private void pullStream(InputStream stream) throws IOException {
+ if ( stream == null || stream.available() <= 0 ) {
+ return;
+ }
+ byte[] buffer = new byte[256];
+ while ( true ) {
+ int read = stream.read( buffer );
+ if ( read == -1 ) {
+ break;
+ }
+ System.err.write( buffer, 0, read );
+ }
+// System.err.println( "" );
+ }
+
+ private void writeJavaProperty(PrintWriter javaWriter, String propName) {
+ javaWriter.println( " String " + propName + ";" );
+ javaWriter.println( " String get" + propName + "() { return " + propName + "; }" );
+ javaWriter.println( " void set" + propName + "(String newVal) { " + propName + "=newVal; }" );
+ }
+
+ private File getTestComplileDirectory() {
+ String resourceName = "org/hibernate/test/legacy/ABC.hbm.xml";
+ String prefix = getClass().getClassLoader().getResource( resourceName ).getFile();
+ prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // ABC.hbm.xml
+ prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // legacy/
+ prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // test/
+ prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // hibernate/
+ prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // org/
+ return new File( prefix + '/' );
+ }
+}
15 years, 1 month
Hibernate SVN: r17964 - in core/trunk: testsuite/src/test/java/org/hibernate/test/cfg and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2009-11-12 14:46:04 -0500 (Thu, 12 Nov 2009)
New Revision: 17964
Added:
core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationSerializationTest.java
core/trunk/testsuite/src/test/perf/org/hibernate/test/perf/ConfigurationPerformanceTest.java
Removed:
core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationPerformanceTest.java
Modified:
core/trunk/core/src/main/java/org/hibernate/cfg/Configuration.java
core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/CacheableFileTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/ListenerTest.java
Log:
HHH-4569 - Split focus of ConfigurationPerformanceTest
Modified: core/trunk/core/src/main/java/org/hibernate/cfg/Configuration.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/cfg/Configuration.java 2009-11-12 16:17:12 UTC (rev 17963)
+++ core/trunk/core/src/main/java/org/hibernate/cfg/Configuration.java 2009-11-12 19:46:04 UTC (rev 17964)
@@ -424,70 +424,85 @@
* the non-cached file.
*/
public Configuration addCacheableFile(File xmlFile) throws MappingException {
+ File cachedFile = determineCachedDomFile( xmlFile );
+
try {
- File cachedFile = new File( xmlFile.getAbsolutePath() + ".bin" );
- org.dom4j.Document doc = null;
+ return addCacheableFileStrictly( xmlFile );
+ }
+ catch ( SerializationException e ) {
+ log.warn( "Could not deserialize cache file: " + cachedFile.getPath() + " : " + e );
+ }
+ catch ( FileNotFoundException e ) {
+ log.warn( "I/O reported cached file could not be found : " + cachedFile.getPath() + " : " + e );
+ }
- final boolean useCachedFile = xmlFile.exists() &&
- cachedFile.exists() &&
- xmlFile.lastModified() < cachedFile.lastModified();
+ if ( !xmlFile.exists() ) {
+ throw new MappingNotFoundException( "file", xmlFile.toString() );
+ }
- if ( useCachedFile ) {
- try {
- log.info( "Reading mappings from cache file: " + cachedFile );
- doc = ( org.dom4j.Document ) SerializationHelper.deserialize( new FileInputStream( cachedFile ) );
- }
- catch ( SerializationException e ) {
- log.warn( "Could not deserialize cache file: " + cachedFile.getPath(), e );
- }
- catch ( FileNotFoundException e ) {
- log.warn( "I/O reported cached file could not be found : " + cachedFile.getPath(), e );
- }
+ log.info( "Reading mappings from file: " + xmlFile );
+ List errors = new ArrayList();
+ try {
+ org.dom4j.Document doc = xmlHelper.createSAXReader( xmlFile.getAbsolutePath(), errors, entityResolver ).read( xmlFile );
+ if ( errors.size() != 0 ) {
+ throw new MappingException( "invalid mapping", ( Throwable ) errors.get( 0 ) );
}
- // if doc is null, then for whatever reason, the cached file cannot be used...
- if ( doc == null ) {
- if ( !xmlFile.exists() ) {
- throw new MappingNotFoundException( "file", xmlFile.toString() );
- }
-
- log.info( "Reading mappings from file: " + xmlFile );
- List errors = new ArrayList();
- try {
- doc = xmlHelper.createSAXReader( xmlFile.getAbsolutePath(), errors, entityResolver ).read( xmlFile );
- if ( errors.size() != 0 ) {
- throw new MappingException( "invalid mapping", ( Throwable ) errors.get( 0 ) );
- }
- }
- catch( DocumentException e){
- throw new MappingException( "invalid mapping", e );
- }
-
- try {
- log.debug( "Writing cache file for: " + xmlFile + " to: " + cachedFile );
- SerializationHelper.serialize( ( Serializable ) doc, new FileOutputStream( cachedFile ) );
- }
- catch ( SerializationException e ) {
- log.warn( "Could not write cached file: " + cachedFile, e );
- }
- catch ( FileNotFoundException e ) {
- log.warn( "I/O reported error writing cached file : " + cachedFile.getPath(), e );
- }
+ try {
+ log.debug( "Writing cache file for: " + xmlFile + " to: " + cachedFile );
+ SerializationHelper.serialize( ( Serializable ) doc, new FileOutputStream( cachedFile ) );
}
+ catch ( SerializationException e ) {
+ log.warn( "Could not write cached file: " + cachedFile, e );
+ }
+ catch ( FileNotFoundException e ) {
+ log.warn( "I/O reported error writing cached file : " + cachedFile.getPath(), e );
+ }
add( doc );
- return this;
-
}
- catch ( InvalidMappingException e ) {
- throw e;
+ catch( DocumentException e){
+ throw new MappingException( "invalid mapping", e );
}
- catch ( MappingNotFoundException e ) {
- throw e;
+
+ return this;
+ }
+
+ private File determineCachedDomFile(File xmlFile) {
+ return new File( xmlFile.getAbsolutePath() + ".bin" );
+ }
+
+ /**
+ * <b>INTENDED FOR TESTSUITE USE ONLY!</b>
+ * <p/>
+ * Much like {@link addCacheableFile(File)} except that here we will fail immediately if
+ * the cache version cannot be found or used for whatever reason
+ *
+ * @param xmlFile The xml file, not the bin!
+ *
+ * @return The dom "deserialized" from the cached file.
+ *
+ * @throws MappingException Indicates a problem in the underlyiong call to {@link #add(org.dom4j.Document)}
+ * @throws SerializationException Indicates a problem deserializing the cached dom tree
+ * @throws FileNotFoundException Indicates that the cached file was not found or was not usable.
+ */
+ public Configuration addCacheableFileStrictly(File xmlFile)
+ throws MappingException, SerializationException, FileNotFoundException {
+ final File cachedFile = determineCachedDomFile( xmlFile );
+
+ final boolean useCachedFile = xmlFile.exists()
+ && cachedFile.exists()
+ && xmlFile.lastModified() < cachedFile.lastModified();
+
+ if ( ! useCachedFile ) {
+ throw new FileNotFoundException( "Cached file could not be found or could not be used" );
}
- catch ( Exception e ) {
- throw new InvalidMappingException( "file", xmlFile.toString(), e );
- }
+
+ log.info( "Reading mappings from cache file: " + cachedFile );
+ org.dom4j.Document document =
+ ( org.dom4j.Document ) SerializationHelper.deserialize( new FileInputStream( cachedFile ) );
+ add( document );
+ return this;
}
/**
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/CacheableFileTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/CacheableFileTest.java 2009-11-12 16:17:12 UTC (rev 17963)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/CacheableFileTest.java 2009-11-12 19:46:04 UTC (rev 17964)
@@ -1,3 +1,26 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
package org.hibernate.test.cfg;
import java.io.File;
@@ -4,17 +27,18 @@
import org.hibernate.cfg.Configuration;
import org.hibernate.junit.UnitTestCase;
+import org.hibernate.util.SerializationHelper;
/**
- * {@inheritDoc}
+ * Tests using of cacheable configuration files.
*
* @author Steve Ebersole
*/
public class CacheableFileTest extends UnitTestCase {
-
public static final String MAPPING = "org/hibernate/test/cfg/Cacheable.hbm.xml";
private File mappingFile;
+ private File mappingBinFile;
public CacheableFileTest(String string) {
super( string );
@@ -24,21 +48,31 @@
super.setUp();
mappingFile = new File( getClass().getClassLoader().getResource( MAPPING ).toURI() );
assertTrue( mappingFile.exists() );
- File cached = new File( mappingFile.getParentFile(), mappingFile.getName() + ".bin" );
- if ( cached.exists() ) {
- cached.delete();
+ mappingBinFile = new File( mappingFile.getParentFile(), mappingFile.getName() + ".bin" );
+ if ( mappingBinFile.exists() ) {
+ //noinspection ResultOfMethodCallIgnored
+ mappingBinFile.delete();
}
}
protected void tearDown() throws Exception {
+ if ( mappingBinFile != null && mappingBinFile.exists() ) {
+ // be nice
+ //noinspection ResultOfMethodCallIgnored
+ mappingBinFile.delete();
+ }
+ mappingBinFile = null;
mappingFile = null;
super.tearDown();
}
- public void testCachedFiles() {
- Configuration cfg = new Configuration();
- cfg.addCacheableFile( mappingFile );
- Configuration cfg2 = new Configuration();
- cfg2.addCacheableFile( mappingFile );
+ public void testCachedFiles() throws Exception {
+ assertFalse( mappingBinFile.exists() );
+ // This call should create the cached file
+ new Configuration().addCacheableFile( mappingFile );
+ assertTrue( mappingBinFile.exists() );
+
+ Configuration cfg = new Configuration().addCacheableFileStrictly( mappingFile );
+ SerializationHelper.clone( cfg );
}
}
Deleted: core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationPerformanceTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationPerformanceTest.java 2009-11-12 16:17:12 UTC (rev 17963)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationPerformanceTest.java 2009-11-12 19:46:04 UTC (rev 17964)
@@ -1,352 +0,0 @@
-/*
- * Copyright (c) 2007, Red Hat Middleware, LLC. All rights reserved.
- *
- * This copyrighted material is made available to anyone wishing to use, modify,
- * copy, or redistribute it subject to the terms and conditions of the GNU
- * Lesser General Public License, v. 2.1. This program is distributed in the
- * hope that it will be useful, but WITHOUT A WARRANTY; without even the implied
- * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details. You should have received a
- * copy of the GNU Lesser General Public License, v.2.1 along with this
- * distribution; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Red Hat Author(s): Max Andersen, Steve Ebersole
- */
-package org.hibernate.test.cfg;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.PrintWriter;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-import junit.textui.TestRunner;
-
-import org.hibernate.SessionFactory;
-import org.hibernate.cfg.Configuration;
-import org.hibernate.cfg.Environment;
-import org.hibernate.classic.Session;
-import org.hibernate.junit.UnitTestCase;
-
-/**
- * Test of configuration, specifically "cacheable files".
- *
- * @author Max Andersen
- * @author Steve Ebersole
- */
-public class ConfigurationPerformanceTest extends UnitTestCase {
-
- private final String workPackageName = "org.hibernate.test.cfg.work";
- private File compilationBaseDir;
- private File mappingBaseDir;
- private File workPackageDir;
-
- protected void setUp() throws Exception {
- compilationBaseDir = getTestComplileDirectory();
- mappingBaseDir = new File( compilationBaseDir, "org/hibernate/test" );
- workPackageDir = new File( compilationBaseDir, workPackageName.replace( '.', '/' ) );
- if ( workPackageDir.exists() ) {
- //noinspection ResultOfMethodCallIgnored
- workPackageDir.delete();
- }
- boolean created = workPackageDir.mkdirs();
- if ( !created ) {
- System.err.println( "Unable to create workPackageDir during setup" );
- }
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- private static final String[] FILES = new String[] {
- "legacy/ABC.hbm.xml",
- "legacy/ABCExtends.hbm.xml",
- "legacy/Baz.hbm.xml",
- "legacy/Blobber.hbm.xml",
- "legacy/Broken.hbm.xml",
- "legacy/Category.hbm.xml",
- "legacy/Circular.hbm.xml",
- "legacy/Commento.hbm.xml",
- "legacy/ComponentNotNullMaster.hbm.xml",
- "legacy/Componentizable.hbm.xml",
- "legacy/Container.hbm.xml",
- "legacy/Custom.hbm.xml",
- "legacy/CustomSQL.hbm.xml",
- "legacy/Eye.hbm.xml",
- "legacy/Fee.hbm.xml",
- "legacy/Fo.hbm.xml",
- "legacy/FooBar.hbm.xml",
- "legacy/Fum.hbm.xml",
- "legacy/Fumm.hbm.xml",
- "legacy/Glarch.hbm.xml",
- "legacy/Holder.hbm.xml",
- "legacy/IJ2.hbm.xml",
- "legacy/Immutable.hbm.xml",
- "legacy/Location.hbm.xml",
- "legacy/Many.hbm.xml",
- "legacy/Map.hbm.xml",
- "legacy/Marelo.hbm.xml",
- "legacy/MasterDetail.hbm.xml",
- "legacy/Middle.hbm.xml",
- "legacy/Multi.hbm.xml",
- "legacy/MultiExtends.hbm.xml",
- "legacy/Nameable.hbm.xml",
- "legacy/One.hbm.xml",
- "legacy/ParentChild.hbm.xml",
- "legacy/Qux.hbm.xml",
- "legacy/Simple.hbm.xml",
- "legacy/SingleSeveral.hbm.xml",
- "legacy/Stuff.hbm.xml",
- "legacy/UpDown.hbm.xml",
- "legacy/Vetoer.hbm.xml",
- "legacy/WZ.hbm.xml",
- };
-
- public ConfigurationPerformanceTest(String string) {
- super( string );
- }
-
- public static Test suite() {
- return new TestSuite( ConfigurationPerformanceTest.class );
- }
-
- public static void main(String[] args) throws Exception {
- TestRunner.run( suite() );
- }
-
- public void testLoadingAndSerializationOfConfiguration() throws Throwable {
- final File cachedCfgFile = new File( workPackageDir, "hibernate.cfg.bin" );
- try {
- System.err.println( "#### Preparing serialized configuration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" );
- prepareSerializedConfiguration( mappingBaseDir, FILES, cachedCfgFile );
- System.err.println( "#### Preparing serialized configuration complete ~~~~~~~~~~~~~~~~~~~~~~~~" );
-
- // now make sure we can reload the serialized configuration...
- System.err.println( "#### Reading serialized configuration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" );
- readSerializedConfiguration( cachedCfgFile );
- System.err.println( "#### Reading serialized configuration complete ~~~~~~~~~~~~~~~~~~~~~~~~~~" );
- }
- finally {
- System.err.println( "###CLEANING UP###" );
- if ( ! cachedCfgFile.delete() ) {
- System.err.println( "Unable to cleanup file " + cachedCfgFile.getAbsolutePath() );
- }
- //noinspection ForLoopReplaceableByForEach
- for ( int i = 0; i < FILES.length; i++ ) {
- File file = new File( mappingBaseDir, FILES[i] + ".bin" );
- if ( ! file.delete() ) {
- System.err.println( "Unable to cleanup file " + file.getAbsolutePath() );
- }
- }
- }
- }
-
- public void testSessionFactoryCreationTime() throws Throwable {
- generateTestFiles();
- if ( !workPackageDir.exists() ) {
- System.err.println( workPackageDir.getAbsoluteFile() + " not found" );
- return;
- }
-
- long start = System.currentTimeMillis();
- Configuration configuration = buildConfigurationFromCacheableFiles(
- workPackageDir,
- workPackageDir.list(
- new FilenameFilter() {
- public boolean accept(File dir, String name) {
- return name.endsWith( ".hbm.xml" );
- }
- }
- )
- );
- SessionFactory factory = configuration.buildSessionFactory();
- long initial = System.currentTimeMillis() - start;
- factory.close();
-
- start = System.currentTimeMillis();
- configuration = buildConfigurationFromCacheableFiles(
- workPackageDir,
- workPackageDir.list(
- new FilenameFilter() {
- public boolean accept(File dir, String name) {
- return name.endsWith( ".hbm.xml" );
- }
- }
- )
- );
- factory = configuration.buildSessionFactory();
- long subsequent = System.currentTimeMillis() - start;
-
- // Let's make sure the mappings were read in correctly (in termas of they are operational).
- Session session = factory.openSession();
- session.beginTransaction();
- session.createQuery( "from Test1" ).list();
- session.getTransaction().commit();
- session.close();
- factory.close();
-
- System.err.println( "Initial SessionFactory load time : " + initial );
- System.err.println( "Subsequent SessionFactory load time : " + subsequent );
- }
-
- private void prepareSerializedConfiguration(
- File mappingFileBase,
- String[] files,
- File cachedCfgFile) throws IOException {
- Configuration cfg = buildConfigurationFromCacheableFiles( mappingFileBase, files );
-
- ObjectOutputStream os = new ObjectOutputStream( new FileOutputStream( cachedCfgFile ) );
- os.writeObject( cfg ); // need to serialize Configuration *before* building sf since it would require non-mappings and cfg types to be serializable
- os.flush();
- os.close();
-
- timeBuildingSessionFactory( cfg );
- }
-
- private Configuration buildConfigurationFromCacheableFiles(File mappingFileBase, String[] files) {
- long start = System.currentTimeMillis();
- Configuration cfg = new Configuration();
- cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
- System.err.println(
- "Created configuration: " + ( System.currentTimeMillis() - start ) / 1000.0 + " sec."
- );
-
- start = System.currentTimeMillis();
- //noinspection ForLoopReplaceableByForEach
- for ( int i = 0; i < files.length; i++ ) {
- cfg.addCacheableFile( new File( mappingFileBase, files[i] ) );
- }
- System.err.println(
- "Added " + ( files.length ) + " resources: " +
- ( System.currentTimeMillis() - start ) / 1000.0 + " sec."
- );
- return cfg;
- }
-
- private void timeBuildingSessionFactory(Configuration configuration) {
- long start = System.currentTimeMillis();
- System.err.println( "Start build of session factory" );
- SessionFactory factory = configuration.buildSessionFactory();
- System.err.println( "Built session factory :" + ( System.currentTimeMillis() - start ) / 1000.0 + " sec." );
- factory.close();
- }
-
- private void readSerializedConfiguration(File cachedCfgFile) throws ClassNotFoundException, IOException {
- long start = System.currentTimeMillis();
- ObjectInputStream is = new ObjectInputStream( new FileInputStream( cachedCfgFile ) );
- Configuration cfg = ( Configuration ) is.readObject();
- is.close();
- System.err.println(
- "Loaded serializable configuration :" +
- ( System.currentTimeMillis() - start ) / 1000.0 + " sec."
- );
-
- timeBuildingSessionFactory( cfg );
- }
-
- public void generateTestFiles() throws Throwable {
- String filesToCompile = "";
- for ( int count = 0; count < 100; count++ ) {
- String name = "Test" + count;
- File javaFile = new File( workPackageDir, name + ".java" );
- File hbmFile = new File( workPackageDir, name + ".hbm.xml" );
- filesToCompile += ( javaFile.getAbsolutePath() + " " );
-
- System.out.println( "Generating " + javaFile.getAbsolutePath() );
- PrintWriter javaWriter = null;
- PrintWriter hbmWriter = null;
- try {
- javaWriter = new PrintWriter( new FileWriter( javaFile ) );
- hbmWriter = new PrintWriter( new FileWriter( hbmFile ) );
-
- javaWriter.println( "package " + workPackageName + ";" );
- hbmWriter.println(
- "<?xml version=\"1.0\"?>\r\n" +
- "<!DOCTYPE hibernate-mapping PUBLIC \r\n" +
- " \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\r\n" +
- " \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\r\n"
- );
-
- hbmWriter.println( "<hibernate-mapping package=\"" + workPackageName + "\">" );
-
- javaWriter.println( "public class " + name + " {" );
- javaWriter.println( " static { System.out.println(\"" + name + " initialized!\"); }" );
- hbmWriter.println( "<class name=\"" + name + "\">" );
-
- hbmWriter.println( "<id type=\"long\"><generator class=\"assigned\"/></id>" );
- for ( int propCount = 0; propCount < 100; propCount++ ) {
- String propName = "Prop" + propCount;
-
- writeJavaProperty( javaWriter, propName );
-
- hbmWriter.println( "<property name=\"" + propName + "\" type=\"string\"/>" );
-
- }
- hbmWriter.println( "</class>" );
- javaWriter.println( "}" );
- hbmWriter.println( "</hibernate-mapping>" );
- }
- finally {
- if ( javaWriter != null ) {
- javaWriter.flush();
- javaWriter.close();
- }
- if ( hbmWriter != null ) {
- hbmWriter.flush();
- hbmWriter.close();
- }
- }
- }
-
- String javac = "javac -version -d " + compilationBaseDir + " " + filesToCompile;
- System.err.println( "JAVAC : " + javac );
- Process process = Runtime.getRuntime().exec( javac );
- process.waitFor();
- System.err.println( "********************* JAVAC OUTPUT **********************" );
- pullStream( process.getInputStream() );
- System.err.println( "---------------------------------------------------------" );
- pullStream( process.getErrorStream() );
- System.err.println( "*********************************************************" );
- }
-
- private void pullStream(InputStream stream) throws IOException {
- if ( stream == null || stream.available() <= 0 ) {
- return;
- }
- byte[] buffer = new byte[256];
- while ( true ) {
- int read = stream.read( buffer );
- if ( read == -1 ) {
- break;
- }
- System.err.write( buffer, 0, read );
- }
-// System.err.println( "" );
- }
-
- private void writeJavaProperty(PrintWriter javaWriter, String propName) {
- javaWriter.println( " String " + propName + ";" );
- javaWriter.println( " String get" + propName + "() { return " + propName + "; }" );
- javaWriter.println( " void set" + propName + "(String newVal) { " + propName + "=newVal; }" );
- }
-
- private File getTestComplileDirectory() {
- String resourceName = "org/hibernate/test/legacy/ABC.hbm.xml";
- String prefix = getClass().getClassLoader().getResource( resourceName ).getFile();
- prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // ABC.hbm.xml
- prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // legacy/
- prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // test/
- prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // hibernate/
- prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // org/
- return new File( prefix + '/' );
- }
-}
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationSerializationTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationSerializationTest.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationSerializationTest.java 2009-11-12 19:46:04 UTC (rev 17964)
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2009 by Red Hat Inc and/or its affiliates or by
+ * third-party contributors as indicated by either @author tags or express
+ * copyright attribution statements applied by the authors. All
+ * third-party contributions are distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA\
+ */
+package org.hibernate.test.cfg;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.hibernate.junit.UnitTestCase;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.util.SerializationHelper;
+import org.hibernate.SessionFactory;
+
+/**
+ * Copied over mostly from ConfigurationPerformanceTest
+ *
+ * @author Steve Ebersole
+ * @author Max Andersen
+ */
+public class ConfigurationSerializationTest extends UnitTestCase {
+ public ConfigurationSerializationTest(String string) {
+ super( string );
+ }
+
+ public static Test suite() {
+ return new TestSuite( ConfigurationSerializationTest.class );
+ }
+
+ private static final String[] FILES = new String[] {
+ "legacy/ABC.hbm.xml",
+ "legacy/ABCExtends.hbm.xml",
+ "legacy/Baz.hbm.xml",
+ "legacy/Blobber.hbm.xml",
+ "legacy/Broken.hbm.xml",
+ "legacy/Category.hbm.xml",
+ "legacy/Circular.hbm.xml",
+ "legacy/Commento.hbm.xml",
+ "legacy/ComponentNotNullMaster.hbm.xml",
+ "legacy/Componentizable.hbm.xml",
+ "legacy/Container.hbm.xml",
+ "legacy/Custom.hbm.xml",
+ "legacy/CustomSQL.hbm.xml",
+ "legacy/Eye.hbm.xml",
+ "legacy/Fee.hbm.xml",
+ "legacy/Fo.hbm.xml",
+ "legacy/FooBar.hbm.xml",
+ "legacy/Fum.hbm.xml",
+ "legacy/Fumm.hbm.xml",
+ "legacy/Glarch.hbm.xml",
+ "legacy/Holder.hbm.xml",
+ "legacy/IJ2.hbm.xml",
+ "legacy/Immutable.hbm.xml",
+ "legacy/Location.hbm.xml",
+ "legacy/Many.hbm.xml",
+ "legacy/Map.hbm.xml",
+ "legacy/Marelo.hbm.xml",
+ "legacy/MasterDetail.hbm.xml",
+ "legacy/Middle.hbm.xml",
+ "legacy/Multi.hbm.xml",
+ "legacy/MultiExtends.hbm.xml",
+ "legacy/Nameable.hbm.xml",
+ "legacy/One.hbm.xml",
+ "legacy/ParentChild.hbm.xml",
+ "legacy/Qux.hbm.xml",
+ "legacy/Simple.hbm.xml",
+ "legacy/SingleSeveral.hbm.xml",
+ "legacy/Stuff.hbm.xml",
+ "legacy/UpDown.hbm.xml",
+ "legacy/Vetoer.hbm.xml",
+ "legacy/WZ.hbm.xml",
+ };
+
+ public void testConfiguraionSerializability() {
+ Configuration cfg = new Configuration();
+ for ( String file : FILES ) {
+ cfg.addResource( "org/hibernate/test/" + file );
+ }
+
+ byte[] bytes = SerializationHelper.serialize( cfg );
+ cfg = ( Configuration ) SerializationHelper.deserialize( bytes );
+
+ // try to build SF
+ SessionFactory factory = cfg.buildSessionFactory();
+ factory.close();
+ }
+}
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/ListenerTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/ListenerTest.java 2009-11-12 16:17:12 UTC (rev 17963)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/ListenerTest.java 2009-11-12 19:46:04 UTC (rev 17964)
@@ -1,3 +1,26 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
package org.hibernate.test.cfg;
import java.util.Set;
Copied: core/trunk/testsuite/src/test/perf/org/hibernate/test/perf/ConfigurationPerformanceTest.java (from rev 17887, core/trunk/testsuite/src/test/java/org/hibernate/test/cfg/ConfigurationPerformanceTest.java)
===================================================================
--- core/trunk/testsuite/src/test/perf/org/hibernate/test/perf/ConfigurationPerformanceTest.java (rev 0)
+++ core/trunk/testsuite/src/test/perf/org/hibernate/test/perf/ConfigurationPerformanceTest.java 2009-11-12 19:46:04 UTC (rev 17964)
@@ -0,0 +1,248 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+package org.hibernate.test.perf;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+import junit.textui.TestRunner;
+
+import org.hibernate.SessionFactory;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.classic.Session;
+import org.hibernate.junit.UnitTestCase;
+
+/**
+ * Test of configuration, specifically "cacheable files".
+ *
+ * @author Max Andersen
+ * @author Steve Ebersole
+ */
+public class ConfigurationPerformanceTest extends UnitTestCase {
+
+ private final String workPackageName = "org.hibernate.test.cfg.work";
+ private File compilationBaseDir;
+ private File workPackageDir;
+
+ protected void setUp() throws Exception {
+ compilationBaseDir = getTestComplileDirectory();
+ workPackageDir = new File( compilationBaseDir, workPackageName.replace( '.', '/' ) );
+ if ( workPackageDir.exists() ) {
+ //noinspection ResultOfMethodCallIgnored
+ workPackageDir.delete();
+ }
+ boolean created = workPackageDir.mkdirs();
+ if ( !created ) {
+ System.err.println( "Unable to create workPackageDir during setup" );
+ }
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public ConfigurationPerformanceTest(String string) {
+ super( string );
+ }
+
+ public static Test suite() {
+ return new TestSuite( ConfigurationPerformanceTest.class );
+ }
+
+ public static void main(String[] args) throws Exception {
+ TestRunner.run( suite() );
+ }
+
+ public void testSessionFactoryCreationTime() throws Throwable {
+ generateTestFiles();
+ if ( !workPackageDir.exists() ) {
+ System.err.println( workPackageDir.getAbsoluteFile() + " not found" );
+ return;
+ }
+
+ long start = System.currentTimeMillis();
+ Configuration configuration = buildConfigurationFromCacheableFiles(
+ workPackageDir,
+ workPackageDir.list(
+ new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return name.endsWith( ".hbm.xml" );
+ }
+ }
+ )
+ );
+ SessionFactory factory = configuration.buildSessionFactory();
+ long initial = System.currentTimeMillis() - start;
+ factory.close();
+
+ start = System.currentTimeMillis();
+ configuration = buildConfigurationFromCacheableFiles(
+ workPackageDir,
+ workPackageDir.list(
+ new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return name.endsWith( ".hbm.xml" );
+ }
+ }
+ )
+ );
+ factory = configuration.buildSessionFactory();
+ long subsequent = System.currentTimeMillis() - start;
+
+ // Let's make sure the mappings were read in correctly (in termas of they are operational).
+ Session session = factory.openSession();
+ session.beginTransaction();
+ session.createQuery( "from Test1" ).list();
+ session.getTransaction().commit();
+ session.close();
+ factory.close();
+
+ System.err.println( "Initial SessionFactory load time : " + initial );
+ System.err.println( "Subsequent SessionFactory load time : " + subsequent );
+ }
+
+ private Configuration buildConfigurationFromCacheableFiles(File mappingFileBase, String[] files) {
+ long start = System.currentTimeMillis();
+ Configuration cfg = new Configuration();
+ cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
+ System.err.println(
+ "Created configuration: " + ( System.currentTimeMillis() - start ) / 1000.0 + " sec."
+ );
+
+ start = System.currentTimeMillis();
+ //noinspection ForLoopReplaceableByForEach
+ for ( int i = 0; i < files.length; i++ ) {
+ cfg.addCacheableFile( new File( mappingFileBase, files[i] ) );
+ }
+ System.err.println(
+ "Added " + ( files.length ) + " resources: " +
+ ( System.currentTimeMillis() - start ) / 1000.0 + " sec."
+ );
+ return cfg;
+ }
+
+ public void generateTestFiles() throws Throwable {
+ String filesToCompile = "";
+ for ( int count = 0; count < 100; count++ ) {
+ String name = "Test" + count;
+ File javaFile = new File( workPackageDir, name + ".java" );
+ File hbmFile = new File( workPackageDir, name + ".hbm.xml" );
+ filesToCompile += ( javaFile.getAbsolutePath() + " " );
+
+ System.out.println( "Generating " + javaFile.getAbsolutePath() );
+ PrintWriter javaWriter = null;
+ PrintWriter hbmWriter = null;
+ try {
+ javaWriter = new PrintWriter( new FileWriter( javaFile ) );
+ hbmWriter = new PrintWriter( new FileWriter( hbmFile ) );
+
+ javaWriter.println( "package " + workPackageName + ";" );
+ hbmWriter.println(
+ "<?xml version=\"1.0\"?>\r\n" +
+ "<!DOCTYPE hibernate-mapping PUBLIC \r\n" +
+ " \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\r\n" +
+ " \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\r\n"
+ );
+
+ hbmWriter.println( "<hibernate-mapping package=\"" + workPackageName + "\">" );
+
+ javaWriter.println( "public class " + name + " {" );
+ javaWriter.println( " static { System.out.println(\"" + name + " initialized!\"); }" );
+ hbmWriter.println( "<class name=\"" + name + "\">" );
+
+ hbmWriter.println( "<id type=\"long\"><generator class=\"assigned\"/></id>" );
+ for ( int propCount = 0; propCount < 100; propCount++ ) {
+ String propName = "Prop" + propCount;
+
+ writeJavaProperty( javaWriter, propName );
+
+ hbmWriter.println( "<property name=\"" + propName + "\" type=\"string\"/>" );
+
+ }
+ hbmWriter.println( "</class>" );
+ javaWriter.println( "}" );
+ hbmWriter.println( "</hibernate-mapping>" );
+ }
+ finally {
+ if ( javaWriter != null ) {
+ javaWriter.flush();
+ javaWriter.close();
+ }
+ if ( hbmWriter != null ) {
+ hbmWriter.flush();
+ hbmWriter.close();
+ }
+ }
+ }
+
+ String javac = "javac -version -d " + compilationBaseDir + " " + filesToCompile;
+ System.err.println( "JAVAC : " + javac );
+ Process process = Runtime.getRuntime().exec( javac );
+ process.waitFor();
+ System.err.println( "********************* JAVAC OUTPUT **********************" );
+ pullStream( process.getInputStream() );
+ System.err.println( "---------------------------------------------------------" );
+ pullStream( process.getErrorStream() );
+ System.err.println( "*********************************************************" );
+ }
+
+ private void pullStream(InputStream stream) throws IOException {
+ if ( stream == null || stream.available() <= 0 ) {
+ return;
+ }
+ byte[] buffer = new byte[256];
+ while ( true ) {
+ int read = stream.read( buffer );
+ if ( read == -1 ) {
+ break;
+ }
+ System.err.write( buffer, 0, read );
+ }
+// System.err.println( "" );
+ }
+
+ private void writeJavaProperty(PrintWriter javaWriter, String propName) {
+ javaWriter.println( " String " + propName + ";" );
+ javaWriter.println( " String get" + propName + "() { return " + propName + "; }" );
+ javaWriter.println( " void set" + propName + "(String newVal) { " + propName + "=newVal; }" );
+ }
+
+ private File getTestComplileDirectory() {
+ String resourceName = "org/hibernate/test/legacy/ABC.hbm.xml";
+ String prefix = getClass().getClassLoader().getResource( resourceName ).getFile();
+ prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // ABC.hbm.xml
+ prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // legacy/
+ prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // test/
+ prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // hibernate/
+ prefix = prefix.substring( 0, prefix.lastIndexOf( '/' ) ); // org/
+ return new File( prefix + '/' );
+ }
+}
15 years, 1 month
Hibernate SVN: r17963 - sandbox/trunk.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2009-11-12 11:17:12 -0500 (Thu, 12 Nov 2009)
New Revision: 17963
Added:
sandbox/trunk/new-metadata/
Log:
snadbox for working on the separated metamodel redesign
15 years, 1 month
Hibernate SVN: r17962 - in core/trunk/core/src/main/java/org/hibernate: dialect and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: smarlow(a)redhat.com
Date: 2009-11-11 23:20:41 -0500 (Wed, 11 Nov 2009)
New Revision: 17962
Added:
core/trunk/core/src/main/java/org/hibernate/dialect/lock/OptimisticForceIncrementLockingStrategy.java
core/trunk/core/src/main/java/org/hibernate/dialect/lock/OptimisticLockingStrategy.java
core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticForceIncrementLockingStrategy.java
core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticReadSelectLockingStrategy.java
core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticReadUpdateLockingStrategy.java
core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteSelectLockingStrategy.java
core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteUpdateLockingStrategy.java
Modified:
core/trunk/core/src/main/java/org/hibernate/LockMode.java
core/trunk/core/src/main/java/org/hibernate/dialect/Cache71Dialect.java
core/trunk/core/src/main/java/org/hibernate/dialect/Dialect.java
core/trunk/core/src/main/java/org/hibernate/dialect/FrontBaseDialect.java
core/trunk/core/src/main/java/org/hibernate/dialect/HSQLDialect.java
core/trunk/core/src/main/java/org/hibernate/dialect/MckoiDialect.java
core/trunk/core/src/main/java/org/hibernate/dialect/PointbaseDialect.java
core/trunk/core/src/main/java/org/hibernate/dialect/RDMSOS2200Dialect.java
core/trunk/core/src/main/java/org/hibernate/dialect/SQLServerDialect.java
core/trunk/core/src/main/java/org/hibernate/dialect/TimesTenDialect.java
core/trunk/core/src/main/java/org/hibernate/dialect/lock/LockingStrategy.java
core/trunk/core/src/main/java/org/hibernate/dialect/lock/SelectLockingStrategy.java
core/trunk/core/src/main/java/org/hibernate/dialect/lock/UpdateLockingStrategy.java
core/trunk/core/src/main/java/org/hibernate/event/def/AbstractLockUpgradeEventListener.java
core/trunk/core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java
Log:
HHH-4546 - add JPA 2.0 locking.
Modified: core/trunk/core/src/main/java/org/hibernate/LockMode.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/LockMode.java 2009-11-11 22:20:48 UTC (rev 17961)
+++ core/trunk/core/src/main/java/org/hibernate/LockMode.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -120,30 +120,30 @@
* Optimisticly assume that transaction will not experience contention for
* entities. The entity version will be verified near the transaction end.
*/
- public static final LockMode OPTIMISTIC = new LockMode(3,"OPTIMISTIC");
+ public static final LockMode OPTIMISTIC = new LockMode( 3, "OPTIMISTIC");
/**
* Optimisticly assume that transaction will not experience contention for entities.
* The entity version will be verified and incremented near the transaction end.
*/
- public static final LockMode OPTIMISTIC_FORCE_INCREMENT = new LockMode(7,"OPTIMISTIC_FORCE_INCREMENT");
+ public static final LockMode OPTIMISTIC_FORCE_INCREMENT = new LockMode( 4, "OPTIMISTIC_FORCE_INCREMENT");
/**
* Implemented as PESSIMISTIC_WRITE.
* TODO: introduce separate support for PESSIMISTIC_READ
*/
- public static final LockMode PESSIMISTIC_READ = new LockMode(12,"PESSIMISTIC_READ");
+ public static final LockMode PESSIMISTIC_READ = new LockMode( 12, "PESSIMISTIC_READ");
/**
* Transaction will obtain a database lock immediately.
* TODO: add PESSIMISTIC_WRITE_NOWAIT
*/
- public static final LockMode PESSIMISTIC_WRITE = new LockMode(13,"PESSIMISTIC_WRITE");
+ public static final LockMode PESSIMISTIC_WRITE = new LockMode( 13, "PESSIMISTIC_WRITE");
/**
* Transaction will immediately increment the entity version.
*/
- public static final LockMode PESSIMISTIC_FORCE_INCREMENT = new LockMode(17,"PESSIMISTIC_FORCE_INCREMENT");
+ public static final LockMode PESSIMISTIC_FORCE_INCREMENT = new LockMode( 17, "PESSIMISTIC_FORCE_INCREMENT");
/**
* end of javax.persistence.LockModeType modes
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/Cache71Dialect.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/Cache71Dialect.java 2009-11-11 22:20:48 UTC (rev 17961)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/Cache71Dialect.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -41,9 +41,7 @@
import org.hibernate.dialect.function.StandardJDBCEscapeFunction;
import org.hibernate.dialect.function.ConvertFunction;
import org.hibernate.dialect.function.ConditionalParenthesisFunction;
-import org.hibernate.dialect.lock.LockingStrategy;
-import org.hibernate.dialect.lock.SelectLockingStrategy;
-import org.hibernate.dialect.lock.UpdateLockingStrategy;
+import org.hibernate.dialect.lock.*;
import org.hibernate.exception.CacheSQLStateConverter;
import org.hibernate.exception.SQLExceptionConverter;
import org.hibernate.exception.TemplatedViolatedConstraintNameExtracter;
@@ -564,7 +562,22 @@
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
// InterSystems Cache' does not current support "SELECT ... FOR UPDATE" syntax...
// Set your transaction mode to READ_COMMITTED before using
- if ( lockMode.greaterThan( LockMode.READ ) ) {
+ if ( lockMode==LockMode.PESSIMISTIC_FORCE_INCREMENT) {
+ return new PessimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.PESSIMISTIC_WRITE) {
+ return new PessimisticWriteUpdateLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.PESSIMISTIC_READ) {
+ return new PessimisticReadUpdateLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC) {
+ return new OptimisticLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC_FORCE_INCREMENT) {
+ return new OptimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode.greaterThan( LockMode.READ ) ) {
return new UpdateLockingStrategy( lockable, lockMode );
}
else {
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/Dialect.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/Dialect.java 2009-11-11 22:20:48 UTC (rev 17961)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/Dialect.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -48,8 +48,7 @@
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.function.StandardSQLFunction;
-import org.hibernate.dialect.lock.LockingStrategy;
-import org.hibernate.dialect.lock.SelectLockingStrategy;
+import org.hibernate.dialect.lock.*;
import org.hibernate.engine.Mapping;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.exception.SQLExceptionConverter;
@@ -952,6 +951,21 @@
* @since 3.2
*/
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
+ if ( lockMode==LockMode.PESSIMISTIC_FORCE_INCREMENT) {
+ return new PessimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.PESSIMISTIC_WRITE) {
+ return new PessimisticWriteSelectLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.PESSIMISTIC_READ) {
+ return new PessimisticReadSelectLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC) {
+ return new OptimisticLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC_FORCE_INCREMENT) {
+ return new OptimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
return new SelectLockingStrategy( lockable, lockMode );
}
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/FrontBaseDialect.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/FrontBaseDialect.java 2009-11-11 22:20:48 UTC (rev 17961)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/FrontBaseDialect.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -24,9 +24,7 @@
*/
package org.hibernate.dialect;
-import org.hibernate.dialect.lock.LockingStrategy;
-import org.hibernate.dialect.lock.UpdateLockingStrategy;
-import org.hibernate.dialect.lock.SelectLockingStrategy;
+import org.hibernate.dialect.lock.*;
import org.hibernate.persister.entity.Lockable;
import org.hibernate.LockMode;
@@ -104,7 +102,22 @@
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
// Frontbase has no known variation of a "SELECT ... FOR UPDATE" syntax...
- if ( lockMode.greaterThan( LockMode.READ ) ) {
+ if ( lockMode==LockMode.PESSIMISTIC_FORCE_INCREMENT) {
+ return new PessimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.PESSIMISTIC_WRITE) {
+ return new PessimisticWriteUpdateLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.PESSIMISTIC_READ) {
+ return new PessimisticReadUpdateLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC) {
+ return new OptimisticLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC_FORCE_INCREMENT) {
+ return new OptimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode.greaterThan( LockMode.READ ) ) {
return new UpdateLockingStrategy( lockable, lockMode );
}
else {
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/HSQLDialect.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/HSQLDialect.java 2009-11-11 22:20:48 UTC (rev 17961)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/HSQLDialect.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -38,8 +38,7 @@
import org.hibernate.dialect.function.NoArgSQLFunction;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.VarArgsSQLFunction;
-import org.hibernate.dialect.lock.LockingStrategy;
-import org.hibernate.dialect.lock.SelectLockingStrategy;
+import org.hibernate.dialect.lock.*;
import org.hibernate.exception.JDBCExceptionHelper;
import org.hibernate.exception.TemplatedViolatedConstraintNameExtracter;
import org.hibernate.exception.ViolatedConstraintNameExtracter;
@@ -292,7 +291,17 @@
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
// HSQLDB only supports READ_UNCOMMITTED transaction isolation
+ if ( lockMode==LockMode.PESSIMISTIC_FORCE_INCREMENT) {
+ return new PessimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC) {
+ return new OptimisticLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC_FORCE_INCREMENT) {
+ return new OptimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
return new ReadUncommittedLockingStrategy( lockable, lockMode );
+
}
public static class ReadUncommittedLockingStrategy extends SelectLockingStrategy {
@@ -300,12 +309,12 @@
super( lockable, lockMode );
}
- public void lock(Serializable id, Object version, Object object, SessionImplementor session)
+ public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session)
throws StaleObjectStateException, JDBCException {
if ( getLockMode().greaterThan( LockMode.READ ) ) {
log.warn( "HSQLDB supports only READ_UNCOMMITTED isolation" );
}
- super.lock( id, version, object, session );
+ super.lock( id, version, object, timeout, session );
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/MckoiDialect.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/MckoiDialect.java 2009-11-11 22:20:48 UTC (rev 17961)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/MckoiDialect.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -31,9 +31,7 @@
import org.hibernate.persister.entity.Lockable;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.function.StandardSQLFunction;
-import org.hibernate.dialect.lock.LockingStrategy;
-import org.hibernate.dialect.lock.UpdateLockingStrategy;
-import org.hibernate.dialect.lock.SelectLockingStrategy;
+import org.hibernate.dialect.lock.*;
import org.hibernate.sql.CaseFragment;
import org.hibernate.sql.MckoiCaseFragment;
@@ -111,7 +109,22 @@
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
// Mckoi has no known variation of a "SELECT ... FOR UPDATE" syntax...
- if ( lockMode.greaterThan( LockMode.READ ) ) {
+ if ( lockMode==LockMode.PESSIMISTIC_FORCE_INCREMENT) {
+ return new PessimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.PESSIMISTIC_WRITE) {
+ return new PessimisticWriteUpdateLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.PESSIMISTIC_READ) {
+ return new PessimisticReadUpdateLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC) {
+ return new OptimisticLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC_FORCE_INCREMENT) {
+ return new OptimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode.greaterThan( LockMode.READ ) ) {
return new UpdateLockingStrategy( lockable, lockMode );
}
else {
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/PointbaseDialect.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/PointbaseDialect.java 2009-11-11 22:20:48 UTC (rev 17961)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/PointbaseDialect.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -24,9 +24,7 @@
*/
package org.hibernate.dialect;
-import org.hibernate.dialect.lock.LockingStrategy;
-import org.hibernate.dialect.lock.UpdateLockingStrategy;
-import org.hibernate.dialect.lock.SelectLockingStrategy;
+import org.hibernate.dialect.lock.*;
import org.hibernate.persister.entity.Lockable;
import org.hibernate.LockMode;
@@ -81,7 +79,22 @@
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
// Pointbase has no known variation of a "SELECT ... FOR UPDATE" syntax...
- if ( lockMode.greaterThan( LockMode.READ ) ) {
+ if ( lockMode==LockMode.PESSIMISTIC_FORCE_INCREMENT) {
+ return new PessimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.PESSIMISTIC_WRITE) {
+ return new PessimisticWriteUpdateLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.PESSIMISTIC_READ) {
+ return new PessimisticReadUpdateLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC) {
+ return new OptimisticLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC_FORCE_INCREMENT) {
+ return new OptimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode.greaterThan( LockMode.READ ) ) {
return new UpdateLockingStrategy( lockable, lockMode );
}
else {
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/RDMSOS2200Dialect.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/RDMSOS2200Dialect.java 2009-11-11 22:20:48 UTC (rev 17961)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/RDMSOS2200Dialect.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -27,9 +27,7 @@
import org.hibernate.dialect.function.NoArgSQLFunction;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.SQLFunctionTemplate;
-import org.hibernate.dialect.lock.LockingStrategy;
-import org.hibernate.dialect.lock.UpdateLockingStrategy;
-import org.hibernate.dialect.lock.SelectLockingStrategy;
+import org.hibernate.dialect.lock.*;
import java.sql.Types;
import org.hibernate.Hibernate;
@@ -336,7 +334,22 @@
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
// RDMS has no known variation of a "SELECT ... FOR UPDATE" syntax...
- if ( lockMode.greaterThan( LockMode.READ ) ) {
+ if ( lockMode==LockMode.PESSIMISTIC_FORCE_INCREMENT) {
+ return new PessimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.PESSIMISTIC_WRITE) {
+ return new PessimisticWriteUpdateLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.PESSIMISTIC_READ) {
+ return new PessimisticReadUpdateLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC) {
+ return new OptimisticLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC_FORCE_INCREMENT) {
+ return new OptimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode.greaterThan( LockMode.READ ) ) {
return new UpdateLockingStrategy( lockable, lockMode );
}
else {
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/SQLServerDialect.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/SQLServerDialect.java 2009-11-11 22:20:48 UTC (rev 17961)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/SQLServerDialect.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -111,10 +111,15 @@
}
public String appendLockHint(LockMode mode, String tableName) {
- if ( mode.greaterThan( LockMode.READ ) ) {
- // does this need holdlock also? : return tableName + " with (updlock, rowlock, holdlock)";
+ if ( ( mode == LockMode.UPGRADE ) ||
+ ( mode == LockMode.UPGRADE_NOWAIT ) ||
+ ( mode == LockMode.PESSIMISTIC_WRITE ) ||
+ ( mode == LockMode.WRITE ) ) {
return tableName + " with (updlock, rowlock)";
}
+ else if ( mode == LockMode.PESSIMISTIC_READ ) {
+ return tableName + " with (holdlock, rowlock)";
+ }
else {
return tableName;
}
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/TimesTenDialect.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/TimesTenDialect.java 2009-11-11 22:20:48 UTC (rev 17961)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/TimesTenDialect.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -32,9 +32,7 @@
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.function.NoArgSQLFunction;
import org.hibernate.dialect.function.StandardSQLFunction;
-import org.hibernate.dialect.lock.LockingStrategy;
-import org.hibernate.dialect.lock.UpdateLockingStrategy;
-import org.hibernate.dialect.lock.SelectLockingStrategy;
+import org.hibernate.dialect.lock.*;
import org.hibernate.sql.JoinFragment;
import org.hibernate.sql.OracleJoinFragment;
@@ -217,7 +215,22 @@
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
// TimesTen has no known variation of a "SELECT ... FOR UPDATE" syntax...
- if ( lockMode.greaterThan( LockMode.READ ) ) {
+ if ( lockMode==LockMode.PESSIMISTIC_FORCE_INCREMENT) {
+ return new PessimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.PESSIMISTIC_WRITE) {
+ return new PessimisticWriteUpdateLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.PESSIMISTIC_READ) {
+ return new PessimisticReadUpdateLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC) {
+ return new OptimisticLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode==LockMode.OPTIMISTIC_FORCE_INCREMENT) {
+ return new OptimisticForceIncrementLockingStrategy( lockable, lockMode);
+ }
+ else if ( lockMode.greaterThan( LockMode.READ ) ) {
return new UpdateLockingStrategy( lockable, lockMode );
}
else {
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/lock/LockingStrategy.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/lock/LockingStrategy.java 2009-11-11 22:20:48 UTC (rev 17961)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/lock/LockingStrategy.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -51,11 +51,12 @@
* @param id The id of the row to be locked
* @param version The current version (or null if not versioned)
* @param object The object logically being locked (currently not used)
+ * @param timeout timeout in milliseconds, 0 = no wait, -1 = wait indefinitely
* @param session The session from which the lock request originated
* @throws StaleObjectStateException Indicates an optimisitic lock failure
* as part of acquiring the requested database lock.
* @throws JDBCException
*/
- public void lock(Serializable id, Object version, Object object, SessionImplementor session)
+ public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session)
throws StaleObjectStateException, JDBCException;
}
Added: core/trunk/core/src/main/java/org/hibernate/dialect/lock/OptimisticForceIncrementLockingStrategy.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/lock/OptimisticForceIncrementLockingStrategy.java (rev 0)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/lock/OptimisticForceIncrementLockingStrategy.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -0,0 +1,91 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.dialect.lock;
+
+import java.io.Serializable;
+
+import org.hibernate.HibernateException;
+import org.hibernate.JDBCException;
+import org.hibernate.LockMode;
+import org.hibernate.StaleObjectStateException;
+import org.hibernate.event.EventSource;
+import org.hibernate.action.EntityIncrementVersionProcess;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.engine.EntityEntry;
+import org.hibernate.persister.entity.Lockable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An optimistic locking strategy that forces an increment of the version (after verifying that version hasn't changed).
+ * This takes place just prior to transaction commit.
+ * <p/>
+ * This strategy is valid for LockMode.OPTIMISTIC_FORCE_INCREMENT
+ *
+ * @since 3.5
+ *
+ * @author Scott Marlow
+ */
+public class OptimisticForceIncrementLockingStrategy implements LockingStrategy {
+ private static final Logger log = LoggerFactory.getLogger( OptimisticForceIncrementLockingStrategy.class );
+
+ private final Lockable lockable;
+ private final LockMode lockMode;
+ /**
+ * Construct locking strategy.
+ *
+ * @param lockable The metadata for the entity to be locked.
+ * @param lockMode Indictates the type of lock to be acquired.
+ */
+ public OptimisticForceIncrementLockingStrategy(Lockable lockable, LockMode lockMode) {
+ this.lockable = lockable;
+ this.lockMode = lockMode;
+ if ( lockMode.lessThan( LockMode.OPTIMISTIC_FORCE_INCREMENT ) ) {
+ throw new HibernateException( "[" + lockMode + "] not valid for [" + lockable.getEntityName() + "]" );
+ }
+ }
+
+ /**
+ * @see LockingStrategy#lock
+ */
+ public void lock(
+ Serializable id,
+ Object version,
+ Object object,
+ int timeout, SessionImplementor session) throws StaleObjectStateException, JDBCException {
+ if ( !lockable.isVersioned() ) {
+ throw new HibernateException( "[" + lockMode + "] not supported for non-versioned entities [" + lockable.getEntityName() + "]" );
+ }
+ EntityEntry entry = session.getPersistenceContext().getEntry(object);
+ EntityIncrementVersionProcess incrementVersion = new EntityIncrementVersionProcess(object, entry);
+ EventSource source = (EventSource)session;
+ // Register the EntityIncrementVersionProcess action to run just prior to transaction commit.
+ source.getActionQueue().registerProcess(incrementVersion);
+ }
+
+ protected LockMode getLockMode() {
+ return lockMode;
+ }
+}
\ No newline at end of file
Added: core/trunk/core/src/main/java/org/hibernate/dialect/lock/OptimisticLockingStrategy.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/lock/OptimisticLockingStrategy.java (rev 0)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/lock/OptimisticLockingStrategy.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -0,0 +1,88 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.dialect.lock;
+
+import java.io.Serializable;
+
+import org.hibernate.*;
+import org.hibernate.event.EventSource;
+import org.hibernate.action.EntityVerifyVersionProcess;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.engine.EntityEntry;
+import org.hibernate.persister.entity.Lockable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An optimistic locking strategy that verifies that the version hasn't changed (prior to transaction commit).
+ * <p/>
+ * This strategy is valid for LockMode.OPTIMISTIC
+ *
+ * @since 3.5
+ *
+ * @author Scott Marlow
+ */
+public class OptimisticLockingStrategy implements LockingStrategy {
+ private static final Logger log = LoggerFactory.getLogger( OptimisticLockingStrategy.class );
+
+ private final Lockable lockable;
+ private final LockMode lockMode;
+
+ /**
+ * Construct locking strategy.
+ *
+ * @param lockable The metadata for the entity to be locked.
+ * @param lockMode Indictates the type of lock to be acquired.
+ */
+ public OptimisticLockingStrategy(Lockable lockable, LockMode lockMode) {
+ this.lockable = lockable;
+ this.lockMode = lockMode;
+ if ( lockMode.lessThan( LockMode.OPTIMISTIC ) ) {
+ throw new HibernateException( "[" + lockMode + "] not valid for [" + lockable.getEntityName() + "]" );
+ }
+ }
+
+ /**
+ * @see org.hibernate.dialect.lock.LockingStrategy#lock
+ */
+ public void lock(
+ Serializable id,
+ Object version,
+ Object object,
+ int timeout, SessionImplementor session) throws StaleObjectStateException, JDBCException {
+ if ( !lockable.isVersioned() ) {
+ throw new OptimisticLockException( "[" + lockMode + "] not supported for non-versioned entities [" + lockable.getEntityName() + "]" );
+ }
+ EntityEntry entry = session.getPersistenceContext().getEntry(object);
+ EventSource source = (EventSource)session;
+ EntityVerifyVersionProcess verifyVersion = new EntityVerifyVersionProcess(object, entry);
+ // Register the EntityVerifyVersionProcess action to run just prior to transaction commit.
+ source.getActionQueue().registerProcess(verifyVersion);
+ }
+
+ protected LockMode getLockMode() {
+ return lockMode;
+ }
+}
\ No newline at end of file
Added: core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticForceIncrementLockingStrategy.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticForceIncrementLockingStrategy.java (rev 0)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticForceIncrementLockingStrategy.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -0,0 +1,93 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.dialect.lock;
+
+import java.io.Serializable;
+
+import org.hibernate.HibernateException;
+import org.hibernate.JDBCException;
+import org.hibernate.LockMode;
+import org.hibernate.StaleObjectStateException;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.engine.EntityEntry;
+import org.hibernate.persister.entity.Lockable;
+import org.hibernate.persister.entity.EntityPersister;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A pessimistic locking strategy that increments the version immediately (obtaining an exclusive write lock).
+ * <p/>
+ * This strategy is valid for LockMode.PESSIMISTIC_FORCE_INCREMENT
+ *
+ * @since 3.5
+ *
+ * @author Scott Marlow
+ */
+public class PessimisticForceIncrementLockingStrategy implements LockingStrategy {
+ private static final Logger log = LoggerFactory.getLogger( PessimisticForceIncrementLockingStrategy.class );
+
+ private final Lockable lockable;
+ private final LockMode lockMode;
+
+ /**
+ * Construct locking strategy.
+ *
+ * @param lockable The metadata for the entity to be locked.
+ * @param lockMode Indictates the type of lock to be acquired.
+ */
+ public PessimisticForceIncrementLockingStrategy(Lockable lockable, LockMode lockMode) {
+ this.lockable = lockable;
+ this.lockMode = lockMode;
+ // ForceIncrement can be used for PESSIMISTIC_READ, PESSIMISTIC_WRITE or PESSIMISTIC_FORCE_INCREMENT
+ if ( lockMode.lessThan( LockMode.PESSIMISTIC_READ ) ) {
+ throw new HibernateException( "[" + lockMode + "] not valid for [" + lockable.getEntityName() + "]" );
+ }
+ }
+
+ /**
+ * @see org.hibernate.dialect.lock.LockingStrategy#lock
+ */
+ public void lock(
+ Serializable id,
+ Object version,
+ Object object,
+ int timeout,
+ SessionImplementor session) throws StaleObjectStateException, JDBCException {
+ if ( !lockable.isVersioned() ) {
+ throw new HibernateException( "[" + lockMode + "] not supported for non-versioned entities [" + lockable.getEntityName() + "]" );
+ }
+ EntityEntry entry = session.getPersistenceContext().getEntry(object);
+ final EntityPersister persister = entry.getPersister();
+ Object nextVersion = persister.forceVersionIncrement(
+ entry.getId(), entry.getVersion(), session
+ );
+ entry.forceLocked( object, nextVersion );
+ }
+
+ protected LockMode getLockMode() {
+ return lockMode;
+ }
+}
\ No newline at end of file
Added: core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticReadSelectLockingStrategy.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticReadSelectLockingStrategy.java (rev 0)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticReadSelectLockingStrategy.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -0,0 +1,148 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.dialect.lock;
+
+import org.hibernate.persister.entity.Lockable;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.engine.SessionFactoryImplementor;
+import org.hibernate.StaleObjectStateException;
+import org.hibernate.JDBCException;
+import org.hibernate.LockMode;
+import org.hibernate.sql.SimpleSelect;
+import org.hibernate.pretty.MessageHelper;
+import org.hibernate.exception.JDBCExceptionHelper;
+
+import java.io.Serializable;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+/**
+ * A pessimistic locking strategy where the locks are obtained through select statements.
+ * <p/>
+ * For non-read locks, this is achieved through the Dialect's specific
+ * SELECT ... FOR UPDATE syntax.
+ *
+ * This strategy is valid for LockMode.PESSIMISTIC_READ
+ *
+ * This class is a clone of SelectLockingStrategy.
+ *
+ * @see org.hibernate.dialect.Dialect#getForUpdateString(org.hibernate.LockMode)
+ * @see org.hibernate.dialect.Dialect#appendLockHint(org.hibernate.LockMode, String)
+ * @since 3.5
+ *
+ * @author Steve Ebersole
+ * @author Scott Marlow
+ */
+public class PessimisticReadSelectLockingStrategy implements LockingStrategy {
+
+ private final Lockable lockable;
+ private final LockMode lockMode;
+ private final String sql;
+
+ /**
+ * Construct a locking strategy based on SQL SELECT statements.
+ *
+ * @param lockable The metadata for the entity to be locked.
+ * @param lockMode Indictates the type of lock to be acquired.
+ */
+ public PessimisticReadSelectLockingStrategy(Lockable lockable, LockMode lockMode) {
+ this.lockable = lockable;
+ this.lockMode = lockMode;
+ this.sql = generateLockString();
+ }
+
+ /**
+ * @see org.hibernate.dialect.lock.LockingStrategy#lock
+ */
+ public void lock(
+ Serializable id,
+ Object version,
+ Object object,
+ int timeout, SessionImplementor session) throws StaleObjectStateException, JDBCException {
+
+ SessionFactoryImplementor factory = session.getFactory();
+ try {
+ PreparedStatement st = session.getBatcher().prepareSelectStatement( sql );
+ try {
+ lockable.getIdentifierType().nullSafeSet( st, id, 1, session );
+ if ( lockable.isVersioned() ) {
+ lockable.getVersionType().nullSafeSet(
+ st,
+ version,
+ lockable.getIdentifierType().getColumnSpan( factory ) + 1,
+ session
+ );
+ }
+
+ ResultSet rs = st.executeQuery();
+ try {
+ if ( !rs.next() ) {
+ if ( factory.getStatistics().isStatisticsEnabled() ) {
+ factory.getStatisticsImplementor()
+ .optimisticFailure( lockable.getEntityName() );
+ }
+ throw new StaleObjectStateException( lockable.getEntityName(), id );
+ }
+ }
+ finally {
+ rs.close();
+ }
+ }
+ finally {
+ session.getBatcher().closeStatement( st );
+ }
+
+ }
+ catch ( SQLException sqle ) {
+ throw JDBCExceptionHelper.convert(
+ session.getFactory().getSQLExceptionConverter(),
+ sqle,
+ "could not lock: " + MessageHelper.infoString( lockable, id, session.getFactory() ),
+ sql
+ );
+ }
+ }
+
+ protected LockMode getLockMode() {
+ return lockMode;
+ }
+
+ protected String generateLockString() {
+ SessionFactoryImplementor factory = lockable.getFactory();
+ SimpleSelect select = new SimpleSelect( factory.getDialect() )
+ .setLockMode( lockMode )
+ .setTableName( lockable.getRootTableName() )
+ .addColumn( lockable.getRootTableIdentifierColumnNames()[0] )
+ .addCondition( lockable.getRootTableIdentifierColumnNames(), "=?" );
+ if ( lockable.isVersioned() ) {
+ select.addCondition( lockable.getVersionColumnName(), "=?" );
+ }
+ if ( factory.getSettings().isCommentsEnabled() ) {
+ select.setComment( lockMode + " lock " + lockable.getEntityName() );
+ }
+ return select.toStatementString();
+ }
+}
\ No newline at end of file
Added: core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticReadUpdateLockingStrategy.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticReadUpdateLockingStrategy.java (rev 0)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticReadUpdateLockingStrategy.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -0,0 +1,148 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.dialect.lock;
+
+import java.io.Serializable;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+
+import org.hibernate.HibernateException;
+import org.hibernate.JDBCException;
+import org.hibernate.LockMode;
+import org.hibernate.StaleObjectStateException;
+import org.hibernate.engine.SessionFactoryImplementor;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.exception.JDBCExceptionHelper;
+import org.hibernate.persister.entity.Lockable;
+import org.hibernate.pretty.MessageHelper;
+import org.hibernate.sql.Update;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A pessimistic locking strategy where the locks are obtained through update statements.
+ * <p/>
+ * This strategy is valid for LockMode.PESSIMISTIC_READ
+ *
+ * This class is a clone of UpdateLockingStrategy.
+ *
+ * @since 3.5
+ *
+ * @author Steve Ebersole
+ * @author Scott Marlow
+ */
+public class PessimisticReadUpdateLockingStrategy implements LockingStrategy {
+ private static final Logger log = LoggerFactory.getLogger( PessimisticReadUpdateLockingStrategy.class );
+
+ private final Lockable lockable;
+ private final LockMode lockMode;
+ private final String sql;
+
+ /**
+ * Construct a locking strategy based on SQL UPDATE statements.
+ *
+ * @param lockable The metadata for the entity to be locked.
+ * @param lockMode Indictates the type of lock to be acquired. Note that
+ * read-locks are not valid for this strategy.
+ */
+ public PessimisticReadUpdateLockingStrategy(Lockable lockable, LockMode lockMode) {
+ this.lockable = lockable;
+ this.lockMode = lockMode;
+ if ( lockMode.lessThan( LockMode.PESSIMISTIC_READ ) ) {
+ throw new HibernateException( "[" + lockMode + "] not valid for update statement" );
+ }
+ if ( !lockable.isVersioned() ) {
+ log.warn( "write locks via update not supported for non-versioned entities [" + lockable.getEntityName() + "]" );
+ this.sql = null;
+ }
+ else {
+ this.sql = generateLockString();
+ }
+ }
+
+ /**
+ * @see org.hibernate.dialect.lock.LockingStrategy#lock
+ */
+ public void lock(
+ Serializable id,
+ Object version,
+ Object object,
+ int timeout, SessionImplementor session) throws StaleObjectStateException, JDBCException {
+ if ( !lockable.isVersioned() ) {
+ throw new HibernateException( "write locks via update not supported for non-versioned entities [" + lockable.getEntityName() + "]" );
+ }
+ SessionFactoryImplementor factory = session.getFactory();
+ try {
+ PreparedStatement st = session.getBatcher().prepareSelectStatement( sql );
+ try {
+ lockable.getVersionType().nullSafeSet( st, version, 1, session );
+ int offset = 2;
+
+ lockable.getIdentifierType().nullSafeSet( st, id, offset, session );
+ offset += lockable.getIdentifierType().getColumnSpan( factory );
+
+ if ( lockable.isVersioned() ) {
+ lockable.getVersionType().nullSafeSet( st, version, offset, session );
+ }
+
+ int affected = st.executeUpdate();
+ if ( affected < 0 ) { // todo: should this instead check for exactly one row modified?
+ factory.getStatisticsImplementor().optimisticFailure( lockable.getEntityName() );
+ throw new StaleObjectStateException( lockable.getEntityName(), id );
+ }
+
+ }
+ finally {
+ session.getBatcher().closeStatement( st );
+ }
+
+ }
+ catch ( SQLException sqle ) {
+ throw JDBCExceptionHelper.convert(
+ session.getFactory().getSQLExceptionConverter(),
+ sqle,
+ "could not lock: " + MessageHelper.infoString( lockable, id, session.getFactory() ),
+ sql
+ );
+ }
+ }
+
+ protected String generateLockString() {
+ SessionFactoryImplementor factory = lockable.getFactory();
+ Update update = new Update( factory.getDialect() );
+ update.setTableName( lockable.getRootTableName() );
+ update.addPrimaryKeyColumns( lockable.getRootTableIdentifierColumnNames() );
+ update.setVersionColumnName( lockable.getVersionColumnName() );
+ update.addColumn( lockable.getVersionColumnName() );
+ if ( factory.getSettings().isCommentsEnabled() ) {
+ update.setComment( lockMode + " lock " + lockable.getEntityName() );
+ }
+ return update.toStatementString();
+ }
+
+ protected LockMode getLockMode() {
+ return lockMode;
+ }
+}
\ No newline at end of file
Added: core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteSelectLockingStrategy.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteSelectLockingStrategy.java (rev 0)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteSelectLockingStrategy.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -0,0 +1,148 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.dialect.lock;
+
+import org.hibernate.persister.entity.Lockable;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.engine.SessionFactoryImplementor;
+import org.hibernate.StaleObjectStateException;
+import org.hibernate.JDBCException;
+import org.hibernate.LockMode;
+import org.hibernate.sql.SimpleSelect;
+import org.hibernate.pretty.MessageHelper;
+import org.hibernate.exception.JDBCExceptionHelper;
+
+import java.io.Serializable;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+/**
+ * A pessimistic locking strategy where the locks are obtained through select statements.
+ * <p/>
+ * For non-read locks, this is achieved through the Dialect's specific
+ * SELECT ... FOR UPDATE syntax.
+ *
+ * This strategy is valid for LockMode.PESSIMISTIC_WRITE
+ *
+ * This class is a clone of SelectLockingStrategy.
+ *
+ * @see org.hibernate.dialect.Dialect#getForUpdateString(org.hibernate.LockMode)
+ * @see org.hibernate.dialect.Dialect#appendLockHint(org.hibernate.LockMode, String)
+ * @since 3.5
+ *
+ * @author Steve Ebersole
+ * @author Scott Marlow
+ */
+public class PessimisticWriteSelectLockingStrategy implements LockingStrategy {
+
+ private final Lockable lockable;
+ private final LockMode lockMode;
+ private final String sql;
+
+ /**
+ * Construct a locking strategy based on SQL SELECT statements.
+ *
+ * @param lockable The metadata for the entity to be locked.
+ * @param lockMode Indictates the type of lock to be acquired.
+ */
+ public PessimisticWriteSelectLockingStrategy(Lockable lockable, LockMode lockMode) {
+ this.lockable = lockable;
+ this.lockMode = lockMode;
+ this.sql = generateLockString();
+ }
+
+ /**
+ * @see LockingStrategy#lock
+ */
+ public void lock(
+ Serializable id,
+ Object version,
+ Object object,
+ int timeout, SessionImplementor session) throws StaleObjectStateException, JDBCException {
+
+ SessionFactoryImplementor factory = session.getFactory();
+ try {
+ PreparedStatement st = session.getBatcher().prepareSelectStatement( sql );
+ try {
+ lockable.getIdentifierType().nullSafeSet( st, id, 1, session );
+ if ( lockable.isVersioned() ) {
+ lockable.getVersionType().nullSafeSet(
+ st,
+ version,
+ lockable.getIdentifierType().getColumnSpan( factory ) + 1,
+ session
+ );
+ }
+
+ ResultSet rs = st.executeQuery();
+ try {
+ if ( !rs.next() ) {
+ if ( factory.getStatistics().isStatisticsEnabled() ) {
+ factory.getStatisticsImplementor()
+ .optimisticFailure( lockable.getEntityName() );
+ }
+ throw new StaleObjectStateException( lockable.getEntityName(), id );
+ }
+ }
+ finally {
+ rs.close();
+ }
+ }
+ finally {
+ session.getBatcher().closeStatement( st );
+ }
+
+ }
+ catch ( SQLException sqle ) {
+ throw JDBCExceptionHelper.convert(
+ session.getFactory().getSQLExceptionConverter(),
+ sqle,
+ "could not lock: " + MessageHelper.infoString( lockable, id, session.getFactory() ),
+ sql
+ );
+ }
+ }
+
+ protected LockMode getLockMode() {
+ return lockMode;
+ }
+
+ protected String generateLockString() {
+ SessionFactoryImplementor factory = lockable.getFactory();
+ SimpleSelect select = new SimpleSelect( factory.getDialect() )
+ .setLockMode( lockMode )
+ .setTableName( lockable.getRootTableName() )
+ .addColumn( lockable.getRootTableIdentifierColumnNames()[0] )
+ .addCondition( lockable.getRootTableIdentifierColumnNames(), "=?" );
+ if ( lockable.isVersioned() ) {
+ select.addCondition( lockable.getVersionColumnName(), "=?" );
+ }
+ if ( factory.getSettings().isCommentsEnabled() ) {
+ select.setComment( lockMode + " lock " + lockable.getEntityName() );
+ }
+ return select.toStatementString();
+ }
+}
\ No newline at end of file
Added: core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteUpdateLockingStrategy.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteUpdateLockingStrategy.java (rev 0)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteUpdateLockingStrategy.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -0,0 +1,148 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.dialect.lock;
+
+import java.io.Serializable;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+
+import org.hibernate.HibernateException;
+import org.hibernate.JDBCException;
+import org.hibernate.LockMode;
+import org.hibernate.StaleObjectStateException;
+import org.hibernate.engine.SessionFactoryImplementor;
+import org.hibernate.engine.SessionImplementor;
+import org.hibernate.exception.JDBCExceptionHelper;
+import org.hibernate.persister.entity.Lockable;
+import org.hibernate.pretty.MessageHelper;
+import org.hibernate.sql.Update;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A pessimistic locking strategy where the locks are obtained through update statements.
+ * <p/>
+ * This strategy is valid for LockMode.PESSIMISTIC_WRITE
+ *
+ * This class is a clone of UpdateLockingStrategy.
+ *
+ * @since 3.5
+ *
+ * @author Steve Ebersole
+ * @author Scott Marlow
+ */
+public class PessimisticWriteUpdateLockingStrategy implements LockingStrategy {
+ private static final Logger log = LoggerFactory.getLogger( PessimisticWriteUpdateLockingStrategy.class );
+
+ private final Lockable lockable;
+ private final LockMode lockMode;
+ private final String sql;
+
+ /**
+ * Construct a locking strategy based on SQL UPDATE statements.
+ *
+ * @param lockable The metadata for the entity to be locked.
+ * @param lockMode Indictates the type of lock to be acquired. Note that
+ * read-locks are not valid for this strategy.
+ */
+ public PessimisticWriteUpdateLockingStrategy(Lockable lockable, LockMode lockMode) {
+ this.lockable = lockable;
+ this.lockMode = lockMode;
+ if ( lockMode.lessThan( LockMode.PESSIMISTIC_READ ) ) {
+ throw new HibernateException( "[" + lockMode + "] not valid for update statement" );
+ }
+ if ( !lockable.isVersioned() ) {
+ log.warn( "write locks via update not supported for non-versioned entities [" + lockable.getEntityName() + "]" );
+ this.sql = null;
+ }
+ else {
+ this.sql = generateLockString();
+ }
+ }
+
+ /**
+ * @see LockingStrategy#lock
+ */
+ public void lock(
+ Serializable id,
+ Object version,
+ Object object,
+ int timeout, SessionImplementor session) throws StaleObjectStateException, JDBCException {
+ if ( !lockable.isVersioned() ) {
+ throw new HibernateException( "write locks via update not supported for non-versioned entities [" + lockable.getEntityName() + "]" );
+ }
+ SessionFactoryImplementor factory = session.getFactory();
+ try {
+ PreparedStatement st = session.getBatcher().prepareSelectStatement( sql );
+ try {
+ lockable.getVersionType().nullSafeSet( st, version, 1, session );
+ int offset = 2;
+
+ lockable.getIdentifierType().nullSafeSet( st, id, offset, session );
+ offset += lockable.getIdentifierType().getColumnSpan( factory );
+
+ if ( lockable.isVersioned() ) {
+ lockable.getVersionType().nullSafeSet( st, version, offset, session );
+ }
+
+ int affected = st.executeUpdate();
+ if ( affected < 0 ) { // todo: should this instead check for exactly one row modified?
+ factory.getStatisticsImplementor().optimisticFailure( lockable.getEntityName() );
+ throw new StaleObjectStateException( lockable.getEntityName(), id );
+ }
+
+ }
+ finally {
+ session.getBatcher().closeStatement( st );
+ }
+
+ }
+ catch ( SQLException sqle ) {
+ throw JDBCExceptionHelper.convert(
+ session.getFactory().getSQLExceptionConverter(),
+ sqle,
+ "could not lock: " + MessageHelper.infoString( lockable, id, session.getFactory() ),
+ sql
+ );
+ }
+ }
+
+ protected String generateLockString() {
+ SessionFactoryImplementor factory = lockable.getFactory();
+ Update update = new Update( factory.getDialect() );
+ update.setTableName( lockable.getRootTableName() );
+ update.addPrimaryKeyColumns( lockable.getRootTableIdentifierColumnNames() );
+ update.setVersionColumnName( lockable.getVersionColumnName() );
+ update.addColumn( lockable.getVersionColumnName() );
+ if ( factory.getSettings().isCommentsEnabled() ) {
+ update.setComment( lockMode + " lock " + lockable.getEntityName() );
+ }
+ return update.toStatementString();
+ }
+
+ protected LockMode getLockMode() {
+ return lockMode;
+ }
+}
\ No newline at end of file
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/lock/SelectLockingStrategy.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/lock/SelectLockingStrategy.java 2009-11-11 22:20:48 UTC (rev 17961)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/lock/SelectLockingStrategy.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -76,6 +76,7 @@
Serializable id,
Object version,
Object object,
+ int timeout,
SessionImplementor session) throws StaleObjectStateException, JDBCException {
SessionFactoryImplementor factory = session.getFactory();
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/lock/UpdateLockingStrategy.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/lock/UpdateLockingStrategy.java 2009-11-11 22:20:48 UTC (rev 17961)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/lock/UpdateLockingStrategy.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -83,9 +83,10 @@
* @see LockingStrategy#lock
*/
public void lock(
- Serializable id,
+ Serializable id,
Object version,
Object object,
+ int timeout,
SessionImplementor session) throws StaleObjectStateException, JDBCException {
if ( !lockable.isVersioned() ) {
throw new HibernateException( "write locks via update not supported for non-versioned entities [" + lockable.getEntityName() + "]" );
Modified: core/trunk/core/src/main/java/org/hibernate/event/def/AbstractLockUpgradeEventListener.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/event/def/AbstractLockUpgradeEventListener.java 2009-11-11 22:20:48 UTC (rev 17961)
+++ core/trunk/core/src/main/java/org/hibernate/event/def/AbstractLockUpgradeEventListener.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -100,27 +100,13 @@
}
try {
- if ( persister.isVersioned() && (requestedLockMode == LockMode.FORCE || requestedLockMode == LockMode.PESSIMISTIC_FORCE_INCREMENT ) ) {
+ if ( persister.isVersioned() && requestedLockMode == LockMode.FORCE ) {
// todo : should we check the current isolation mode explicitly?
Object nextVersion = persister.forceVersionIncrement(
entry.getId(), entry.getVersion(), source
);
entry.forceLocked( object, nextVersion );
}
- else if ( requestedLockMode == LockMode.OPTIMISTIC_FORCE_INCREMENT ) {
- if(!persister.isVersioned()) {
- throw new OptimisticLockException("force: Version column is not mapped for " + entry.getPersister().getEntityName(), object);
- }
- EntityIncrementVersionProcess incrementVersion = new EntityIncrementVersionProcess(object, entry);
- source.getActionQueue().registerProcess(incrementVersion);
- }
- else if ( requestedLockMode == LockMode.OPTIMISTIC ) {
- if(!persister.isVersioned()) {
- throw new OptimisticLockException("Version column is not mapped for " + entry.getPersister().getEntityName(), object);
- }
- EntityVerifyVersionProcess verifyVersion = new EntityVerifyVersionProcess(object, entry);
- source.getActionQueue().registerProcess(verifyVersion);
- }
else {
persister.lock( entry.getId(), entry.getVersion(), object, requestedLockMode, source );
}
Modified: core/trunk/core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java 2009-11-11 22:20:48 UTC (rev 17961)
+++ core/trunk/core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java 2009-11-12 04:20:41 UTC (rev 17962)
@@ -1412,7 +1412,7 @@
Object object,
LockMode lockMode,
SessionImplementor session) throws HibernateException {
- getLocker( lockMode ).lock( id, version, object, session );
+ getLocker( lockMode ).lock( id, version, object, -1, session );
}
public String getRootTableName() {
15 years, 1 month
Hibernate SVN: r17961 - in core/trunk/entitymanager/src: test/java/org/hibernate/ejb/test and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2009-11-11 17:20:48 -0500 (Wed, 11 Nov 2009)
New Revision: 17961
Modified:
core/trunk/entitymanager/src/main/java/org/hibernate/ejb/QueryImpl.java
core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/QueryTest.java
Log:
HHH-4567 - EntiytManager's QueryImpl mishandles ordinal position of HQL-style positional parameters
Modified: core/trunk/entitymanager/src/main/java/org/hibernate/ejb/QueryImpl.java
===================================================================
--- core/trunk/entitymanager/src/main/java/org/hibernate/ejb/QueryImpl.java 2009-11-11 20:36:03 UTC (rev 17960)
+++ core/trunk/entitymanager/src/main/java/org/hibernate/ejb/QueryImpl.java 2009-11-11 22:20:48 UTC (rev 17961)
@@ -75,7 +75,7 @@
extractParameterInfo();
}
- @SuppressWarnings({ "unchecked" })
+ @SuppressWarnings({ "unchecked", "RedundantCast" })
private void extractParameterInfo() {
if ( ! AbstractQueryImpl.class.isInstance( query ) ) {
throw new IllegalStateException( "Unknown query type for parameter extraction" );
@@ -108,7 +108,7 @@
final OrdinalParameterDescriptor descriptor =
queryImpl.getParameterMetadata().getOrdinalParameterDescriptor( i+1 );
ParameterImpl parameter = new ParameterImpl(
- descriptor.getOrdinalPosition() + 1,
+ i + 1,
descriptor.getExpectedType() == null
? null
: descriptor.getExpectedType().getReturnedClass()
@@ -204,7 +204,7 @@
/**
* {@inheritDoc}
*/
- @SuppressWarnings({ "unchecked" })
+ @SuppressWarnings({ "unchecked", "RedundantCast" })
public List<X> getResultList() {
try {
return (List<X>) query.list();
@@ -223,7 +223,7 @@
/**
* {@inheritDoc}
*/
- @SuppressWarnings({ "unchecked" })
+ @SuppressWarnings({ "unchecked", "RedundantCast" })
public X getSingleResult() {
try {
boolean mucked = false;
Modified: core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/QueryTest.java
===================================================================
--- core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/QueryTest.java 2009-11-11 20:36:03 UTC (rev 17960)
+++ core/trunk/entitymanager/src/test/java/org/hibernate/ejb/test/QueryTest.java 2009-11-11 22:20:48 UTC (rev 17961)
@@ -212,6 +212,40 @@
em.close();
}
+ public void testPositionalParameterForms() throws Exception {
+ EntityManager em = getOrCreateEntityManager();
+ em.getTransaction().begin();
+ Wallet w = new Wallet();
+ w.setBrand( "Lacoste" );
+ w.setModel( "Minimic" );
+ w.setSerial( "0100202002" );
+ em.persist( w );
+ em.getTransaction().commit();
+
+ em.getTransaction().begin();
+ // first using jpa-style positional parameter
+ Query query = em.createQuery( "select w from Wallet w where w.brand = ?1" );
+ query.setParameter( 1, "Lacoste" );
+ w = (Wallet) query.getSingleResult();
+ assertNotNull( w );
+
+ // next using jpa-style positional parameter, but as a name (which is how Hibernate core treats these
+ query = em.createQuery( "select w from Wallet w where w.brand = ?1" );
+ query.setParameter( "1", "Lacoste" );
+ w = (Wallet) query.getSingleResult();
+ assertNotNull( w );
+
+ // finally using hql-style positional parameter
+ query = em.createQuery( "select w from Wallet w where w.brand = ?" );
+ query.setParameter( 1, "Lacoste" );
+ w = (Wallet) query.getSingleResult();
+ assertNotNull( w );
+
+ em.remove( w );
+ em.getTransaction().commit();
+ em.close();
+ }
+
public void testNativeQuestionMarkParameter() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
15 years, 1 month
Hibernate SVN: r17960 - in core/branches/Branch_3_3: core/src/main/java/org/hibernate/util and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2009-11-11 15:36:03 -0500 (Wed, 11 Nov 2009)
New Revision: 17960
Modified:
core/branches/Branch_3_3/core/src/main/java/org/hibernate/engine/query/QueryPlanCache.java
core/branches/Branch_3_3/core/src/main/java/org/hibernate/util/CollectionHelper.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java
Log:
HHH-4065 - Incorrect SQL is used for HQL if the number of values for a filter collection parameter is changed
Modified: core/branches/Branch_3_3/core/src/main/java/org/hibernate/engine/query/QueryPlanCache.java
===================================================================
--- core/branches/Branch_3_3/core/src/main/java/org/hibernate/engine/query/QueryPlanCache.java 2009-11-11 20:27:39 UTC (rev 17959)
+++ core/branches/Branch_3_3/core/src/main/java/org/hibernate/engine/query/QueryPlanCache.java 2009-11-11 20:36:03 UTC (rev 17960)
@@ -26,10 +26,13 @@
import org.hibernate.util.SimpleMRUCache;
import org.hibernate.util.SoftLimitMRUCache;
+import org.hibernate.util.CollectionHelper;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.query.sql.NativeSQLQuerySpecification;
import org.hibernate.QueryException;
import org.hibernate.MappingException;
+import org.hibernate.impl.FilterImpl;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -40,6 +43,7 @@
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
+import java.util.Collection;
/**
* Acts as a cache for compiled query plans, as well as query-parameter metadata.
@@ -174,7 +178,7 @@
private static class HQLQueryPlanKey implements Serializable {
private final String query;
private final boolean shallow;
- private final Set filterNames;
+ private final Set filterKeys;
private final int hashCode;
public HQLQueryPlanKey(String query, boolean shallow, Map enabledFilters) {
@@ -182,17 +186,23 @@
this.shallow = shallow;
if ( enabledFilters == null || enabledFilters.isEmpty() ) {
- filterNames = Collections.EMPTY_SET;
+ filterKeys = Collections.EMPTY_SET;
}
else {
- Set tmp = new HashSet();
- tmp.addAll( enabledFilters.keySet() );
- this.filterNames = Collections.unmodifiableSet( tmp );
+ Set tmp = new HashSet(
+ CollectionHelper.determineProperSizing( enabledFilters ),
+ CollectionHelper.LOAD_FACTOR
+ );
+ Iterator itr = enabledFilters.values().iterator();
+ while ( itr.hasNext() ) {
+ tmp.add( new DynamicFilterKey( ( FilterImpl ) itr.next() ) );
+ }
+ this.filterKeys = Collections.unmodifiableSet( tmp );
}
int hash = query.hashCode();
hash = 29 * hash + ( shallow ? 1 : 0 );
- hash = 29 * hash + filterNames.hashCode();
+ hash = 29 * hash + filterKeys.hashCode();
this.hashCode = hash;
}
@@ -206,17 +216,63 @@
final HQLQueryPlanKey that = ( HQLQueryPlanKey ) o;
- if ( shallow != that.shallow ) {
- return false;
+ return shallow == that.shallow
+ && filterKeys.equals( that.filterKeys )
+ && query.equals( that.query );
+ }
+
+ public int hashCode() {
+ return hashCode;
+ }
+ }
+
+ private static class DynamicFilterKey implements Serializable {
+ private final String filterName;
+ private final Map parameterMetadata;
+ private final int hashCode;
+
+ private DynamicFilterKey(FilterImpl filter) {
+ this.filterName = filter.getName();
+ if ( filter.getParameters().isEmpty() ) {
+ parameterMetadata = Collections.EMPTY_MAP;
}
- if ( !filterNames.equals( that.filterNames ) ) {
- return false;
+ else {
+ parameterMetadata = new HashMap(
+ CollectionHelper.determineProperSizing( filter.getParameters() ),
+ CollectionHelper.LOAD_FACTOR
+ );
+ Iterator itr = filter.getParameters().entrySet().iterator();
+ while ( itr.hasNext() ) {
+ final Integer valueCount;
+ final Map.Entry entry = ( Map.Entry ) itr.next();
+ if ( Collection.class.isInstance( entry.getValue() ) ) {
+ valueCount = new Integer( ( (Collection) entry.getValue() ).size() );
+ }
+ else {
+ valueCount = new Integer(1);
+ }
+ parameterMetadata.put( entry.getKey(), valueCount );
+ }
}
- if ( !query.equals( that.query ) ) {
+
+ int hash = filterName.hashCode();
+ hash = 31 * hash + parameterMetadata.hashCode();
+ this.hashCode = hash;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) {
+ return true;
+ }
+ if ( o == null || getClass() != o.getClass() ) {
return false;
}
- return true;
+ DynamicFilterKey that = ( DynamicFilterKey ) o;
+
+ return filterName.equals( that.filterName )
+ && parameterMetadata.equals( that.parameterMetadata );
+
}
public int hashCode() {
@@ -262,20 +318,10 @@
final FilterQueryPlanKey that = ( FilterQueryPlanKey ) o;
- if ( shallow != that.shallow ) {
- return false;
- }
- if ( !filterNames.equals( that.filterNames ) ) {
- return false;
- }
- if ( !query.equals( that.query ) ) {
- return false;
- }
- if ( !collectionRole.equals( that.collectionRole ) ) {
- return false;
- }
-
- return true;
+ return shallow == that.shallow
+ && filterNames.equals( that.filterNames )
+ && query.equals( that.query )
+ && collectionRole.equals( that.collectionRole );
}
public int hashCode() {
Modified: core/branches/Branch_3_3/core/src/main/java/org/hibernate/util/CollectionHelper.java
===================================================================
--- core/branches/Branch_3_3/core/src/main/java/org/hibernate/util/CollectionHelper.java 2009-11-11 20:27:39 UTC (rev 17959)
+++ core/branches/Branch_3_3/core/src/main/java/org/hibernate/util/CollectionHelper.java 2009-11-11 20:36:03 UTC (rev 17960)
@@ -29,6 +29,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
/**
* Various help for handling collections.
@@ -37,11 +38,13 @@
* @author Steve Ebersole
*/
public final class CollectionHelper {
+ public static final int MINIMUM_INITIAL_CAPACITY = 16;
+ public static final float LOAD_FACTOR = 0.75f;
public static final List EMPTY_LIST = Collections.unmodifiableList( new ArrayList(0) );
public static final Collection EMPTY_COLLECTION = Collections.unmodifiableCollection( new ArrayList(0) );
public static final Map EMPTY_MAP = Collections.unmodifiableMap( new HashMap(0) );
-
+
private CollectionHelper() {
}
@@ -54,7 +57,40 @@
* @return The sized map.
*/
public static Map mapOfSize(int size) {
- final int currentSize = (int) (size / 0.75f);
- return new HashMap( Math.max( currentSize+ 1, 16), 0.75f );
+ return new HashMap( determineProperSizing( size ), LOAD_FACTOR );
}
+
+ /**
+ * Given a map, determine the proper initial size for a new Map to hold the same number of values.
+ * Specifically we want to account for load size and load factor to prevent immediate resizing.
+ *
+ * @param original The original map
+ * @return The proper size.
+ */
+ public static int determineProperSizing(Map original) {
+ return determineProperSizing( original.size() );
+ }
+
+ /**
+ * Given a set, determine the proper initial size for a new set to hold the same number of values.
+ * Specifically we want to account for load size and load factor to prevent immediate resizing.
+ *
+ * @param original The original set
+ * @return The proper size.
+ */
+ public static int determineProperSizing(Set original) {
+ return determineProperSizing( original.size() );
+ }
+
+ /**
+ * Determine the proper initial size for a new collection in order for it to hold the given a number of elements.
+ * Specifically we want to account for load size and load factor to prevent immediate resizing.
+ *
+ * @param numberOfElements The number of elements to be stored.
+ * @return The proper size.
+ */
+ public static int determineProperSizing(int numberOfElements) {
+ int actual = ( (int) (numberOfElements / LOAD_FACTOR) ) + 1;
+ return Math.max( actual, MINIMUM_INITIAL_CAPACITY );
+ }
}
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java 2009-11-11 20:27:39 UTC (rev 17959)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java 2009-11-11 20:36:03 UTC (rev 17960)
@@ -39,6 +39,7 @@
*
* @author Steve
*/
+@SuppressWarnings({ "WhileLoopReplaceableByForEach", "unchecked" })
public class DynamicFilterTest extends FunctionalTestCase {
private Logger log = LoggerFactory.getLogger( DynamicFilterTest.class );
@@ -99,7 +100,7 @@
ts = ( ( SessionImplementor ) session ).getTimestamp();
session.enableFilter( "fulfilledOrders" ).setParameter( "asOfDate", testData.lastMonth.getTime() );
sp = ( Salesperson ) session.createQuery( "from Salesperson as s where s.id = :id" )
- .setLong( "id", testData.steveId.longValue() )
+ .setLong( "id", testData.steveId )
.uniqueResult();
assertEquals( "Filtered-collection not bypassing 2L-cache", 1, sp.getOrders().size() );
@@ -142,6 +143,17 @@
session.clear();
+ session.disableFilter( "regionlist" );
+ session.enableFilter( "regionlist" ).setParameterList( "regions", new String[]{"LA", "APAC", "APAC"} );
+ // Second test retreival through hql with the collection as non-eager with different region list
+ salespersons = session.createQuery( "select s from Salesperson as s" ).list();
+ assertEquals( "Incorrect salesperson count", 1, salespersons.size() );
+ sp = ( Salesperson ) salespersons.get( 0 );
+ assertEquals( "Incorrect order count", 1, sp.getOrders().size() );
+
+ session.clear();
+
+
// test retreival through hql with the collection join fetched
salespersons = session.createQuery( "select s from Salesperson as s left join fetch s.orders" ).list();
assertEquals( "Incorrect salesperson count", 1, salespersons.size() );
@@ -206,7 +218,7 @@
log.info( "Criteria query against Product..." );
List products = session.createCriteria( Product.class )
- .add( Restrictions.eq( "stockNumber", new Integer( 124 ) ) )
+ .add( Restrictions.eq( "stockNumber", 124 ) )
.list();
assertEquals( "Incorrect product count", 1, products.size() );
@@ -644,7 +656,7 @@
// Force the categories to not get initialized here
List result = session.createQuery( "from Product as p where p.id = :id" )
- .setLong( "id", testData.prod1Id.longValue() )
+ .setLong( "id", testData.prod1Id )
.list();
assertTrue( "No products returned from HQL", !result.isEmpty() );
15 years, 1 month
Hibernate SVN: r17959 - in core/trunk: core/src/main/java/org/hibernate/util and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2009-11-11 15:27:39 -0500 (Wed, 11 Nov 2009)
New Revision: 17959
Modified:
core/trunk/core/src/main/java/org/hibernate/engine/query/QueryPlanCache.java
core/trunk/core/src/main/java/org/hibernate/util/CollectionHelper.java
core/trunk/testsuite/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java
Log:
HHH-4065 - Incorrect SQL is used for HQL if the number of values for a filter collection parameter is changed
Modified: core/trunk/core/src/main/java/org/hibernate/engine/query/QueryPlanCache.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/engine/query/QueryPlanCache.java 2009-11-11 18:56:29 UTC (rev 17958)
+++ core/trunk/core/src/main/java/org/hibernate/engine/query/QueryPlanCache.java 2009-11-11 20:27:39 UTC (rev 17959)
@@ -26,10 +26,13 @@
import org.hibernate.util.SimpleMRUCache;
import org.hibernate.util.SoftLimitMRUCache;
+import org.hibernate.util.CollectionHelper;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.query.sql.NativeSQLQuerySpecification;
import org.hibernate.QueryException;
import org.hibernate.MappingException;
+import org.hibernate.impl.FilterImpl;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -40,6 +43,7 @@
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
+import java.util.Collection;
/**
* Acts as a cache for compiled query plans, as well as query-parameter metadata.
@@ -174,7 +178,7 @@
private static class HQLQueryPlanKey implements Serializable {
private final String query;
private final boolean shallow;
- private final Set filterNames;
+ private final Set filterKeys;
private final int hashCode;
public HQLQueryPlanKey(String query, boolean shallow, Map enabledFilters) {
@@ -182,17 +186,23 @@
this.shallow = shallow;
if ( enabledFilters == null || enabledFilters.isEmpty() ) {
- filterNames = Collections.EMPTY_SET;
+ filterKeys = Collections.EMPTY_SET;
}
else {
- Set tmp = new HashSet();
- tmp.addAll( enabledFilters.keySet() );
- this.filterNames = Collections.unmodifiableSet( tmp );
+ Set tmp = new HashSet(
+ CollectionHelper.determineProperSizing( enabledFilters ),
+ CollectionHelper.LOAD_FACTOR
+ );
+ Iterator itr = enabledFilters.values().iterator();
+ while ( itr.hasNext() ) {
+ tmp.add( new DynamicFilterKey( ( FilterImpl ) itr.next() ) );
+ }
+ this.filterKeys = Collections.unmodifiableSet( tmp );
}
int hash = query.hashCode();
hash = 29 * hash + ( shallow ? 1 : 0 );
- hash = 29 * hash + filterNames.hashCode();
+ hash = 29 * hash + filterKeys.hashCode();
this.hashCode = hash;
}
@@ -206,17 +216,64 @@
final HQLQueryPlanKey that = ( HQLQueryPlanKey ) o;
- if ( shallow != that.shallow ) {
- return false;
+ return shallow == that.shallow
+ && filterKeys.equals( that.filterKeys )
+ && query.equals( that.query );
+
+ }
+
+ public int hashCode() {
+ return hashCode;
+ }
+ }
+
+ private static class DynamicFilterKey implements Serializable {
+ private final String filterName;
+ private final Map parameterMetadata;
+ private final int hashCode;
+
+ private DynamicFilterKey(FilterImpl filter) {
+ this.filterName = filter.getName();
+ if ( filter.getParameters().isEmpty() ) {
+ parameterMetadata = Collections.EMPTY_MAP;
}
- if ( !filterNames.equals( that.filterNames ) ) {
- return false;
+ else {
+ parameterMetadata = new HashMap(
+ CollectionHelper.determineProperSizing( filter.getParameters() ),
+ CollectionHelper.LOAD_FACTOR
+ );
+ Iterator itr = filter.getParameters().entrySet().iterator();
+ while ( itr.hasNext() ) {
+ final Integer valueCount;
+ final Map.Entry entry = ( Map.Entry ) itr.next();
+ if ( Collection.class.isInstance( entry.getValue() ) ) {
+ valueCount = new Integer( ( (Collection) entry.getValue() ).size() );
+ }
+ else {
+ valueCount = new Integer(1);
+ }
+ parameterMetadata.put( entry.getKey(), valueCount );
+ }
}
- if ( !query.equals( that.query ) ) {
+
+ int hash = filterName.hashCode();
+ hash = 31 * hash + parameterMetadata.hashCode();
+ this.hashCode = hash;
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) {
+ return true;
+ }
+ if ( o == null || getClass() != o.getClass() ) {
return false;
}
- return true;
+ DynamicFilterKey that = ( DynamicFilterKey ) o;
+
+ return filterName.equals( that.filterName )
+ && parameterMetadata.equals( that.parameterMetadata );
+
}
public int hashCode() {
@@ -262,20 +319,11 @@
final FilterQueryPlanKey that = ( FilterQueryPlanKey ) o;
- if ( shallow != that.shallow ) {
- return false;
- }
- if ( !filterNames.equals( that.filterNames ) ) {
- return false;
- }
- if ( !query.equals( that.query ) ) {
- return false;
- }
- if ( !collectionRole.equals( that.collectionRole ) ) {
- return false;
- }
+ return shallow == that.shallow
+ && filterNames.equals( that.filterNames )
+ && query.equals( that.query )
+ && collectionRole.equals( that.collectionRole );
- return true;
}
public int hashCode() {
Modified: core/trunk/core/src/main/java/org/hibernate/util/CollectionHelper.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/util/CollectionHelper.java 2009-11-11 18:56:29 UTC (rev 17958)
+++ core/trunk/core/src/main/java/org/hibernate/util/CollectionHelper.java 2009-11-11 20:27:39 UTC (rev 17959)
@@ -29,6 +29,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
/**
* Various help for handling collections.
@@ -37,6 +38,8 @@
* @author Steve Ebersole
*/
public final class CollectionHelper {
+ public static final int MINIMUM_INITIAL_CAPACITY = 16;
+ public static final float LOAD_FACTOR = 0.75f;
public static final List EMPTY_LIST = Collections.unmodifiableList( new ArrayList(0) );
public static final Collection EMPTY_COLLECTION = Collections.unmodifiableCollection( new ArrayList(0) );
@@ -54,7 +57,40 @@
* @return The sized map.
*/
public static Map mapOfSize(int size) {
- final int currentSize = (int) (size / 0.75f);
- return new HashMap( Math.max( currentSize+ 1, 16), 0.75f );
+ return new HashMap( determineProperSizing( size ), LOAD_FACTOR );
}
+
+ /**
+ * Given a map, determine the proper initial size for a new Map to hold the same number of values.
+ * Specifically we want to account for load size and load factor to prevent immediate resizing.
+ *
+ * @param original The original map
+ * @return The proper size.
+ */
+ public static int determineProperSizing(Map original) {
+ return determineProperSizing( original.size() );
+ }
+
+ /**
+ * Given a set, determine the proper initial size for a new set to hold the same number of values.
+ * Specifically we want to account for load size and load factor to prevent immediate resizing.
+ *
+ * @param original The original set
+ * @return The proper size.
+ */
+ public static int determineProperSizing(Set original) {
+ return determineProperSizing( original.size() );
+ }
+
+ /**
+ * Determine the proper initial size for a new collection in order for it to hold the given a number of elements.
+ * Specifically we want to account for load size and load factor to prevent immediate resizing.
+ *
+ * @param numberOfElements The number of elements to be stored.
+ * @return The proper size.
+ */
+ public static int determineProperSizing(int numberOfElements) {
+ int actual = ( (int) (numberOfElements / LOAD_FACTOR) ) + 1;
+ return Math.max( actual, MINIMUM_INITIAL_CAPACITY );
+ }
}
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java 2009-11-11 18:56:29 UTC (rev 17958)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/filter/DynamicFilterTest.java 2009-11-11 20:27:39 UTC (rev 17959)
@@ -39,6 +39,7 @@
*
* @author Steve
*/
+@SuppressWarnings({ "WhileLoopReplaceableByForEach", "unchecked" })
public class DynamicFilterTest extends FunctionalTestCase {
private Logger log = LoggerFactory.getLogger( DynamicFilterTest.class );
@@ -99,7 +100,7 @@
ts = ( ( SessionImplementor ) session ).getTimestamp();
session.enableFilter( "fulfilledOrders" ).setParameter( "asOfDate", testData.lastMonth.getTime() );
sp = ( Salesperson ) session.createQuery( "from Salesperson as s where s.id = :id" )
- .setLong( "id", testData.steveId.longValue() )
+ .setLong( "id", testData.steveId )
.uniqueResult();
assertEquals( "Filtered-collection not bypassing 2L-cache", 1, sp.getOrders().size() );
@@ -142,6 +143,17 @@
session.clear();
+ session.disableFilter("regionlist");
+ session.enableFilter( "regionlist" ).setParameterList( "regions", new String[]{"LA", "APAC", "APAC"} );
+ // Second test retreival through hql with the collection as non-eager with different region list
+ salespersons = session.createQuery( "select s from Salesperson as s" ).list();
+ assertEquals( "Incorrect salesperson count", 1, salespersons.size() );
+ sp = ( Salesperson ) salespersons.get( 0 );
+ assertEquals( "Incorrect order count", 1, sp.getOrders().size() );
+
+ session.clear();
+
+
// test retreival through hql with the collection join fetched
salespersons = session.createQuery( "select s from Salesperson as s left join fetch s.orders" ).list();
assertEquals( "Incorrect salesperson count", 1, salespersons.size() );
@@ -224,7 +236,7 @@
log.info( "Criteria query against Product..." );
List products = session.createCriteria( Product.class )
- .add( Restrictions.eq( "stockNumber", new Integer( 124 ) ) )
+ .add( Restrictions.eq( "stockNumber", 124 ) )
.list();
assertEquals( "Incorrect product count", 1, products.size() );
@@ -288,10 +300,10 @@
session.enableFilter("region").setParameter("region", "APAC");
DetachedCriteria lineItemSubquery = DetachedCriteria.forClass(LineItem.class)
- .add(Restrictions.ge( "quantity", new Long(1L) ))
- .createCriteria("product")
- .add(Restrictions.eq("name", "Acme Hair Gel"))
- .setProjection(Property.forName("id"));
+ .add( Restrictions.ge( "quantity", 1L ) )
+ .createCriteria( "product" )
+ .add( Restrictions.eq( "name", "Acme Hair Gel" ) )
+ .setProjection( Property.forName( "id" ) );
List orders = session.createCriteria(Order.class)
.add(Subqueries.exists(lineItemSubquery))
@@ -309,7 +321,7 @@
.setProjection(Property.forName("id"));
lineItemSubquery = DetachedCriteria.forClass(LineItem.class)
- .add(Restrictions.ge("quantity", new Long(1L) ))
+ .add(Restrictions.ge("quantity", 1L ))
.createCriteria("product")
.add(Subqueries.propertyIn("id", productSubquery))
.setProjection(Property.forName("id"));
@@ -662,7 +674,7 @@
// Force the categories to not get initialized here
List result = session.createQuery( "from Product as p where p.id = :id" )
- .setLong( "id", testData.prod1Id.longValue() )
+ .setLong( "id", testData.prod1Id )
.list();
assertTrue( "No products returned from HQL", !result.isEmpty() );
15 years, 1 month