diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a157cac46f..0ad0a0323a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -8,18 +8,20 @@ contributing to a minimum, there are a few guidelines we ask that you mind.
If you are just getting started with Git, GitHub and/or contributing to Hibernate via
GitHub there are a few pre-requisite steps.
+* Make sure you have signed a [Contributor License Aggrement](https://cla.jboss.org) (CLA) for the Hibernate project
* Make sure you have a [Hibernate Jira account](https://hibernate.onjira.com)
* Make sure you have a [GitHub account](https://github.com/signup/free)
* [Fork](http://help.github.com/fork-a-repo) the Hibernate repository. As discussed in
the linked page, this also includes:
* [Set](https://help.github.com/articles/set-up-git) up your local git install
* Clone your fork
-
+* See the wiki pages for setting up your IDE, whether you use [IntelliJ IDEA](https://community.jboss.org/wiki/ContributingToHibernateUsingIntelliJ)
+or [Eclipse](https://community.jboss.org/wiki/ContributingToHibernateUsingEclipse).
## Create the working (topic) branch
-Create a "topic" branch on which you will work. The convention is to name the branch
-using the JIRA issue key. If there is not already a Jira issue covering the work you
-want to do, create one. Assuming you will be working from the master branch and working
+Create a [topic branch](http://git-scm.com/book/en/Git-Branching-Branching-Workflows#Topic-Branches) on which you
+will work. The convention is to name the branch using the JIRA issue key. If there is not already a Jira issue
+covering the work you want to do, create one. Assuming you will be working from the master branch and working
on the Jira HHH-123 : `git checkout -b HHH-123 master`
@@ -39,7 +41,7 @@ appreciated btw), please use rebasing rather than merging. Merging creates
"merge commits" that really muck up the project timeline._
## Submit
-* Sign the [Contributor License Agreement](https://cla.jboss.org/index.seam).
-* Push your changes to a topic branch in your fork of the repository.
+* If you have not already, sign the [Contributor License Agreement](https://cla.jboss.org).
+* Push your changes to the topic branch in your fork of the repository.
* Initiate a [pull request](http://help.github.com/send-pull-requests/)
* Update the Jira issue, adding a comment inclusing a link to the created pull request
diff --git a/build.gradle b/build.gradle
index 1ee0216333..06afcd59bf 100644
--- a/build.gradle
+++ b/build.gradle
@@ -348,14 +348,30 @@ subprojects { subProject ->
ignoreFailures = true
}
// exclude generated sources
- checkstyleMain.exclude '**/generated-src/**'
+ // unfortunately this nice easy approach does not seem to work : http://forums.gradle.org/gradle/topics/specify_excludes_to_checkstyle_task
+ //checkstyleMain.exclude '**/generated-src/**'
+ checkstyleMain.exclude '**/org/hibernate/hql/internal/antlr/**'
+ checkstyleMain.exclude '**/org/hibernate/hql/internal/antlr/*'
+ checkstyleMain.exclude '**/org/hibernate/sql/ordering/antlr/*'
+ checkstyleMain.exclude '**/*_$logger*'
+ checkstyleMain.exclude '**/org/hibernate/internal/jaxb/**'
// because cfg package is a mess mainly from annotation stuff
checkstyleMain.exclude '**/org/hibernate/cfg/**'
checkstyleMain.exclude '**/org/hibernate/cfg/*'
findbugs {
+ sourceSets = [ subProject.sourceSets.main, subProject.sourceSets.test ]
ignoreFailures = true
}
+ // exclude generated sources
+ // unfortunately this nice easy approach does not seem to work : http://forums.gradle.org/gradle/topics/specify_excludes_to_checkstyle_task
+ //findbugsMain.exclude '**/generated-src/**'
+ findbugsMain.exclude '**/org/hibernate/hql/internal/antlr/**'
+ findbugsMain.exclude '**/org/hibernate/hql/internal/antlr/*'
+ findbugsMain.exclude '**/org/hibernate/sql/ordering/antlr/*'
+ findbugsMain.exclude '**/*_$logger*'
+ findbugsMain.exclude '**/org/hibernate/internal/jaxb/**'
+
buildDashboard.dependsOn check
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/buildSrc/src/main/groovy/org/hibernate/build/gradle/util/Jdk.java b/buildSrc/src/main/groovy/org/hibernate/build/gradle/util/Jdk.java
index 4eb21f61b0..4921414f40 100644
--- a/buildSrc/src/main/groovy/org/hibernate/build/gradle/util/Jdk.java
+++ b/buildSrc/src/main/groovy/org/hibernate/build/gradle/util/Jdk.java
@@ -129,7 +129,10 @@ public class Jdk {
try {
final File javaCommand = getJavaExecutable();
- Process javaProcess = Runtime.getRuntime().exec( javaCommand.getAbsolutePath() + " -version" );
+
+ // Fix build for e.g. windows when path to java command contains spaces
+ // Using the array for Runtime.exec will make sure that arguments with spaces get quoted
+ Process javaProcess = Runtime.getRuntime().exec( new String[]{javaCommand.getAbsolutePath(), "-version"} );
try {
version = extractVersion( new BufferedReader( new InputStreamReader( javaProcess.getErrorStream() ) ) );
diff --git a/changelog.txt b/changelog.txt
index 1f6a846cb6..aaa3e4ae16 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -5,6 +5,68 @@ match the actual issue resolution (i.e. a bug might not be a bug). Please
refer to the particular case on JIRA using the issue tracking number to learn
more about each case.
+Changes in version 4.3.0.Beta2 (2013.05.02)
+------------------------------------------------------------------------------------------------------------------------
+https://hibernate.atlassian.net/browse/HHH/fixforversion/13052
+
+** Sub-task
+ * [HHH-7617] - Gradle eclipse task missing src paths and test source generation
+ * [HHH-7943] - C3P0, Proxool, ehcache, and infinispan services for OSGi
+ * [HHH-7944] - Envers OSGi support
+ * [HHH-7993] - Support jar scanning in OSGi
+ * [HHH-7995] - Auto-discovery of Hibernate extension points in OSGi
+ * [HHH-8141] - Upgrade to Gradle 1.5
+ * [HHH-8142] - Create a 'compile' task that performs all copmpilations
+ * [HHH-8143] - Create a 'generateSources' task that performs all generation tasks
+ * [HHH-8145] - Add MaxPermSize to test configuration
+ * [HHH-8146] - Update to use maven-publishing plugin
+ * [HHH-8147] - Update to use distribution plugin for createing release bundles
+ * [HHH-8151] - Consolidate defining "java language level" in one place
+ * [HHH-8152] - General cleanup
+ * [HHH-8156] - Apply new Gradle plugins
+ * [HHH-8160] - Integrate with Aries JPA 2.1 branch
+
+** Bug
+ * [HHH-5845] - Lazy Loading of audited entites with revision type 'delete'
+ * [HHH-7357] - Incorrect exception translation when using Oracle
+ * [HHH-7478] - ConcurrentModificationException when adding a BeforeTransactionCompletionProcess from with a PostInsertEventListener for an @Audited entity
+ * [HHH-7880] - SessionFactory.openStatelessSession() does not respect tenant identifier from CurrentTenantIdentifierResolver
+ * [HHH-7974] - Session.getTenantIdentifier() not callable without active transaction
+ * [HHH-8049] - Initialization error with mapping
+ * [HHH-8084] - LobMergeTest fails on oracle
+ * [HHH-8103] - Oracle LOB ordering not working with SequenceIdentityGenerator
+ * [HHH-8137] - Javadoc generation is currently not playing nicely with Java7 javadoc changes
+ * [HHH-8171] - Auditing of collections of embeddables only supporting single element changes
+ * [HHH-8173] - AvailableSettings constants for javax.persistence.schema-generation contain space
+ * [HHH-8178] - Natural IDs generating one UniqueKey per Column
+ * [HHH-8182] - Correct intermittent UpgradeLockTest failures
+ * [HHH-8189] - Audit records are not rolled back when transaction is rolled back
+ * [HHH-8207] - Locale conversion is broken
+ * [HHH-8215] - Windows Build with Eclipse does not work
+
+** Deprecation
+ * [HHH-8170] - Deprecate Hibernate @ForeignKey in favor of JPA 2.1 introduced @ForeignKey annotation
+
+** Improvement
+ * [HHH-7605] - Provide details "An entity copy was already assigned to a different entity."
+ * [HHH-7908] - Logging level checking.
+ * [HHH-8138] - Log SQLException in DatabaseTarget with cause of schema export CREATE statement failure
+ * [HHH-8159] - Apply fixups indicated by analysis tools
+ * [HHH-8162] - Make unique constraint handling on schema update configurable
+ * [HHH-8167] - Adding @NotNull to a @ManyToOne association with @JoinColumnsOrFormulas leads to ClassCastException
+ * [HHH-8180] - Improve performance of logging level checks
+ * [HHH-8183] - Also support synonyms for schema validation
+
+** New Feature
+ * [HHH-8157] - Adding DBAllocator labels for new DBs
+ * [HHH-8163] - Deprecate @IndexColumn and add @ListIndexBase
+
+** Task
+ * [HHH-8164] - Deprecate @Sort in favor of @SortNatural and @SortComparator
+ * [HHH-8175] - Add support for Postgresql 9.2, Postgres Plus 9.2 and IBM DB2 10.1
+ * [HHH-8186] - Type in docs? Caching section nonstrict != nontrict
+ * [HHH-8212] - Add CLA ref to CONTRIBUTING.md
+
Changes in version 4.3.0.Beta1 (2012.07.12)
------------------------------------------------------------------------------------------------------------------------
diff --git a/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0ConnectionProvider.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java
similarity index 66%
rename from hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0ConnectionProvider.java
rename to hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java
index 61238d83f5..207461b1c5 100644
--- a/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0ConnectionProvider.java
+++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java
@@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.service.jdbc.connections.internal;
+package org.hibernate.c3p0.internal;
import java.sql.Connection;
import java.sql.SQLException;
@@ -31,6 +31,7 @@ import java.util.Properties;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.DataSources;
+
import org.jboss.logging.Logger;
import org.hibernate.HibernateException;
@@ -53,25 +54,28 @@ import org.hibernate.service.spi.Stoppable;
* @author various people
* @see ConnectionProvider
*/
-public class C3P0ConnectionProvider
+public class C3P0ConnectionProvider
implements ConnectionProvider, Configurable, Stoppable, ServiceRegistryAwareService {
- private static final C3P0MessageLogger LOG = Logger.getMessageLogger(C3P0MessageLogger.class, C3P0ConnectionProvider.class.getName());
+ private static final C3P0MessageLogger LOG = Logger.getMessageLogger(
+ C3P0MessageLogger.class,
+ C3P0ConnectionProvider.class.getName()
+ );
//swaldman 2006-08-28: define c3p0-style configuration parameters for properties with
// hibernate-specific overrides to detect and warn about conflicting
// declarations
- private final static String C3P0_STYLE_MIN_POOL_SIZE = "c3p0.minPoolSize";
- private final static String C3P0_STYLE_MAX_POOL_SIZE = "c3p0.maxPoolSize";
- private final static String C3P0_STYLE_MAX_IDLE_TIME = "c3p0.maxIdleTime";
- private final static String C3P0_STYLE_MAX_STATEMENTS = "c3p0.maxStatements";
- private final static String C3P0_STYLE_ACQUIRE_INCREMENT = "c3p0.acquireIncrement";
- private final static String C3P0_STYLE_IDLE_CONNECTION_TEST_PERIOD = "c3p0.idleConnectionTestPeriod";
+ private static final String C3P0_STYLE_MIN_POOL_SIZE = "c3p0.minPoolSize";
+ private static final String C3P0_STYLE_MAX_POOL_SIZE = "c3p0.maxPoolSize";
+ private static final String C3P0_STYLE_MAX_IDLE_TIME = "c3p0.maxIdleTime";
+ private static final String C3P0_STYLE_MAX_STATEMENTS = "c3p0.maxStatements";
+ private static final String C3P0_STYLE_ACQUIRE_INCREMENT = "c3p0.acquireIncrement";
+ private static final String C3P0_STYLE_IDLE_CONNECTION_TEST_PERIOD = "c3p0.idleConnectionTestPeriod";
//swaldman 2006-08-28: define c3p0-style configuration parameters for initialPoolSize, which
// hibernate sensibly lets default to minPoolSize, but we'll let users
// override it with the c3p0-style property if they want.
- private final static String C3P0_STYLE_INITIAL_POOL_SIZE = "c3p0.initialPoolSize";
+ private static final String C3P0_STYLE_INITIAL_POOL_SIZE = "c3p0.initialPoolSize";
private DataSource ds;
private Integer isolation;
@@ -105,7 +109,7 @@ public class C3P0ConnectionProvider
}
@Override
- @SuppressWarnings( {"unchecked"})
+ @SuppressWarnings({"unchecked"})
public T unwrap(Class unwrapType) {
if ( ConnectionProvider.class.equals( unwrapType ) ||
C3P0ConnectionProvider.class.isAssignableFrom( unwrapType ) ) {
@@ -120,46 +124,46 @@ public class C3P0ConnectionProvider
}
@Override
- @SuppressWarnings( {"unchecked"})
+ @SuppressWarnings({"unchecked"})
public void configure(Map props) {
- String jdbcDriverClass = (String) props.get( Environment.DRIVER );
- String jdbcUrl = (String) props.get( Environment.URL );
- Properties connectionProps = ConnectionProviderInitiator.getConnectionProperties( props );
+ final String jdbcDriverClass = (String) props.get( Environment.DRIVER );
+ final String jdbcUrl = (String) props.get( Environment.URL );
+ final Properties connectionProps = ConnectionProviderInitiator.getConnectionProperties( props );
- LOG.c3p0UsingDriver(jdbcDriverClass, jdbcUrl);
- LOG.connectionProperties(ConfigurationHelper.maskOut(connectionProps, "password"));
+ LOG.c3p0UsingDriver( jdbcDriverClass, jdbcUrl );
+ LOG.connectionProperties( ConfigurationHelper.maskOut( connectionProps, "password" ) );
autocommit = ConfigurationHelper.getBoolean( Environment.AUTOCOMMIT, props );
- LOG.autoCommitMode( autocommit );
+ LOG.autoCommitMode( autocommit );
- if (jdbcDriverClass == null) {
- LOG.jdbcDriverNotSpecified(Environment.DRIVER);
+ if ( jdbcDriverClass == null ) {
+ LOG.jdbcDriverNotSpecified( Environment.DRIVER );
}
else {
try {
serviceRegistry.getService( ClassLoaderService.class ).classForName( jdbcDriverClass );
}
- catch ( ClassLoadingException e ) {
- throw new ClassLoadingException( LOG.jdbcDriverNotFound(jdbcDriverClass), e );
+ catch (ClassLoadingException e) {
+ throw new ClassLoadingException( LOG.jdbcDriverNotFound( jdbcDriverClass ), e );
}
}
try {
//swaldman 2004-02-07: modify to allow null values to signify fall through to c3p0 PoolConfig defaults
- Integer minPoolSize = ConfigurationHelper.getInteger( Environment.C3P0_MIN_SIZE, props );
- Integer maxPoolSize = ConfigurationHelper.getInteger( Environment.C3P0_MAX_SIZE, props );
- Integer maxIdleTime = ConfigurationHelper.getInteger( Environment.C3P0_TIMEOUT, props );
- Integer maxStatements = ConfigurationHelper.getInteger( Environment.C3P0_MAX_STATEMENTS, props );
- Integer acquireIncrement = ConfigurationHelper.getInteger( Environment.C3P0_ACQUIRE_INCREMENT, props );
- Integer idleTestPeriod = ConfigurationHelper.getInteger( Environment.C3P0_IDLE_TEST_PERIOD, props );
+ final Integer minPoolSize = ConfigurationHelper.getInteger( Environment.C3P0_MIN_SIZE, props );
+ final Integer maxPoolSize = ConfigurationHelper.getInteger( Environment.C3P0_MAX_SIZE, props );
+ final Integer maxIdleTime = ConfigurationHelper.getInteger( Environment.C3P0_TIMEOUT, props );
+ final Integer maxStatements = ConfigurationHelper.getInteger( Environment.C3P0_MAX_STATEMENTS, props );
+ final Integer acquireIncrement = ConfigurationHelper.getInteger( Environment.C3P0_ACQUIRE_INCREMENT, props );
+ final Integer idleTestPeriod = ConfigurationHelper.getInteger( Environment.C3P0_IDLE_TEST_PERIOD, props );
- Properties c3props = new Properties();
+ final Properties c3props = new Properties();
// turn hibernate.c3p0.* into c3p0.*, so c3p0
// gets a chance to see all hibernate.c3p0.*
for ( Object o : props.keySet() ) {
- if ( ! String.class.isInstance( o ) ) {
+ if ( !String.class.isInstance( o ) ) {
continue;
}
final String key = (String) o;
@@ -182,63 +186,62 @@ public class C3P0ConnectionProvider
Environment.C3P0_ACQUIRE_INCREMENT, C3P0_STYLE_ACQUIRE_INCREMENT, props, c3props, acquireIncrement
);
setOverwriteProperty(
- Environment.C3P0_IDLE_TEST_PERIOD, C3P0_STYLE_IDLE_CONNECTION_TEST_PERIOD, props, c3props, idleTestPeriod
+ Environment.C3P0_IDLE_TEST_PERIOD,
+ C3P0_STYLE_IDLE_CONNECTION_TEST_PERIOD,
+ props,
+ c3props,
+ idleTestPeriod
);
// revert to traditional hibernate behavior of setting initialPoolSize to minPoolSize
// unless otherwise specified with a c3p0.*-style parameter.
- Integer initialPoolSize = ConfigurationHelper.getInteger( C3P0_STYLE_INITIAL_POOL_SIZE, props );
+ final Integer initialPoolSize = ConfigurationHelper.getInteger( C3P0_STYLE_INITIAL_POOL_SIZE, props );
if ( initialPoolSize == null && minPoolSize != null ) {
c3props.put( C3P0_STYLE_INITIAL_POOL_SIZE, String.valueOf( minPoolSize ).trim() );
}
- /*DataSource unpooled = DataSources.unpooledDataSource(
- jdbcUrl, props.getProperty(Environment.USER), props.getProperty(Environment.PASS)
- );*/
- DataSource unpooled = DataSources.unpooledDataSource( jdbcUrl, connectionProps );
+ final DataSource unpooled = DataSources.unpooledDataSource( jdbcUrl, connectionProps );
- Map allProps = new HashMap();
+ final Map allProps = new HashMap();
allProps.putAll( props );
allProps.putAll( c3props );
ds = DataSources.pooledDataSource( unpooled, allProps );
}
- catch ( Exception e ) {
- LOG.error(LOG.unableToInstantiateC3p0ConnectionPool(), e);
- throw new HibernateException(LOG.unableToInstantiateC3p0ConnectionPool(), e);
+ catch (Exception e) {
+ LOG.error( LOG.unableToInstantiateC3p0ConnectionPool(), e );
+ throw new HibernateException( LOG.unableToInstantiateC3p0ConnectionPool(), e );
}
- String i = (String) props.get( Environment.ISOLATION );
- if (i == null) isolation = null;
+ final String i = (String) props.get( Environment.ISOLATION );
+ if ( i == null ) {
+ isolation = null;
+ }
else {
isolation = Integer.valueOf( i );
- LOG.jdbcIsolationLevel(Environment.isolationLevelToString(isolation));
+ LOG.jdbcIsolationLevel( Environment.isolationLevelToString( isolation ) );
}
}
- public void close() {
- try {
- DataSources.destroy( ds );
- }
- catch ( SQLException sqle ) {
- LOG.unableToDestroyC3p0ConnectionPool(sqle);
- }
- }
-
@Override
public boolean supportsAggressiveRelease() {
return false;
}
- private void setOverwriteProperty(String hibernateStyleKey, String c3p0StyleKey, Map hibp, Properties c3p, Integer value) {
+ private void setOverwriteProperty(
+ String hibernateStyleKey,
+ String c3p0StyleKey,
+ Map hibp,
+ Properties c3p,
+ Integer value) {
if ( value != null ) {
- String peeledC3p0Key = c3p0StyleKey.substring(5);
+ final String peeledC3p0Key = c3p0StyleKey.substring( 5 );
c3p.put( peeledC3p0Key, String.valueOf( value ).trim() );
- if ( hibp.containsKey( c3p0StyleKey ) ) {
+ if ( hibp.containsKey( c3p0StyleKey ) ) {
warnPropertyConflict( hibernateStyleKey, c3p0StyleKey );
}
- String longC3p0StyleKey = "hibernate." + c3p0StyleKey;
+ final String longC3p0StyleKey = "hibernate." + c3p0StyleKey;
if ( hibp.containsKey( longC3p0StyleKey ) ) {
warnPropertyConflict( hibernateStyleKey, longC3p0StyleKey );
}
@@ -246,12 +249,27 @@ public class C3P0ConnectionProvider
}
private void warnPropertyConflict(String hibernateStyle, String c3p0Style) {
- LOG.bothHibernateAndC3p0StylesSet(hibernateStyle, c3p0Style, hibernateStyle, c3p0Style);
+ LOG.bothHibernateAndC3p0StylesSet( hibernateStyle, c3p0Style );
}
@Override
public void stop() {
- close();
+ try {
+ DataSources.destroy( ds );
+ }
+ catch (SQLException sqle) {
+ LOG.unableToDestroyC3p0ConnectionPool( sqle );
+ }
+ }
+
+ /**
+ * Close the provider.
+ *
+ * @deprecated Use {@link #stop} instead
+ */
+ @Deprecated
+ public void close() {
+ stop();
}
@Override
diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java
new file mode 100644
index 0000000000..7ff9c6eab0
--- /dev/null
+++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java
@@ -0,0 +1,94 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2007-2011, Red Hat Inc. 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 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.c3p0.internal;
+
+import java.sql.SQLException;
+
+import org.jboss.logging.Cause;
+import org.jboss.logging.LogMessage;
+import org.jboss.logging.Message;
+import org.jboss.logging.MessageLogger;
+
+import org.hibernate.internal.CoreMessageLogger;
+
+import static org.jboss.logging.Logger.Level.INFO;
+import static org.jboss.logging.Logger.Level.WARN;
+
+/**
+ * The jboss-logging {@link MessageLogger} for the hibernate-c3p0 module. It reserves message ids ranging from
+ * 10001 to 15000 inclusively.
+ *
+ * New messages must be added after the last message defined to ensure message codes are unique.
+ */
+@MessageLogger(projectCode = "HHH")
+public interface C3P0MessageLogger extends CoreMessageLogger {
+
+ /**
+ * Log a message (WARN) about conflicting {@code hibernate.c3p0.XYZ} and {@code c3p0.XYZ} settings
+ *
+ * @param hibernateStyle The {@code hibernate.c3p0} prefixed setting
+ * @param c3p0Style The {@code c3p0.} prefixed setting
+ */
+ @LogMessage(level = WARN)
+ @Message(value = "Both hibernate-style property '%1$s' and c3p0-style property '%2$s' have been set in Hibernate "
+ + "properties. Hibernate-style property '%1$s' will be used and c3p0-style property '%2$s' will be ignored!", id = 10001)
+ void bothHibernateAndC3p0StylesSet(String hibernateStyle,String c3p0Style);
+
+ /**
+ * Log a message (INFO) about which Driver class is being used.
+ *
+ * @param jdbcDriverClass The JDBC Driver class
+ * @param jdbcUrl The JDBC URL
+ */
+ @LogMessage(level = INFO)
+ @Message(value = "C3P0 using driver: %s at URL: %s", id = 10002)
+ void c3p0UsingDriver(String jdbcDriverClass, String jdbcUrl);
+
+ /**
+ * Build a message about not being able to find the JDBC driver class
+ *
+ * @param jdbcDriverClass The JDBC driver class we could not find
+ *
+ * @return The message
+ */
+ @Message(value = "JDBC Driver class not found: %s", id = 10003)
+ String jdbcDriverNotFound(String jdbcDriverClass);
+
+ /**
+ * Log a message (WARN) about not being able to stop the underlying c3p0 pool.
+ *
+ * @param e The exception when we tried to stop pool
+ */
+ @LogMessage(level = WARN)
+ @Message(value = "Could not destroy C3P0 connection pool", id = 10004)
+ void unableToDestroyC3p0ConnectionPool(@Cause SQLException e);
+
+ /**
+ * Build a message about not being able to start the underlying c3p0 pool.
+ *
+ * @return The message
+ */
+ @Message(value = "Could not instantiate C3P0 connection pool", id = 10005)
+ String unableToInstantiateC3p0ConnectionPool();
+}
diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java
new file mode 100644
index 0000000000..b1b98bd9c5
--- /dev/null
+++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java
@@ -0,0 +1,59 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2012, Red Hat Inc. 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 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.c3p0.internal;
+
+import java.util.Collections;
+import java.util.List;
+
+import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl;
+import org.hibernate.boot.registry.selector.StrategyRegistration;
+import org.hibernate.boot.registry.selector.StrategyRegistrationProvider;
+import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
+
+/**
+ * Provides the {@link C3P0ConnectionProvider} to the
+ * {@link org.hibernate.boot.registry.selector.spi.StrategySelector} service.
+ *
+ * @author Brett Meyer
+ */
+public class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider {
+ private static final List REGISTRATIONS = Collections.singletonList(
+ (StrategyRegistration) new SimpleStrategyRegistrationImpl(
+ ConnectionProvider.class,
+ C3P0ConnectionProvider.class,
+ "c3p0",
+ C3P0ConnectionProvider.class.getSimpleName(),
+ // legacy
+ "org.hibernate.connection.C3P0ConnectionProvider",
+ // legacy
+ "org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider"
+ )
+ );
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public Iterable getStrategyRegistrations() {
+ return REGISTRATIONS;
+ }
+}
diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/package-info.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/package-info.java
new file mode 100644
index 0000000000..52b4638e53
--- /dev/null
+++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Implementation of ConnectionProvider using the c3p0 Connection pool.
+ */
+package org.hibernate.c3p0.internal;
diff --git a/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0MessageLogger.java b/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0MessageLogger.java
deleted file mode 100644
index 434af89276..0000000000
--- a/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0MessageLogger.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2007-2011, Red Hat Inc. 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 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.service.jdbc.connections.internal;
-
-import java.sql.SQLException;
-
-import org.jboss.logging.Cause;
-import org.jboss.logging.LogMessage;
-import org.jboss.logging.Message;
-import org.jboss.logging.MessageLogger;
-
-import org.hibernate.internal.CoreMessageLogger;
-
-import static org.jboss.logging.Logger.Level.INFO;
-import static org.jboss.logging.Logger.Level.WARN;
-
-/**
- * The jboss-logging {@link MessageLogger} for the hibernate-c3p0 module. It reserves message ids ranging from
- * 10001 to 15000 inclusively.
- *
- * New messages must be added after the last message defined to ensure message codes are unique.
- */
-@MessageLogger( projectCode = "HHH" )
-public interface C3P0MessageLogger extends CoreMessageLogger {
-
- @LogMessage( level = WARN )
- @Message( value = "Both hibernate-style property '%s' and c3p0-style property '%s' have been set in hibernate.properties. "
- + "Hibernate-style property '%s' will be used and c3p0-style property '%s' will be ignored!", id = 10001 )
- void bothHibernateAndC3p0StylesSet( String hibernateStyle,
- String c3p0Style,
- String hibernateStyle2,
- String c3p0Style2 );
-
- @LogMessage( level = INFO )
- @Message( value = "C3P0 using driver: %s at URL: %s", id = 10002 )
- void c3p0UsingDriver( String jdbcDriverClass,
- String jdbcUrl );
-
- @Message( value = "JDBC Driver class not found: %s", id = 10003 )
- String jdbcDriverNotFound( String jdbcDriverClass );
-
- @LogMessage( level = WARN )
- @Message( value = "Could not destroy C3P0 connection pool", id = 10004 )
- void unableToDestroyC3p0ConnectionPool( @Cause SQLException e );
-
- @Message( value = "Could not instantiate C3P0 connection pool", id = 10005 )
- String unableToInstantiateC3p0ConnectionPool();
-}
diff --git a/hibernate-c3p0/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider b/hibernate-c3p0/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider
new file mode 100644
index 0000000000..cde2be1446
--- /dev/null
+++ b/hibernate-c3p0/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider
@@ -0,0 +1 @@
+org.hibernate.c3p0.internal.StrategyRegistrationProviderImpl
diff --git a/hibernate-c3p0/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/hibernate-c3p0/src/main/resources/OSGI-INF/blueprint/blueprint.xml
new file mode 100644
index 0000000000..3ade79977f
--- /dev/null
+++ b/hibernate-c3p0/src/main/resources/OSGI-INF/blueprint/blueprint.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
diff --git a/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/C3P0ConnectionProviderTest.java b/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/C3P0ConnectionProviderTest.java
index 2175f15193..03e3c4fb33 100644
--- a/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/C3P0ConnectionProviderTest.java
+++ b/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/C3P0ConnectionProviderTest.java
@@ -30,8 +30,8 @@ import javax.management.ObjectName;
import org.junit.Test;
+import org.hibernate.c3p0.internal.C3P0ConnectionProvider;
import org.hibernate.engine.jdbc.spi.JdbcServices;
-import org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
diff --git a/hibernate-core/src/main/java/org/hibernate/QueryException.java b/hibernate-core/src/main/java/org/hibernate/QueryException.java
index 6a0a27d752..dd59a7ed0c 100644
--- a/hibernate-core/src/main/java/org/hibernate/QueryException.java
+++ b/hibernate-core/src/main/java/org/hibernate/QueryException.java
@@ -23,15 +23,11 @@
*/
package org.hibernate;
-import org.jboss.logging.Logger;
-
/**
* A problem occurred translating a Hibernate query to SQL due to invalid query syntax, etc.
*/
public class QueryException extends HibernateException {
- private static final Logger log = Logger.getLogger( QueryException.class );
-
- private String queryString;
+ private final String queryString;
/**
* Constructs a QueryException using the specified exception message.
@@ -39,7 +35,7 @@ public class QueryException extends HibernateException {
* @param message A message explaining the exception condition
*/
public QueryException(String message) {
- super( message );
+ this( message, null, null );
}
/**
@@ -48,8 +44,8 @@ public class QueryException extends HibernateException {
* @param message A message explaining the exception condition
* @param cause The underlying cause
*/
- public QueryException(String message, Throwable cause) {
- super( message, cause );
+ public QueryException(String message, Exception cause) {
+ this( message, null, cause );
}
/**
@@ -59,7 +55,18 @@ public class QueryException extends HibernateException {
* @param queryString The query being evaluated when the exception occurred
*/
public QueryException(String message, String queryString) {
- super( message );
+ this( message, queryString, null );
+ }
+
+ /**
+ * Constructs a QueryException using the specified exception message and query-string.
+ *
+ * @param message A message explaining the exception condition
+ * @param queryString The query being evaluated when the exception occurred
+ * @param cause The underlying cause
+ */
+ public QueryException(String message, String queryString, Exception cause) {
+ super( message, cause );
this.queryString = queryString;
}
@@ -69,7 +76,7 @@ public class QueryException extends HibernateException {
* @param cause The underlying cause
*/
public QueryException(Exception cause) {
- super( cause );
+ this( "A query exception occurred", null, cause );
}
/**
@@ -81,30 +88,52 @@ public class QueryException extends HibernateException {
return queryString;
}
- /**
- * Set the query string. Even an option since often the part of the code generating the exception does not
- * have access to the query overall.
- *
- * @param queryString The query string.
- */
- public void setQueryString(String queryString) {
- if ( this.queryString != null ) {
- log.debugf(
- "queryString overriding non-null previous value [%s] : %s",
- this.queryString,
- queryString
- );
- }
- this.queryString = queryString;
- }
-
@Override
public String getMessage() {
- String msg = super.getMessage();
- if ( queryString!=null ) {
+ String msg = getOriginalMessage();
+ if ( queryString != null ) {
msg += " [" + queryString + ']';
}
return msg;
}
+ protected final String getOriginalMessage() {
+ return super.getMessage();
+ }
+
+ /**
+ * Wraps this exception with another, of same kind, with the specified queryString. If this exception already
+ * has a queryString defined, the same exception ({@code this}) is returned. Otherwise the protected
+ * {@link #generateQueryException(String)} is called, to allow subclasses to properly create the correct
+ * subclass for return.
+ *
+ * @param queryString The query string that led to the QueryException
+ *
+ * @return {@code this}, if {@code this} has {@code null} for {@link #getQueryString()}; otherwise a new
+ * QueryException (or subclass) is returned.
+ */
+ public final QueryException wrapWithQueryString(String queryString) {
+ if ( this.getQueryString() != null ) {
+ return this;
+ }
+
+ return generateQueryException( queryString );
+ }
+
+ /**
+ * Called from {@link #wrapWithQueryString(String)} when we really need to generate a new QueryException
+ * (or subclass).
+ *
+ * NOTE : implementors should take care to use {@link #getOriginalMessage()} for the message, not
+ * {@link #getMessage()}
+ *
+ * @param queryString The query string
+ *
+ * @return The generated QueryException (or subclass)
+ *
+ * @see #getOriginalMessage()
+ */
+ protected QueryException generateQueryException(String queryString) {
+ return new QueryException( getOriginalMessage(), queryString, this );
+ }
}
diff --git a/hibernate-core/src/main/java/org/hibernate/QueryParameterException.java b/hibernate-core/src/main/java/org/hibernate/QueryParameterException.java
index 92998c0029..3f07de8ebc 100644
--- a/hibernate-core/src/main/java/org/hibernate/QueryParameterException.java
+++ b/hibernate-core/src/main/java/org/hibernate/QueryParameterException.java
@@ -37,4 +37,20 @@ public class QueryParameterException extends QueryException {
public QueryParameterException(String message) {
super( message );
}
+
+ /**
+ * Constructs a QueryParameterException
+ *
+ * @param message The message explaining the exception condition
+ * @param queryString The query that led to the exception
+ * @param cause The underlying cause
+ */
+ public QueryParameterException(String message, String queryString, Exception cause) {
+ super( message, queryString, cause );
+ }
+
+ @Override
+ protected QueryException generateQueryException(String queryString) {
+ return new QueryParameterException( super.getOriginalMessage(), queryString, this );
+ }
}
diff --git a/hibernate-core/src/main/java/org/hibernate/action/internal/BulkOperationCleanupAction.java b/hibernate-core/src/main/java/org/hibernate/action/internal/BulkOperationCleanupAction.java
index 7423691c76..ad7dd07a66 100644
--- a/hibernate-core/src/main/java/org/hibernate/action/internal/BulkOperationCleanupAction.java
+++ b/hibernate-core/src/main/java/org/hibernate/action/internal/BulkOperationCleanupAction.java
@@ -217,7 +217,7 @@ public class BulkOperationCleanupAction implements Executable, Serializable {
// nothing to do
}
- private static class EntityCleanup {
+ private static class EntityCleanup implements Serializable {
private final EntityRegionAccessStrategy cacheAccess;
private final SoftLock cacheLock;
@@ -232,7 +232,7 @@ public class BulkOperationCleanupAction implements Executable, Serializable {
}
}
- private static class CollectionCleanup {
+ private static class CollectionCleanup implements Serializable {
private final CollectionRegionAccessStrategy cacheAccess;
private final SoftLock cacheLock;
@@ -247,7 +247,7 @@ public class BulkOperationCleanupAction implements Executable, Serializable {
}
}
- private class NaturalIdCleanup {
+ private static class NaturalIdCleanup implements Serializable {
private final NaturalIdRegionAccessStrategy naturalIdCacheAccessStrategy;
private final SoftLock cacheLock;
diff --git a/hibernate-core/src/main/java/org/hibernate/action/internal/EntityInsertAction.java b/hibernate-core/src/main/java/org/hibernate/action/internal/EntityInsertAction.java
index fba5c3e6ef..9c17828b15 100644
--- a/hibernate-core/src/main/java/org/hibernate/action/internal/EntityInsertAction.java
+++ b/hibernate-core/src/main/java/org/hibernate/action/internal/EntityInsertAction.java
@@ -48,7 +48,6 @@ import org.hibernate.persister.entity.EntityPersister;
* @see EntityIdentityInsertAction
*/
public final class EntityInsertAction extends AbstractEntityInsertAction {
-
private Object version;
private Object cacheEntry;
@@ -130,7 +129,7 @@ public final class EntityInsertAction extends AbstractEntityInsertAction {
version,
session
);
- cacheEntry = persister.getCacheEntryStructure().structure(ce);
+ cacheEntry = persister.getCacheEntryStructure().structure( ce );
final CacheKey ck = session.generateCacheKey( id, persister.getIdentifierType(), persister.getRootEntityName() );
final boolean put = persister.getCacheAccessStrategy().insert( ck, cacheEntry, version );
diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/BootstrapServiceRegistryBuilder.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/BootstrapServiceRegistryBuilder.java
index 775ea0f4cf..ce59202409 100644
--- a/hibernate-core/src/main/java/org/hibernate/boot/registry/BootstrapServiceRegistryBuilder.java
+++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/BootstrapServiceRegistryBuilder.java
@@ -32,8 +32,8 @@ import java.util.Set;
import org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.registry.internal.BootstrapServiceRegistryImpl;
-import org.hibernate.boot.registry.selector.Availability;
-import org.hibernate.boot.registry.selector.AvailabilityAnnouncer;
+import org.hibernate.boot.registry.selector.StrategyRegistration;
+import org.hibernate.boot.registry.selector.StrategyRegistrationProvider;
import org.hibernate.boot.registry.selector.internal.StrategySelectorBuilder;
import org.hibernate.integrator.internal.IntegratorServiceImpl;
import org.hibernate.integrator.spi.Integrator;
@@ -169,23 +169,23 @@ public class BootstrapServiceRegistryBuilder {
*/
@SuppressWarnings( {"UnusedDeclaration"})
public BootstrapServiceRegistryBuilder withStrategySelector(Class strategy, String name, Class extends T> implementation) {
- this.strategySelectorBuilder.addExplicitAvailability( strategy, implementation, name );
+ this.strategySelectorBuilder.addExplicitStrategyRegistration( strategy, implementation, name );
return this;
}
/**
* Applies one or more strategy selectors announced as available by the passed announcer.
*
- * @param availabilityAnnouncer An announcer for one or more available selectors
+ * @param strategyRegistrationProvider An provider for one or more available selectors
*
* @return {@code this}, for method chaining
*
* @see org.hibernate.boot.registry.selector.spi.StrategySelector#registerStrategyImplementor(Class, String, Class)
*/
@SuppressWarnings( {"UnusedDeclaration"})
- public BootstrapServiceRegistryBuilder withStrategySelectors(AvailabilityAnnouncer availabilityAnnouncer) {
- for ( Availability availability : availabilityAnnouncer.getAvailabilities() ) {
- this.strategySelectorBuilder.addExplicitAvailability( availability );
+ public BootstrapServiceRegistryBuilder withStrategySelectors(StrategyRegistrationProvider strategyRegistrationProvider) {
+ for ( StrategyRegistration strategyRegistration : strategyRegistrationProvider.getStrategyRegistrations() ) {
+ this.strategySelectorBuilder.addExplicitStrategyRegistration( strategyRegistration );
}
return this;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/package-info.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/package-info.java
index 88b77afdc4..962c27b4e9 100644
--- a/hibernate-core/src/main/java/org/hibernate/boot/registry/package-info.java
+++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/package-info.java
@@ -2,6 +2,18 @@
* Defines service registry contracts application are likely to want to utilize for
* configuring Hibernate behavior.
*
- * {@link BootstrapServiceRegistry} is the
+ * Service registries are designed to be hierarchical. This works in 2 fashions. First registries can "hide" or
+ * "override" services from parent registries. It also allows granular building of registries as services
+ * become available.
+ *
+ * {@link BootstrapServiceRegistry} is the base service registry, intended to be built via
+ * {@link BootstrapServiceRegistryBuilder} if you need customization. For non-customized
+ * {@link BootstrapServiceRegistry} usage, the {@link BootstrapServiceRegistryBuilder} and
+ * {@link BootstrapServiceRegistry} can be bypassed altogether.
+ *
+ * Usually the next level in a standard registry set up is the {@link StandardServiceRegistry}, intended to be built
+ * by the {@link StandardServiceRegistryBuilder} if you need customization. The builder optionally takes the
+ * {@link BootstrapServiceRegistry} to use as a base; if none is provided a default one is generated assuming sensible
+ * defaults in Java SE and EE environments, particularly in respect to Class loading.
*/
package org.hibernate.boot.registry;
diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleAvailabilityImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleStrategyRegistrationImpl.java
similarity index 88%
rename from hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleAvailabilityImpl.java
rename to hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleStrategyRegistrationImpl.java
index ff536956ab..725b526ef7 100644
--- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleAvailabilityImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleStrategyRegistrationImpl.java
@@ -26,25 +26,25 @@ package org.hibernate.boot.registry.selector;
import java.util.Arrays;
/**
- * A simple implementation of Availability.
+ * A simple implementation of StrategyRegistration.
*
* @param The strategy type.
*
* @author Steve Ebersole
*/
-public class SimpleAvailabilityImpl implements Availability {
+public class SimpleStrategyRegistrationImpl implements StrategyRegistration {
private final Class strategyRole;
private final Class extends T> strategyImplementation;
private final Iterable selectorNames;
/**
- * Constructs a SimpleAvailabilityImpl.
+ * Constructs a SimpleStrategyRegistrationImpl.
*
* @param strategyRole The strategy contract
* @param strategyImplementation The strategy implementation class
* @param selectorNames The selection/registration names for this implementation
*/
- public SimpleAvailabilityImpl(
+ public SimpleStrategyRegistrationImpl(
Class strategyRole,
Class extends T> strategyImplementation,
Iterable selectorNames) {
@@ -54,13 +54,13 @@ public class SimpleAvailabilityImpl implements Availability {
}
/**
- * Constructs a SimpleAvailabilityImpl.
+ * Constructs a SimpleStrategyRegistrationImpl.
*
* @param strategyRole The strategy contract
* @param strategyImplementation The strategy implementation class
* @param selectorNames The selection/registration names for this implementation
*/
- public SimpleAvailabilityImpl(
+ public SimpleStrategyRegistrationImpl(
Class strategyRole,
Class extends T> strategyImplementation,
String... selectorNames) {
diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/Availability.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistration.java
similarity index 89%
rename from hibernate-core/src/main/java/org/hibernate/boot/registry/selector/Availability.java
rename to hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistration.java
index 20de189f6f..5b1fd1b78a 100644
--- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/Availability.java
+++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistration.java
@@ -24,16 +24,14 @@
package org.hibernate.boot.registry.selector;
/**
- * Describes the availability of a named strategy implementation. A strategy + selector name should resolve
+ * Describes the registration of a named strategy implementation. A strategy + selector name should resolve
* to a single implementation.
*
- * todo : better name?
- *
- * @param The type of the strategy described by this implementation availability.
+ * @param The type of the strategy described by this implementation registration.
*
* @author Steve Ebersole
*/
-public interface Availability {
+public interface StrategyRegistration {
/**
* The strategy role. Best practice says this should be an interface.
*
@@ -42,7 +40,7 @@ public interface Availability {
public Class getStrategyRole();
/**
- * Any registered names for this strategy availability.
+ * Any registered names for this strategy registration.
*
* @return The registered selection names.
*/
diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/AvailabilityAnnouncer.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistrationProvider.java
similarity index 82%
rename from hibernate-core/src/main/java/org/hibernate/boot/registry/selector/AvailabilityAnnouncer.java
rename to hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistrationProvider.java
index bcc365a887..df28691ae2 100644
--- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/AvailabilityAnnouncer.java
+++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistrationProvider.java
@@ -24,18 +24,16 @@
package org.hibernate.boot.registry.selector;
/**
- * Responsible for announcing the availability of strategy selector(s). Can be registered directly with the
+ * Responsible for providing the registrations of strategy selector(s). Can be registered directly with the
* {@link org.hibernate.boot.registry.BootstrapServiceRegistry} or located via discovery.
*
- * todo : better name?
- *
* @author Steve Ebersole
*/
-public interface AvailabilityAnnouncer {
+public interface StrategyRegistrationProvider {
/**
- * Get all availabilities announced by this announcer.
+ * Get all StrategyRegistrations announced by this provider.
*
- * @return All announced availabilities
+ * @return All StrategyRegistrations
*/
- public Iterable getAvailabilities();
+ public Iterable getStrategyRegistrations();
}
diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java
index 0850823954..9b14797e2c 100644
--- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java
+++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java
@@ -29,9 +29,9 @@ import java.util.List;
import org.jboss.logging.Logger;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
-import org.hibernate.boot.registry.selector.Availability;
-import org.hibernate.boot.registry.selector.AvailabilityAnnouncer;
-import org.hibernate.boot.registry.selector.SimpleAvailabilityImpl;
+import org.hibernate.boot.registry.selector.StrategyRegistration;
+import org.hibernate.boot.registry.selector.StrategyRegistrationProvider;
+import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl;
import org.hibernate.boot.registry.selector.spi.StrategySelectionException;
import org.hibernate.boot.registry.selector.spi.StrategySelector;
import org.hibernate.dialect.CUBRIDDialect;
@@ -106,10 +106,10 @@ import org.hibernate.hql.spi.TemporaryTableBulkIdStrategy;
public class StrategySelectorBuilder {
private static final Logger log = Logger.getLogger( StrategySelectorBuilder.class );
- private final List explicitAvailabilities = new ArrayList();
+ private final List explicitStrategyRegistrations = new ArrayList();
/**
- * Adds an explicit (as opposed to discovered) strategy availability.
+ * Adds an explicit (as opposed to discovered) strategy registration.
*
* @param strategy The strategy
* @param implementation The strategy implementation
@@ -118,31 +118,31 @@ public class StrategySelectorBuilder {
* compatible.
*/
@SuppressWarnings("unchecked")
- public void addExplicitAvailability(Class strategy, Class extends T> implementation, String name) {
- addExplicitAvailability( new SimpleAvailabilityImpl( strategy, implementation, name ) );
+ public void addExplicitStrategyRegistration(Class strategy, Class extends T> implementation, String name) {
+ addExplicitStrategyRegistration( new SimpleStrategyRegistrationImpl( strategy, implementation, name ) );
}
/**
- * Adds an explicit (as opposed to discovered) strategy availability.
+ * Adds an explicit (as opposed to discovered) strategy registration.
*
- * @param availability The strategy implementation availability.
+ * @param strategyRegistration The strategy implementation registration.
* @param The type of the strategy. Used to make sure that the strategy and implementation are type
* compatible.
*/
- public void addExplicitAvailability(Availability availability) {
- if ( !availability.getStrategyRole().isInterface() ) {
+ public void addExplicitStrategyRegistration(StrategyRegistration strategyRegistration) {
+ if ( !strategyRegistration.getStrategyRole().isInterface() ) {
// not good form...
- log.debug( "Registering non-interface strategy : " + availability.getStrategyRole().getName() );
+ log.debug( "Registering non-interface strategy : " + strategyRegistration.getStrategyRole().getName() );
}
- if ( ! availability.getStrategyRole().isAssignableFrom( availability.getStrategyImplementation() ) ) {
+ if ( ! strategyRegistration.getStrategyRole().isAssignableFrom( strategyRegistration.getStrategyImplementation() ) ) {
throw new StrategySelectionException(
- "Implementation class [" + availability.getStrategyImplementation().getName()
+ "Implementation class [" + strategyRegistration.getStrategyImplementation().getName()
+ "] does not implement strategy interface ["
- + availability.getStrategyRole().getName() + "]"
+ + strategyRegistration.getStrategyRole().getName() + "]"
);
}
- explicitAvailabilities.add( availability );
+ explicitStrategyRegistrations.add( strategyRegistration );
}
/**
@@ -163,27 +163,27 @@ public class StrategySelectorBuilder {
addMultiTableBulkIdStrategies( strategySelector );
// apply auto-discovered registrations
- for ( AvailabilityAnnouncer announcer : classLoaderService.loadJavaServices( AvailabilityAnnouncer.class ) ) {
- for ( Availability discoveredAvailability : announcer.getAvailabilities() ) {
- applyFromAvailability( strategySelector, discoveredAvailability );
+ for ( StrategyRegistrationProvider provider : classLoaderService.loadJavaServices( StrategyRegistrationProvider.class ) ) {
+ for ( StrategyRegistration discoveredStrategyRegistration : provider.getStrategyRegistrations() ) {
+ applyFromStrategyRegistration( strategySelector, discoveredStrategyRegistration );
}
}
// apply customizations
- for ( Availability explicitAvailability : explicitAvailabilities ) {
- applyFromAvailability( strategySelector, explicitAvailability );
+ for ( StrategyRegistration explicitStrategyRegistration : explicitStrategyRegistrations ) {
+ applyFromStrategyRegistration( strategySelector, explicitStrategyRegistration );
}
return strategySelector;
}
@SuppressWarnings("unchecked")
- private void applyFromAvailability(StrategySelectorImpl strategySelector, Availability availability) {
- for ( String name : availability.getSelectorNames() ) {
+ private void applyFromStrategyRegistration(StrategySelectorImpl strategySelector, StrategyRegistration strategyRegistration) {
+ for ( String name : strategyRegistration.getSelectorNames() ) {
strategySelector.registerStrategyImplementor(
- availability.getStrategyRole(),
+ strategyRegistration.getStrategyRole(),
name,
- availability.getStrategyImplementation()
+ strategyRegistration.getStrategyImplementation()
);
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/bytecode/internal/javassist/TransformingClassLoader.java b/hibernate-core/src/main/java/org/hibernate/bytecode/internal/javassist/TransformingClassLoader.java
index 96661cb461..53ad74fdd7 100644
--- a/hibernate-core/src/main/java/org/hibernate/bytecode/internal/javassist/TransformingClassLoader.java
+++ b/hibernate-core/src/main/java/org/hibernate/bytecode/internal/javassist/TransformingClassLoader.java
@@ -63,7 +63,7 @@ public class TransformingClassLoader extends ClassLoader {
try {
final CtClass cc = classPool.get( name );
// todo : modify the class definition if not already transformed...
- byte[] b = cc.toBytecode();
+ final byte[] b = cc.toBytecode();
return defineClass( name, b, 0, b.length );
}
catch (NotFoundException e) {
diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/CacheDataDescriptionImpl.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/CacheDataDescriptionImpl.java
index aacaf92cf4..cf8c7e1857 100644
--- a/hibernate-core/src/main/java/org/hibernate/cache/internal/CacheDataDescriptionImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/CacheDataDescriptionImpl.java
@@ -30,10 +30,11 @@ import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.metamodel.spi.binding.EntityBinding;
import org.hibernate.metamodel.spi.binding.PluralAttributeBinding;
-import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.type.VersionType;
/**
+ * Standard CacheDataDescription implementation.
+ *
* @author Steve Ebersole
*/
public class CacheDataDescriptionImpl implements CacheDataDescription {
@@ -41,48 +42,87 @@ public class CacheDataDescriptionImpl implements CacheDataDescription {
private final boolean versioned;
private final Comparator versionComparator;
+ /**
+ * Constructs a CacheDataDescriptionImpl instance. Generally speaking, code should use one of the
+ * overloaded {@link #decode} methods rather than direct instantiation.
+ *
+ * @param mutable Is the described data mutable?
+ * @param versioned Is the described data versioned?
+ * @param versionComparator The described data's version value comparator (if versioned).
+ */
public CacheDataDescriptionImpl(boolean mutable, boolean versioned, Comparator versionComparator) {
this.mutable = mutable;
this.versioned = versioned;
this.versionComparator = versionComparator;
}
+ @Override
public boolean isMutable() {
return mutable;
}
+ @Override
public boolean isVersioned() {
return versioned;
}
+ @Override
public Comparator getVersionComparator() {
return versionComparator;
}
+ /**
+ * Builds a CacheDataDescriptionImpl from the mapping model of an entity class.
+ *
+ * @param model The mapping model.
+ *
+ * @return The constructed CacheDataDescriptionImpl
+ */
public static CacheDataDescriptionImpl decode(PersistentClass model) {
return new CacheDataDescriptionImpl(
model.isMutable(),
model.isVersioned(),
- model.isVersioned() ? ( ( VersionType ) model.getVersion().getType() ).getComparator() : null
+ model.isVersioned()
+ ? ( (VersionType) model.getVersion().getType() ).getComparator()
+ : null
);
}
+ /**
+ * Builds a CacheDataDescriptionImpl from the mapping model of an entity class (using the new metamodel code).
+ *
+ * @param model The mapping model.
+ *
+ * @return The constructed CacheDataDescriptionImpl
+ */
public static CacheDataDescriptionImpl decode(EntityBinding model) {
- return new CacheDataDescriptionImpl(
- model.isMutable(),
- model.isVersioned(),
- getVersionComparator( model )
- );
+ return new CacheDataDescriptionImpl( model.isMutable(), model.isVersioned(), getVersionComparator( model ) );
}
+ /**
+ * Builds a CacheDataDescriptionImpl from the mapping model of a collection
+ *
+ * @param model The mapping model.
+ *
+ * @return The constructed CacheDataDescriptionImpl
+ */
public static CacheDataDescriptionImpl decode(Collection model) {
return new CacheDataDescriptionImpl(
model.isMutable(),
model.getOwner().isVersioned(),
- model.getOwner().isVersioned() ? ( ( VersionType ) model.getOwner().getVersion().getType() ).getComparator() : null
+ model.getOwner().isVersioned()
+ ? ( (VersionType) model.getOwner().getVersion().getType() ).getComparator()
+ : null
);
}
+ /**
+ * Builds a CacheDataDescriptionImpl from the mapping model of a collection (using the new metamodel code).
+ *
+ * @param model The mapping model.
+ *
+ * @return The constructed CacheDataDescriptionImpl
+ */
public static CacheDataDescriptionImpl decode(PluralAttributeBinding model) {
return new CacheDataDescriptionImpl(
model.isMutable(),
@@ -91,18 +131,9 @@ public class CacheDataDescriptionImpl implements CacheDataDescription {
);
}
- public static CacheDataDescriptionImpl decode(EntityPersister persister) {
- return new CacheDataDescriptionImpl(
- !persister.getEntityMetamodel().hasImmutableNaturalId(),
- false,
- null
- );
- }
-
private static Comparator getVersionComparator(EntityBinding model ) {
- Comparator versionComparator = null;
if ( model.isVersioned() ) {
- versionComparator = (
+ return (
( VersionType ) model.getHierarchyDetails()
.getEntityVersion()
.getVersioningAttributeBinding()
@@ -110,6 +141,7 @@ public class CacheDataDescriptionImpl implements CacheDataDescription {
.getResolvedTypeMapping()
).getComparator();
}
- return versionComparator;
+
+ return null;
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/NoCachingRegionFactory.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/NoCachingRegionFactory.java
index c7db90429f..f4ba87b58a 100644
--- a/hibernate-core/src/main/java/org/hibernate/cache/internal/NoCachingRegionFactory.java
+++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/NoCachingRegionFactory.java
@@ -42,7 +42,16 @@ import org.hibernate.cache.spi.access.AccessType;
* @author Steve Ebersole
*/
public class NoCachingRegionFactory extends AbstractRegionFactory {
- public static NoCachingRegionFactory INSTANCE = new NoCachingRegionFactory();
+ /**
+ * Singleton access
+ */
+ public static final NoCachingRegionFactory INSTANCE = new NoCachingRegionFactory();
+
+ /**
+ * Constructs a NoCachingRegionFactory. Although access should generally use {@link #INSTANCE}
+ */
+ public NoCachingRegionFactory() {
+ }
@Override
public void start() {
@@ -51,37 +60,45 @@ public class NoCachingRegionFactory extends AbstractRegionFactory {
@Override
public void stop() {
}
+
@Override
public boolean isMinimalPutsEnabledByDefault() {
return false;
}
+
@Override
public AccessType getDefaultAccessType() {
return null;
}
+
@Override
public long nextTimestamp() {
return System.currentTimeMillis() / 100;
}
+
@Override
public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
throw new NoCacheRegionFactoryAvailableException();
}
+
@Override
public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
throw new NoCacheRegionFactoryAvailableException();
}
+
@Override
public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata)
throws CacheException {
throw new NoCacheRegionFactoryAvailableException();
}
+
@Override
public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException {
throw new NoCacheRegionFactoryAvailableException();
}
+
@Override
public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException {
throw new NoCacheRegionFactoryAvailableException();
diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java
index bd2ca22243..e00bbcbbb7 100644
--- a/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java
@@ -28,32 +28,30 @@ import org.jboss.logging.Logger;
import org.hibernate.boot.registry.selector.spi.StrategySelector;
import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cfg.AvailableSettings;
-import org.hibernate.cfg.Configuration;
-import org.hibernate.engine.config.spi.ConfigurationService;
-import org.hibernate.engine.config.spi.StandardConverters;
-import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.CoreMessageLogger;
-import org.hibernate.metamodel.spi.MetadataImplementor;
import org.hibernate.service.spi.ServiceRegistryImplementor;
-import org.hibernate.service.spi.SessionFactoryServiceInitiator;
+import java.util.Map;
+import java.util.Properties;
+
+import org.hibernate.HibernateException;
+import org.hibernate.boot.registry.StandardServiceInitiator;
+import org.hibernate.internal.util.config.ConfigurationHelper;
/**
* Initiator for the {@link RegionFactory} service.
- *
+ *
* @author Hardy Ferentschik
+ * @author Brett Meyer
*/
-public class RegionFactoryInitiator implements SessionFactoryServiceInitiator {
- public static final RegionFactoryInitiator INSTANCE = new RegionFactoryInitiator();
- private static final String DEFAULT_IMPL = NoCachingRegionFactory.class.getName();
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(
- CoreMessageLogger.class,
- RegionFactoryInitiator.class.getName()
- );
+public class RegionFactoryInitiator implements StandardServiceInitiator {
+
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class,
+ RegionFactoryInitiator.class.getName() );
/**
- * Property name to use to configure the full qualified class name for the {@code RegionFactory}
+ * Singleton access
*/
- public static final String IMPL_NAME = AvailableSettings.CACHE_REGION_FACTORY;
+ public static final RegionFactoryInitiator INSTANCE = new RegionFactoryInitiator();
@Override
public Class getServiceInitiated() {
@@ -61,50 +59,58 @@ public class RegionFactoryInitiator implements SessionFactoryServiceInitiator 1 ) {
LOG.trace(
"Unexpected result tuple! tuple is null; should be Object["
@@ -267,8 +299,12 @@ public class StandardQueryCache implements QueryCache {
+ ( returnTypes == null ? "null" : "empty" )
);
}
- LOG.trace( " tuple is Object[" + tuple.length + "]; returnTypes is Type[" + returnTypes.length + "]" );
- if ( tuple.length != returnTypes.length ) {
+ LOG.tracef(
+ "tuple is Object[%s]; returnTypes is %s",
+ tuple.length,
+ returnTypes == null ? "null" : "Type[" + returnTypes.length + "]"
+ );
+ if ( returnTypes != null && tuple.length != returnTypes.length ) {
LOG.trace(
"Unexpected tuple length! transformer= expected="
+ returnTypes.length + " got=" + tuple.length
@@ -276,7 +312,8 @@ public class StandardQueryCache implements QueryCache {
}
else {
for ( int j = 0; j < tuple.length; j++ ) {
- if ( tuple[j] != null && !returnTypes[j].getReturnedClass().isInstance( tuple[j] ) ) {
+ if ( tuple[j] != null && returnTypes != null
+ && ! returnTypes[j].getReturnedClass().isInstance( tuple[j] ) ) {
LOG.trace(
"Unexpected tuple value type! transformer= expected="
+ returnTypes[j].getReturnedClass().getName()
diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/package-info.java
new file mode 100644
index 0000000000..39a20475e8
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/package-info.java
@@ -0,0 +1,28 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2013, Red Hat Inc. 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 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
+ */
+
+/**
+ * Internal implementations and support for second-level caching.
+ */
+package org.hibernate.cache.internal;
diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/UpdateTimestampsCache.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/UpdateTimestampsCache.java
index 292c80b4bf..83a3c4b8b0 100644
--- a/hibernate-core/src/main/java/org/hibernate/cache/spi/UpdateTimestampsCache.java
+++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/UpdateTimestampsCache.java
@@ -29,7 +29,6 @@ import java.util.Set;
import org.jboss.logging.Logger;
-import org.hibernate.HibernateException;
import org.hibernate.cache.CacheException;
import org.hibernate.cfg.Settings;
import org.hibernate.engine.spi.SessionFactoryImplementor;
diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java
index a71318d31f..2f28f77f93 100644
--- a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java
+++ b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java
@@ -150,6 +150,7 @@ import org.hibernate.cfg.annotations.PropertyBinder;
import org.hibernate.cfg.annotations.QueryBinder;
import org.hibernate.cfg.annotations.SimpleValueBinder;
import org.hibernate.cfg.annotations.TableBinder;
+import org.hibernate.engine.OptimisticLockStyle;
import org.hibernate.engine.internal.Versioning;
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.id.MultipleHiLoPerTableGenerator;
@@ -1561,7 +1562,7 @@ public final class AnnotationBinder {
SimpleValue simpleValue = ( SimpleValue ) prop.getValue();
simpleValue.setNullValue( "undefined" );
- rootClass.setOptimisticLockMode( Versioning.OPTIMISTIC_LOCK_VERSION );
+ rootClass.setOptimisticLockStyle( OptimisticLockStyle.VERSION );
if ( traceEnabled ) {
LOG.tracev( "Version name: {0}, unsavedValue: {1}", rootClass.getVersion().getName(),
( (SimpleValue) rootClass.getVersion().getValue() ).getNullValue() );
diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/AvailableSettings.java b/hibernate-core/src/main/java/org/hibernate/cfg/AvailableSettings.java
index 8fb8a641e0..b7282edfd7 100644
--- a/hibernate-core/src/main/java/org/hibernate/cfg/AvailableSettings.java
+++ b/hibernate-core/src/main/java/org/hibernate/cfg/AvailableSettings.java
@@ -23,8 +23,6 @@
*/
package org.hibernate.cfg;
-import org.hibernate.tool.hbm2ddl.DatabaseMetadata;
-
/**
* @author Steve Ebersole
*/
@@ -697,4 +695,22 @@ public interface AvailableSettings {
* Oracle), this is disabled by default.
*/
public static final String ENABLE_SYNONYMS = "hibernate.synonyms";
+
+ /**
+ * Unique columns and unique keys both use unique constraints in most dialects.
+ * SchemaUpdate needs to create these constraints, but DB's
+ * support for finding existing constraints is extremely inconsistent. Further,
+ * non-explicitly-named unique constraints use randomly generated characters.
+ *
+ * Therefore, select from these strategies.
+ * {@link org.hibernate.tool.hbm2ddl.UniqueConstraintSchemaUpdateStrategy#DROP_RECREATE_QUIETLY} (DEFAULT):
+ * Attempt to drop, then (re-)create each unique constraint.
+ * Ignore any exceptions thrown.
+ * {@link org.hibernate.tool.hbm2ddl.UniqueConstraintSchemaUpdateStrategy#RECREATE_QUIETLY}:
+ * attempt to (re-)create unique constraints,
+ * ignoring exceptions thrown if the constraint already existed
+ * {@link org.hibernate.tool.hbm2ddl.UniqueConstraintSchemaUpdateStrategy#SKIP}:
+ * do not attempt to create unique constraints on a schema update
+ */
+ public static final String UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY = "hibernate.schema_update.unique_constraint_strategy";
}
diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java
index 8f3557f6e6..57b8525787 100644
--- a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java
+++ b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java
@@ -82,6 +82,7 @@ import org.hibernate.annotations.common.reflection.ReflectionManager;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.java.JavaReflectionManager;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
+import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl;
import org.hibernate.cfg.annotations.reflection.JPAMetadataProvider;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
@@ -89,6 +90,7 @@ import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.engine.ResultSetMappingDefinition;
+import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.NamedQueryDefinition;
@@ -136,13 +138,17 @@ import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.Table;
import org.hibernate.mapping.TypeDef;
import org.hibernate.mapping.UniqueKey;
+import org.hibernate.metamodel.spi.TypeContributions;
+import org.hibernate.metamodel.spi.TypeContributor;
import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.secure.spi.GrantedPermission;
import org.hibernate.secure.spi.JaccPermissionDeclarations;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.DatabaseMetadata;
import org.hibernate.tool.hbm2ddl.IndexMetadata;
+import org.hibernate.tool.hbm2ddl.SchemaUpdateScript;
import org.hibernate.tool.hbm2ddl.TableMetadata;
+import org.hibernate.tool.hbm2ddl.UniqueConstraintSchemaUpdateStrategy;
import org.hibernate.tuple.entity.EntityTuplizerFactory;
import org.hibernate.type.BasicType;
import org.hibernate.type.SerializationException;
@@ -221,7 +227,9 @@ public class Configuration implements Serializable {
protected Map extendsQueue;
protected Map sqlFunctions;
+
private TypeResolver typeResolver = new TypeResolver();
+ private List typeContributorRegistrations = new ArrayList();
private EntityTuplizerFactory entityTuplizerFactory;
// private ComponentTuplizerFactory componentTuplizerFactory; todo : HHH-3517 and HHH-1907
@@ -1117,57 +1125,64 @@ public class Configuration implements Serializable {
*
* @throws HibernateException Generally indicates a problem calling {@link #buildMappings()}
*
- * @see org.hibernate.tool.hbm2ddl.SchemaExport
+ * @see org.hibernate.tool.hbm2ddl.SchemaUpdate
+ *
+ * @deprecated Use {@link #generateSchemaUpdateScriptList(Dialect, DatabaseMetadata)} instead
*/
@SuppressWarnings({ "unchecked" })
+ @Deprecated
public String[] generateSchemaUpdateScript(Dialect dialect, DatabaseMetadata databaseMetadata)
throws HibernateException {
+ List scripts = generateSchemaUpdateScriptList( dialect, databaseMetadata );
+ return SchemaUpdateScript.toStringArray( scripts );
+ }
+
+ /**
+ * @param dialect The dialect for which to generate the creation script
+ * @param databaseMetadata The database catalog information for the database to be updated; needed to work out what
+ * should be created/altered
+ *
+ * @return The sequence of DDL commands to apply the schema objects
+ *
+ * @throws HibernateException Generally indicates a problem calling {@link #buildMappings()}
+ *
+ * @see org.hibernate.tool.hbm2ddl.SchemaUpdate
+ */
+ public List generateSchemaUpdateScriptList(Dialect dialect, DatabaseMetadata databaseMetadata)
+ throws HibernateException {
secondPassCompile();
String defaultCatalog = properties.getProperty( Environment.DEFAULT_CATALOG );
String defaultSchema = properties.getProperty( Environment.DEFAULT_SCHEMA );
+ UniqueConstraintSchemaUpdateStrategy constraintMethod = UniqueConstraintSchemaUpdateStrategy.interpret( properties
+ .get( Environment.UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY ) );
- ArrayList script = new ArrayList( 50 );
+ List scripts = new ArrayList();
Iterator iter = getTableMappings();
while ( iter.hasNext() ) {
Table table = (Table) iter.next();
- String tableSchema = ( table.getSchema() == null ) ? defaultSchema : table.getSchema() ;
+ String tableSchema = ( table.getSchema() == null ) ? defaultSchema : table.getSchema();
String tableCatalog = ( table.getCatalog() == null ) ? defaultCatalog : table.getCatalog();
if ( table.isPhysicalTable() ) {
- TableMetadata tableInfo = databaseMetadata.getTableMetadata(
- table.getName(),
- tableSchema,
- tableCatalog,
- table.isQuoted()
- );
+ TableMetadata tableInfo = databaseMetadata.getTableMetadata( table.getName(), tableSchema,
+ tableCatalog, table.isQuoted() );
if ( tableInfo == null ) {
- script.add(
- table.sqlCreateString(
- dialect,
- mapping,
- tableCatalog,
- tableSchema
- )
- );
+ scripts.add( new SchemaUpdateScript( table.sqlCreateString( dialect, mapping, tableCatalog,
+ tableSchema ), false ) );
}
else {
- Iterator subiter = table.sqlAlterStrings(
- dialect,
- mapping,
- tableInfo,
- tableCatalog,
- tableSchema
- );
+ Iterator subiter = table.sqlAlterStrings( dialect, mapping, tableInfo, tableCatalog,
+ tableSchema );
while ( subiter.hasNext() ) {
- script.add( subiter.next() );
+ scripts.add( new SchemaUpdateScript( subiter.next(), false ) );
}
}
Iterator comments = table.sqlCommentStrings( dialect, defaultCatalog, defaultSchema );
while ( comments.hasNext() ) {
- script.add( comments.next() );
+ scripts.add( new SchemaUpdateScript( comments.next(), false ) );
}
}
@@ -1176,32 +1191,34 @@ public class Configuration implements Serializable {
iter = getTableMappings();
while ( iter.hasNext() ) {
Table table = (Table) iter.next();
- String tableSchema = ( table.getSchema() == null ) ? defaultSchema : table.getSchema() ;
+ String tableSchema = ( table.getSchema() == null ) ? defaultSchema : table.getSchema();
String tableCatalog = ( table.getCatalog() == null ) ? defaultCatalog : table.getCatalog();
if ( table.isPhysicalTable() ) {
- TableMetadata tableInfo = databaseMetadata.getTableMetadata(
- table.getName(),
- tableSchema,
- tableCatalog,
- table.isQuoted()
- );
+ TableMetadata tableInfo = databaseMetadata.getTableMetadata( table.getName(), tableSchema,
+ tableCatalog, table.isQuoted() );
- Iterator uniqueIter = table.getUniqueKeyIterator();
- while ( uniqueIter.hasNext() ) {
- final UniqueKey uniqueKey = (UniqueKey) uniqueIter.next();
- // Skip if index already exists. Most of the time, this
- // won't work since most Dialects use Constraints. However,
- // keep it for the few that do use Indexes.
- if ( tableInfo != null && StringHelper.isNotEmpty( uniqueKey.getName() ) ) {
- final IndexMetadata meta = tableInfo.getIndexMetadata( uniqueKey.getName() );
- if ( meta != null ) {
- continue;
+ if (! constraintMethod.equals( UniqueConstraintSchemaUpdateStrategy.SKIP )) {
+ Iterator uniqueIter = table.getUniqueKeyIterator();
+ while ( uniqueIter.hasNext() ) {
+ final UniqueKey uniqueKey = (UniqueKey) uniqueIter.next();
+ // Skip if index already exists. Most of the time, this
+ // won't work since most Dialects use Constraints. However,
+ // keep it for the few that do use Indexes.
+ if ( tableInfo != null && StringHelper.isNotEmpty( uniqueKey.getName() ) ) {
+ final IndexMetadata meta = tableInfo.getIndexMetadata( uniqueKey.getName() );
+ if ( meta != null ) {
+ continue;
+ }
}
+ String constraintString = uniqueKey.sqlCreateString( dialect, mapping, tableCatalog, tableSchema );
+ if ( constraintString != null && !constraintString.isEmpty() )
+ if ( constraintMethod.equals( UniqueConstraintSchemaUpdateStrategy.DROP_RECREATE_QUIETLY ) ) {
+ String constraintDropString = uniqueKey.sqlDropString( dialect, tableCatalog, tableCatalog );
+ scripts.add( new SchemaUpdateScript( constraintDropString, true) );
+ }
+ scripts.add( new SchemaUpdateScript( constraintString, true) );
}
- String constraintString = uniqueKey.sqlCreateString( dialect,
- mapping, tableCatalog, tableSchema );
- if (constraintString != null) script.add( constraintString );
}
if ( dialect.hasAlterTable() ) {
@@ -1209,22 +1226,12 @@ public class Configuration implements Serializable {
while ( subIter.hasNext() ) {
ForeignKey fk = (ForeignKey) subIter.next();
if ( fk.isPhysicalConstraint() ) {
- boolean create = tableInfo == null || (
- tableInfo.getForeignKeyMetadata( fk ) == null && (
- //Icky workaround for MySQL bug:
- !( dialect instanceof MySQLDialect ) ||
- tableInfo.getIndexMetadata( fk.getName() ) == null
- )
- );
+ boolean create = tableInfo == null || ( tableInfo.getForeignKeyMetadata( fk ) == null && (
+ // Icky workaround for MySQL bug:
+ !( dialect instanceof MySQLDialect ) || tableInfo.getIndexMetadata( fk.getName() ) == null ) );
if ( create ) {
- script.add(
- fk.sqlCreateString(
- dialect,
- mapping,
- tableCatalog,
- tableSchema
- )
- );
+ scripts.add( new SchemaUpdateScript( fk.sqlCreateString( dialect, mapping,
+ tableCatalog, tableSchema ), false ) );
}
}
}
@@ -1240,14 +1247,8 @@ public class Configuration implements Serializable {
continue;
}
}
- script.add(
- index.sqlCreateString(
- dialect,
- mapping,
- tableCatalog,
- tableSchema
- )
- );
+ scripts.add( new SchemaUpdateScript( index.sqlCreateString( dialect, mapping, tableCatalog,
+ tableSchema ), false ) );
}
}
}
@@ -1258,11 +1259,11 @@ public class Configuration implements Serializable {
Object key = generator.generatorKey();
if ( !databaseMetadata.isSequence( key ) && !databaseMetadata.isTable( key ) ) {
String[] lines = generator.sqlCreateStrings( dialect );
- script.addAll( Arrays.asList( lines ) );
+ scripts.addAll( SchemaUpdateScript.fromStringArray( lines, false ) );
}
}
- return ArrayHelper.toStringArray( script );
+ return scripts;
}
public void validateSchema(Dialect dialect, DatabaseMetadata databaseMetadata)throws HibernateException {
@@ -1787,7 +1788,8 @@ public class Configuration implements Serializable {
*/
public SessionFactory buildSessionFactory(ServiceRegistry serviceRegistry) throws HibernateException {
LOG.debugf( "Preparing to build session factory with filters : %s", filterDefinitions );
-
+
+ buildTypeRegistrations( serviceRegistry );
secondPassCompile();
if ( !metadataSourceQueue.isEmpty() ) {
LOG.incompleteMappingMetadataCacheProcessing();
@@ -1809,6 +1811,39 @@ public class Configuration implements Serializable {
sessionFactoryObserver
);
}
+
+ private void buildTypeRegistrations(ServiceRegistry serviceRegistry) {
+ final TypeContributions typeContributions = new TypeContributions() {
+ @Override
+ public void contributeType(BasicType type) {
+ typeResolver.registerTypeOverride( type );
+ }
+
+ @Override
+ public void contributeType(UserType type, String[] keys) {
+ typeResolver.registerTypeOverride( type, keys );
+ }
+
+ @Override
+ public void contributeType(CompositeUserType type, String[] keys) {
+ typeResolver.registerTypeOverride( type, keys );
+ }
+ };
+
+ // add Dialect contributed types
+ final Dialect dialect = serviceRegistry.getService( JdbcServices.class ).getDialect();
+ dialect.contributeTypes( typeContributions, serviceRegistry );
+
+ // add TypeContributor contributed types.
+ ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class );
+ for ( TypeContributor contributor : classLoaderService.loadJavaServices( TypeContributor.class ) ) {
+ contributor.contribute( typeContributions, serviceRegistry );
+ }
+ // from app registrations
+ for ( TypeContributor contributor : typeContributorRegistrations ) {
+ contributor.contribute( typeContributions, serviceRegistry );
+ }
+ }
/**
* Create a {@link SessionFactory} using the properties and mappings in this configuration. The
@@ -2515,6 +2550,10 @@ public class Configuration implements Serializable {
getTypeResolver().registerTypeOverride( type, keys );
}
+ public void registerTypeContributor(TypeContributor typeContributor) {
+ typeContributorRegistrations.add( typeContributor );
+ }
+
public SessionFactoryObserver getSessionFactoryObserver() {
return sessionFactoryObserver;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java
index a46b925059..f9701eb4fd 100644
--- a/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java
+++ b/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java
@@ -40,7 +40,7 @@ import org.hibernate.EntityMode;
import org.hibernate.FetchMode;
import org.hibernate.FlushMode;
import org.hibernate.MappingException;
-import org.hibernate.engine.internal.Versioning;
+import org.hibernate.engine.OptimisticLockStyle;
import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle;
import org.hibernate.engine.spi.FilterDefinition;
import org.hibernate.engine.spi.NamedQueryDefinition;
@@ -687,7 +687,7 @@ public final class HbmBinder {
// OPTIMISTIC LOCK MODE
Attribute olNode = node.attribute( "optimistic-lock" );
- entity.setOptimisticLockMode( getOptimisticLockMode( olNode ) );
+ entity.setOptimisticLockStyle( getOptimisticLockStyle( olNode ) );
entity.setMetaAttributes( getMetas( node, inheritedMetas ) );
@@ -2896,21 +2896,23 @@ public final class HbmBinder {
}
}
- private static int getOptimisticLockMode(Attribute olAtt) throws MappingException {
+ private static OptimisticLockStyle getOptimisticLockStyle(Attribute olAtt) throws MappingException {
+ if ( olAtt == null ) {
+ return OptimisticLockStyle.VERSION;
+ }
- if ( olAtt == null ) return Versioning.OPTIMISTIC_LOCK_VERSION;
- String olMode = olAtt.getValue();
+ final String olMode = olAtt.getValue();
if ( olMode == null || "version".equals( olMode ) ) {
- return Versioning.OPTIMISTIC_LOCK_VERSION;
+ return OptimisticLockStyle.VERSION;
}
else if ( "dirty".equals( olMode ) ) {
- return Versioning.OPTIMISTIC_LOCK_DIRTY;
+ return OptimisticLockStyle.DIRTY;
}
else if ( "all".equals( olMode ) ) {
- return Versioning.OPTIMISTIC_LOCK_ALL;
+ return OptimisticLockStyle.ALL;
}
else if ( "none".equals( olMode ) ) {
- return Versioning.OPTIMISTIC_LOCK_NONE;
+ return OptimisticLockStyle.NONE;
}
else {
throw new MappingException( "Unsupported optimistic-lock style: " + olMode );
@@ -2932,7 +2934,7 @@ public final class HbmBinder {
boolean inheritable = Boolean
.valueOf( metaNode.attributeValue( "inherit" ) )
.booleanValue();
- if ( onlyInheritable & !inheritable ) {
+ if ( onlyInheritable && !inheritable ) {
continue;
}
String name = metaNode.attributeValue( "attribute" );
diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java
index 91122cc6e1..f9b64312ec 100644
--- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java
+++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java
@@ -1139,7 +1139,11 @@ public abstract class CollectionBinder {
XProperty property,
PropertyHolder parentPropertyHolder,
Mappings mappings) throws MappingException {
- PersistentClass collectionEntity = (PersistentClass) persistentClasses.get( collType.getName() );
+ if ( property == null ) {
+ throw new IllegalArgumentException( "null was passed for argument property" );
+ }
+
+ final PersistentClass collectionEntity = (PersistentClass) persistentClasses.get( collType.getName() );
final String hqlOrderBy = extractHqlOrderBy( jpaOrderBy );
boolean isCollectionOfEntities = collectionEntity != null;
@@ -1269,9 +1273,11 @@ public abstract class CollectionBinder {
buildOrderByClauseFromHql( hqlOrderBy, collectionEntity, collValue.getRole() )
);
}
- ForeignKey fk = property != null ? property.getAnnotation( ForeignKey.class ) : null;
+ final ForeignKey fk = property.getAnnotation( ForeignKey.class );
String fkName = fk != null ? fk.inverseName() : "";
- if ( !BinderHelper.isEmptyAnnotationValue( fkName ) ) element.setForeignKeyName( fkName );
+ if ( !BinderHelper.isEmptyAnnotationValue( fkName ) ) {
+ element.setForeignKeyName( fkName );
+ }
}
else if ( anyAnn != null ) {
//@ManyToAny
diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java
index d708973460..1fc2e7a75f 100644
--- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java
+++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java
@@ -82,6 +82,7 @@ import org.hibernate.cfg.ObjectNameNormalizer;
import org.hibernate.cfg.ObjectNameSource;
import org.hibernate.cfg.PropertyHolder;
import org.hibernate.cfg.UniqueConstraintHolder;
+import org.hibernate.engine.OptimisticLockStyle;
import org.hibernate.engine.internal.Versioning;
import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle;
import org.hibernate.engine.spi.FilterDefinition;
@@ -270,7 +271,7 @@ public class EntityBinder {
LOG.immutableAnnotationOnNonRoot(annotatedClass.getName());
}
}
- persistentClass.setOptimisticLockMode( getVersioning( optimisticLockType ) );
+ persistentClass.setOptimisticLockStyle( getVersioning( optimisticLockType ) );
persistentClass.setSelectBeforeUpdate( selectBeforeUpdate );
//set persister if needed
@@ -404,16 +405,16 @@ public class EntityBinder {
}
}
- int getVersioning(OptimisticLockType type) {
+ OptimisticLockStyle getVersioning(OptimisticLockType type) {
switch ( type ) {
case VERSION:
- return Versioning.OPTIMISTIC_LOCK_VERSION;
+ return OptimisticLockStyle.VERSION;
case NONE:
- return Versioning.OPTIMISTIC_LOCK_NONE;
+ return OptimisticLockStyle.NONE;
case DIRTY:
- return Versioning.OPTIMISTIC_LOCK_DIRTY;
+ return OptimisticLockStyle.DIRTY;
case ALL:
- return Versioning.OPTIMISTIC_LOCK_ALL;
+ return OptimisticLockStyle.ALL;
default:
throw new AssertionFailure( "optimistic locking not supported: " + type );
}
diff --git a/hibernate-core/src/main/java/org/hibernate/classic/Lifecycle.java b/hibernate-core/src/main/java/org/hibernate/classic/Lifecycle.java
index 9af6bc9fe0..1becbbc3a1 100644
--- a/hibernate-core/src/main/java/org/hibernate/classic/Lifecycle.java
+++ b/hibernate-core/src/main/java/org/hibernate/classic/Lifecycle.java
@@ -75,7 +75,7 @@ public interface Lifecycle {
* Called when an entity is saved.
* @param s the session
* @return true to veto save
- * @throws CallbackException
+ * @throws CallbackException Indicates a problem happened during callback
*/
public boolean onSave(Session s) throws CallbackException;
@@ -85,7 +85,7 @@ public interface Lifecycle {
* state is persisted during a flush.
* @param s the session
* @return true to veto update
- * @throws CallbackException
+ * @throws CallbackException Indicates a problem happened during callback
*/
public boolean onUpdate(Session s) throws CallbackException;
@@ -93,7 +93,7 @@ public interface Lifecycle {
* Called when an entity is deleted.
* @param s the session
* @return true to veto delete
- * @throws CallbackException
+ * @throws CallbackException Indicates a problem happened during callback
*/
public boolean onDelete(Session s) throws CallbackException;
@@ -108,9 +108,3 @@ public interface Lifecycle {
*/
public void onLoad(Session s, Serializable id);
}
-
-
-
-
-
-
diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/AbstractPersistentCollection.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/AbstractPersistentCollection.java
index e3675af1c6..31c9a4f4b1 100644
--- a/hibernate-core/src/main/java/org/hibernate/collection/internal/AbstractPersistentCollection.java
+++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/AbstractPersistentCollection.java
@@ -80,41 +80,57 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
private Serializable storedSnapshot;
private String sessionFactoryUuid;
- private boolean specjLazyLoad = false;
+ private boolean specjLazyLoad;
+ /**
+ * Not called by Hibernate, but used by non-JDK serialization,
+ * eg. SOAP libraries.
+ */
+ public AbstractPersistentCollection() {
+ }
+
+ protected AbstractPersistentCollection(SessionImplementor session) {
+ this.session = session;
+ }
+
+ @Override
public final String getRole() {
return role;
}
+ @Override
public final Serializable getKey() {
return key;
}
+ @Override
public final boolean isUnreferenced() {
return role == null;
}
+ @Override
public final boolean isDirty() {
return dirty;
}
+ @Override
public final void clearDirty() {
dirty = false;
}
+ @Override
public final void dirty() {
dirty = true;
}
+ @Override
public final Serializable getStoredSnapshot() {
return storedSnapshot;
}
//Careful: these methods do not initialize the collection.
- /**
- * Is the initialized collection empty?
- */
+ @Override
public abstract boolean empty();
/**
@@ -134,14 +150,14 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
return true;
}
else {
- boolean isExtraLazy = withTemporarySessionIfNeeded(
+ final boolean isExtraLazy = withTemporarySessionIfNeeded(
new LazyInitializationWork() {
@Override
public Boolean doWork() {
- CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
+ final CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
if ( entry != null ) {
- CollectionPersister persister = entry.getLoadedPersister();
+ final CollectionPersister persister = entry.getLoadedPersister();
if ( persister.isExtraLazy() ) {
if ( hasQueuedOperations() ) {
session.flush();
@@ -168,7 +184,17 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
return false;
}
+ /**
+ * TBH not sure why this is public
+ *
+ * @param The java type of the return for this LazyInitializationWork
+ */
public static interface LazyInitializationWork {
+ /**
+ * Do the represented work and return the result.
+ *
+ * @return The result
+ */
public T doWork();
}
@@ -221,7 +247,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
// be created even if a current session and transaction are
// open (ex: session.clear() was used). We must prevent
// multiple transactions.
- ( ( Session) session ).beginTransaction();
+ ( (Session) session ).beginTransaction();
}
session.getPersistenceContext().addUninitializedDetachedCollection(
@@ -238,7 +264,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
// make sure the just opened temp session gets closed!
try {
if ( !isJTA ) {
- ( ( Session) session ).getTransaction().commit();
+ ( (Session) session ).getTransaction().commit();
}
( (Session) session ).close();
}
@@ -255,19 +281,19 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
throwLazyInitializationException( "SessionFactory UUID not known to create temporary Session for loading" );
}
- SessionFactoryImplementor sf = (SessionFactoryImplementor)
+ final SessionFactoryImplementor sf = (SessionFactoryImplementor)
SessionFactoryRegistry.INSTANCE.getSessionFactory( sessionFactoryUuid );
return (SessionImplementor) sf.openSession();
}
protected Boolean readIndexExistence(final Object index) {
if ( !initialized ) {
- Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded(
+ final Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded(
new LazyInitializationWork() {
@Override
public Boolean doWork() {
- CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
- CollectionPersister persister = entry.getLoadedPersister();
+ final CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
+ final CollectionPersister persister = entry.getLoadedPersister();
if ( persister.isExtraLazy() ) {
if ( hasQueuedOperations() ) {
session.flush();
@@ -290,12 +316,12 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
protected Boolean readElementExistence(final Object element) {
if ( !initialized ) {
- Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded(
+ final Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded(
new LazyInitializationWork() {
@Override
public Boolean doWork() {
- CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
- CollectionPersister persister = entry.getLoadedPersister();
+ final CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
+ final CollectionPersister persister = entry.getLoadedPersister();
if ( persister.isExtraLazy() ) {
if ( hasQueuedOperations() ) {
session.flush();
@@ -326,8 +352,8 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
@Override
public Object doWork() {
- CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
- CollectionPersister persister = entry.getLoadedPersister();
+ final CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this );
+ final CollectionPersister persister = entry.getLoadedPersister();
isExtraLazy = persister.isExtraLazy();
if ( isExtraLazy ) {
if ( hasQueuedOperations() ) {
@@ -342,7 +368,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
}
- ExtraLazyElementByIndexReader reader = new ExtraLazyElementByIndexReader();
+ final ExtraLazyElementByIndexReader reader = new ExtraLazyElementByIndexReader();
//noinspection unchecked
withTemporarySessionIfNeeded( reader );
if ( reader.isExtraLazy ) {
@@ -358,9 +384,9 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
private boolean isConnectedToSession() {
- return session != null &&
- session.isOpen() &&
- session.getPersistenceContext().containsCollection( this );
+ return session != null
+ && session.isOpen()
+ && session.getPersistenceContext().containsCollection( this );
}
/**
@@ -377,9 +403,9 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
*/
@SuppressWarnings({"JavaDoc"})
protected boolean isOperationQueueEnabled() {
- return !initialized &&
- isConnectedToSession() &&
- isInverseCollection();
+ return !initialized
+ && isConnectedToSession()
+ && isInverseCollection();
}
/**
@@ -389,9 +415,9 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
*/
@SuppressWarnings({"JavaDoc"})
protected boolean isPutQueueEnabled() {
- return !initialized &&
- isConnectedToSession() &&
- isInverseOneToManyOrNoOrphanDelete();
+ return !initialized
+ && isConnectedToSession()
+ && isInverseOneToManyOrNoOrphanDelete();
}
/**
@@ -401,9 +427,9 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
*/
@SuppressWarnings({"JavaDoc"})
protected boolean isClearQueueEnabled() {
- return !initialized &&
- isConnectedToSession() &&
- isInverseCollectionNoOrphanDelete();
+ return !initialized
+ && isConnectedToSession()
+ && isInverseCollectionNoOrphanDelete();
}
/**
@@ -411,7 +437,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
*/
@SuppressWarnings({"JavaDoc"})
private boolean isInverseCollection() {
- CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
+ final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
return ce != null && ce.getLoadedPersister().isInverse();
}
@@ -421,8 +447,9 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
*/
@SuppressWarnings({"JavaDoc"})
private boolean isInverseCollectionNoOrphanDelete() {
- CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
- return ce != null &&
+ final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
+ return ce != null
+ &&
ce.getLoadedPersister().isInverse() &&
!ce.getLoadedPersister().hasOrphanDelete();
}
@@ -433,11 +460,10 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
*/
@SuppressWarnings({"JavaDoc"})
private boolean isInverseOneToManyOrNoOrphanDelete() {
- CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
- return ce != null && ce.getLoadedPersister().isInverse() && (
- ce.getLoadedPersister().isOneToMany() ||
- !ce.getLoadedPersister().hasOrphanDelete()
- );
+ final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
+ return ce != null
+ && ce.getLoadedPersister().isInverse()
+ && ( ce.getLoadedPersister().isOneToMany() || !ce.getLoadedPersister().hasOrphanDelete() );
}
/**
@@ -449,7 +475,8 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
operationQueue = new ArrayList( 10 );
}
operationQueue.add( operation );
- dirty = true; //needed so that we remove this collection from the second-level cache
+ //needed so that we remove this collection from the second-level cache
+ dirty = true;
}
/**
@@ -462,59 +489,38 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
}
- /**
- * After flushing, re-init snapshot state.
- */
+ @Override
public void setSnapshot(Serializable key, String role, Serializable snapshot) {
this.key = key;
this.role = role;
this.storedSnapshot = snapshot;
}
- /**
- * After flushing, clear any "queued" additions, since the
- * database state is now synchronized with the memory state.
- */
+ @Override
public void postAction() {
operationQueue = null;
cachedSize = -1;
clearDirty();
}
- /**
- * Not called by Hibernate, but used by non-JDK serialization,
- * eg. SOAP libraries.
- */
- public AbstractPersistentCollection() {
- }
-
- protected AbstractPersistentCollection(SessionImplementor session) {
- this.session = session;
- }
-
- /**
- * return the user-visible collection (or array) instance
- */
+ @Override
public Object getValue() {
return this;
}
- /**
- * Called just before reading any rows from the JDBC result set
- */
+ @Override
public void beginRead() {
// override on some subclasses
initializing = true;
}
- /**
- * Called after reading all rows from the JDBC result set
- */
+ @Override
public boolean endRead() {
//override on some subclasses
return afterInitialize();
}
+ @Override
public boolean afterInitialize() {
setInitialized();
//do this bit after setting initialized to true or it will recurse
@@ -579,19 +585,12 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
this.directlyAccessible = directlyAccessible;
}
- /**
- * Could the application possibly have a direct reference to
- * the underlying collection implementation?
- */
+ @Override
public boolean isDirectlyAccessible() {
return directlyAccessible;
}
- /**
- * Disassociate this collection from the given session.
- *
- * @return true if this was currently associated with the given session
- */
+ @Override
public final boolean unsetSession(SessionImplementor currentSession) {
prepareForPossibleSpecialSpecjInitialization();
if ( currentSession == this.session ) {
@@ -619,21 +618,14 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
- /**
- * Associate the collection with the given session.
- *
- * @return false if the collection was already associated with the session
- *
- * @throws HibernateException if the collection was already associated
- * with another open session
- */
+ @Override
public final boolean setCurrentSession(SessionImplementor session) throws HibernateException {
if ( session == this.session ) {
return false;
}
else {
if ( isConnectedToSession() ) {
- CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
+ final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this );
if ( ce == null ) {
throw new HibernateException(
"Illegal attempt to associate a collection with two open sessions"
@@ -656,17 +648,12 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
}
- /**
- * Do we need to completely recreate this collection when it changes?
- */
+ @Override
public boolean needsRecreate(CollectionPersister persister) {
return false;
}
- /**
- * To be called internally by the session, forcing
- * immediate initialization.
- */
+ @Override
public final void forceInitialization() throws HibernateException {
if ( !initialized ) {
if ( initializing ) {
@@ -691,40 +678,38 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
return session.getPersistenceContext().getSnapshot( this );
}
- /**
- * Is this instance initialized?
- */
+ @Override
public final boolean wasInitialized() {
return initialized;
}
+ @Override
public boolean isRowUpdatePossible() {
return true;
}
- /**
- * Does this instance have any "queued" additions?
- */
+ @Override
public final boolean hasQueuedOperations() {
return operationQueue != null;
}
- /**
- * Iterate the "queued" additions
- */
+ @Override
public final Iterator queuedAdditionIterator() {
if ( hasQueuedOperations() ) {
return new Iterator() {
- int i = 0;
+ private int index;
+ @Override
public Object next() {
- return operationQueue.get( i++ ).getAddedInstance();
+ return operationQueue.get( index++ ).getAddedInstance();
}
+ @Override
public boolean hasNext() {
- return i < operationQueue.size();
+ return index < operationQueue.size();
}
+ @Override
public void remove() {
throw new UnsupportedOperationException();
}
@@ -735,14 +720,12 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
}
- /**
- * Iterate the "queued" additions
- */
+ @Override
@SuppressWarnings({"unchecked"})
public final Collection getQueuedOrphans(String entityName) {
if ( hasQueuedOperations() ) {
- Collection additions = new ArrayList( operationQueue.size() );
- Collection removals = new ArrayList( operationQueue.size() );
+ final Collection additions = new ArrayList( operationQueue.size() );
+ final Collection removals = new ArrayList( operationQueue.size() );
for ( DelayedOperation operation : operationQueue ) {
additions.add( operation.getAddedInstance() );
removals.add( operation.getOrphan() );
@@ -754,28 +737,22 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
}
- /**
- * Called before inserting rows, to ensure that any surrogate keys
- * are fully generated
- */
+ @Override
public void preInsert(CollectionPersister persister) throws HibernateException {
}
- /**
- * Called after inserting a row, to fetch the natively generated id
- */
+ @Override
public void afterRowInsert(CollectionPersister persister, Object entry, int i) throws HibernateException {
}
- /**
- * get all "orphaned" elements
- */
+ @Override
public abstract Collection getOrphans(Serializable snapshot, String entityName) throws HibernateException;
/**
- * Get the current session
+ * Get the session currently associated with this collection.
+ *
+ * @return The session
*/
- @SuppressWarnings({"JavaDoc"})
public final SessionImplementor getSession() {
return session;
}
@@ -787,19 +764,21 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
this.itr = itr;
}
+ @Override
public boolean hasNext() {
return itr.hasNext();
}
+ @Override
public Object next() {
return itr.next();
}
+ @Override
public void remove() {
write();
itr.remove();
}
-
}
protected final class ListIteratorProxy implements ListIterator {
@@ -809,47 +788,55 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
this.itr = itr;
}
+ @Override
@SuppressWarnings({"unchecked"})
public void add(Object o) {
write();
itr.add( o );
}
+ @Override
public boolean hasNext() {
return itr.hasNext();
}
+ @Override
public boolean hasPrevious() {
return itr.hasPrevious();
}
+ @Override
public Object next() {
return itr.next();
}
+ @Override
public int nextIndex() {
return itr.nextIndex();
}
+ @Override
public Object previous() {
return itr.previous();
}
+ @Override
public int previousIndex() {
return itr.previousIndex();
}
+ @Override
public void remove() {
write();
itr.remove();
}
+ @Override
@SuppressWarnings({"unchecked"})
public void set(Object o) {
write();
itr.set( o );
}
-
}
protected class SetProxy implements java.util.Set {
@@ -859,67 +846,82 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
this.set = set;
}
+ @Override
@SuppressWarnings({"unchecked"})
public boolean add(Object o) {
write();
return set.add( o );
}
+ @Override
@SuppressWarnings({"unchecked"})
public boolean addAll(Collection c) {
write();
return set.addAll( c );
}
+ @Override
public void clear() {
write();
set.clear();
}
+ @Override
public boolean contains(Object o) {
return set.contains( o );
}
+ @Override
+ @SuppressWarnings("unchecked")
public boolean containsAll(Collection c) {
return set.containsAll( c );
}
+ @Override
public boolean isEmpty() {
return set.isEmpty();
}
+ @Override
public Iterator iterator() {
return new IteratorProxy( set.iterator() );
}
+ @Override
public boolean remove(Object o) {
write();
return set.remove( o );
}
+ @Override
+ @SuppressWarnings("unchecked")
public boolean removeAll(Collection c) {
write();
return set.removeAll( c );
}
+ @Override
+ @SuppressWarnings("unchecked")
public boolean retainAll(Collection c) {
write();
return set.retainAll( c );
}
+ @Override
public int size() {
return set.size();
}
+ @Override
public Object[] toArray() {
return set.toArray();
}
+ @Override
@SuppressWarnings({"unchecked"})
public Object[] toArray(Object[] array) {
return set.toArray( array );
}
-
}
protected final class ListProxy implements java.util.List {
@@ -969,6 +971,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
@Override
+ @SuppressWarnings("unchecked")
public boolean containsAll(Collection c) {
return list.containsAll( c );
}
@@ -1021,12 +1024,14 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
@Override
+ @SuppressWarnings("unchecked")
public boolean removeAll(Collection c) {
write();
return list.removeAll( c );
}
@Override
+ @SuppressWarnings("unchecked")
public boolean retainAll(Collection c) {
write();
return list.retainAll( c );
@@ -1087,29 +1092,31 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
// short-circuit(s)
if ( currentElements.size() == 0 ) {
- return oldElements; // no new elements, the old list contains only Orphans
+ // no new elements, the old list contains only Orphans
+ return oldElements;
}
if ( oldElements.size() == 0 ) {
- return oldElements; // no old elements, so no Orphans neither
+ // no old elements, so no Orphans neither
+ return oldElements;
}
final EntityPersister entityPersister = session.getFactory().getEntityPersister( entityName );
final Type idType = entityPersister.getIdentifierType();
// create the collection holding the Orphans
- Collection res = new ArrayList();
+ final Collection res = new ArrayList();
// collect EntityIdentifier(s) of the *current* elements - add them into a HashSet for fast access
- java.util.Set currentIds = new HashSet();
- java.util.Set currentSaving = new IdentitySet();
+ final java.util.Set currentIds = new HashSet();
+ final java.util.Set currentSaving = new IdentitySet();
for ( Object current : currentElements ) {
if ( current != null && ForeignKeys.isNotTransient( entityName, current, null, session ) ) {
- EntityEntry ee = session.getPersistenceContext().getEntry( current );
+ final EntityEntry ee = session.getPersistenceContext().getEntry( current );
if ( ee != null && ee.getStatus() == Status.SAVING ) {
currentSaving.add( current );
}
else {
- Serializable currentId = ForeignKeys.getEntityIdentifierIfNotUnsaved(
+ final Serializable currentId = ForeignKeys.getEntityIdentifierIfNotUnsaved(
entityName,
current,
session
@@ -1122,7 +1129,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
// iterate over the *old* list
for ( Object old : oldElements ) {
if ( !currentSaving.contains( old ) ) {
- Serializable oldId = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, old, session );
+ final Serializable oldId = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, old, session );
if ( !currentIds.contains( new TypedValue( idType, oldId ) ) ) {
res.add( old );
}
@@ -1132,20 +1139,28 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
return res;
}
+ /**
+ * Removes entity entries that have an equal identifier with the incoming entity instance
+ *
+ * @param list The list containing the entity instances
+ * @param entityInstance The entity instance to match elements.
+ * @param entityName The entity name
+ * @param session The session
+ */
public static void identityRemove(
Collection list,
- Object object,
+ Object entityInstance,
String entityName,
- SessionImplementor session) throws HibernateException {
+ SessionImplementor session) {
- if ( object != null && ForeignKeys.isNotTransient( entityName, object, null, session ) ) {
+ if ( entityInstance != null && ForeignKeys.isNotTransient( entityName, entityInstance, null, session ) ) {
final EntityPersister entityPersister = session.getFactory().getEntityPersister( entityName );
- Type idType = entityPersister.getIdentifierType();
+ final Type idType = entityPersister.getIdentifierType();
- Serializable idOfCurrent = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, object, session );
- Iterator itr = list.iterator();
+ final Serializable idOfCurrent = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, entityInstance, session );
+ final Iterator itr = list.iterator();
while ( itr.hasNext() ) {
- Serializable idOfOld = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, itr.next(), session );
+ final Serializable idOfOld = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, itr.next(), session );
if ( idType.isEqual( idOfCurrent, idOfOld, session.getFactory() ) ) {
itr.remove();
break;
@@ -1155,14 +1170,17 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers
}
}
+ @Override
public Object getIdentifier(Object entry, int i) {
throw new UnsupportedOperationException();
}
+ @Override
public Object getOwner() {
return owner;
}
+ @Override
public void setOwner(Object owner) {
this.owner = owner;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentArrayHolder.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentArrayHolder.java
index 9ddd1d21aa..8243f08562 100644
--- a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentArrayHolder.java
+++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentArrayHolder.java
@@ -29,6 +29,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.Iterator;
import org.jboss.logging.Logger;
@@ -48,27 +49,52 @@ import org.hibernate.type.Type;
* @author Gavin King
*/
public class PersistentArrayHolder extends AbstractPersistentCollection {
- protected Object array;
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ PersistentArrayHolder.class.getName()
+ );
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, PersistentArrayHolder.class.getName());
+ protected Object array;
//just to help out during the load (ugly, i know)
private transient Class elementClass;
private transient java.util.List tempList;
+ /**
+ * Constructs a PersistentCollection instance for holding an array.
+ *
+ * @param session The session
+ * @param array The array (the persistent "collection").
+ */
public PersistentArrayHolder(SessionImplementor session, Object array) {
- super(session);
+ super( session );
this.array = array;
setInitialized();
}
+ /**
+ * Constructs a PersistentCollection instance for holding an array.
+ *
+ * @param session The session
+ * @param persister The persister for the array
+ */
+ public PersistentArrayHolder(SessionImplementor session, CollectionPersister persister) {
+ super( session );
+ elementClass = persister.getElementClass();
+ }
+
+
+
+ @Override
public Serializable getSnapshot(CollectionPersister persister) throws HibernateException {
- int length = /*(array==null) ? tempList.size() :*/ Array.getLength(array);
- Serializable result = (Serializable) Array.newInstance( persister.getElementClass(), length );
+// final int length = (array==null) ? tempList.size() : Array.getLength( array );
+ final int length = Array.getLength( array );
+ final Serializable result = (Serializable) Array.newInstance( persister.getElementClass(), length );
for ( int i=0; i deletes = new ArrayList();
- Serializable sn = getSnapshot();
- int snSize = Array.getLength(sn);
- int arraySize = Array.getLength(array);
+ final java.util.List deletes = new ArrayList();
+ final Serializable sn = getSnapshot();
+ final int snSize = Array.getLength( sn );
+ final int arraySize = Array.getLength( array );
int end;
if ( snSize > arraySize ) {
- for ( int i=arraySize; i= Array.getLength(sn) || Array.get(sn, i)==null );
+ final Serializable sn = getSnapshot();
+ return Array.get( array, i ) != null && ( i >= Array.getLength( sn ) || Array.get( sn, i ) == null );
}
+ @Override
public boolean needsUpdating(Object entry, int i, Type elemType) throws HibernateException {
- Serializable sn = getSnapshot();
- return i semantics for a
// !
+ @Override
+ @SuppressWarnings("unchecked")
public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula) throws HibernateException {
- //if ( !persister.isOneToMany() ) throw new AssertionFailure("Not implemented for Bags");
- Type elementType = persister.getElementType();
- ArrayList deletes = new ArrayList();
- List sn = (List) getSnapshot();
- Iterator olditer = sn.iterator();
+ final Type elementType = persister.getElementType();
+ final ArrayList deletes = new ArrayList();
+ final List sn = (List) getSnapshot();
+ final Iterator olditer = sn.iterator();
int i=0;
while ( olditer.hasNext() ) {
- Object old = olditer.next();
- Iterator newiter = bag.iterator();
+ final Object old = olditer.next();
+ final Iterator newiter = bag.iterator();
boolean found = false;
- if ( bag.size()>i && elementType.isSame( old, bag.get(i++) ) ) {
+ if ( bag.size()>i && elementType.isSame( old, bag.get( i++ ) ) ) {
//a shortcut if its location didn't change!
found = true;
}
@@ -202,104 +237,91 @@ public class PersistentBag extends AbstractPersistentCollection implements List
}
}
}
- if (!found) deletes.add(old);
+ if ( !found ) {
+ deletes.add( old );
+ }
}
return deletes.iterator();
}
+ @Override
public boolean needsInserting(Object entry, int i, Type elemType) throws HibernateException {
- //if ( !persister.isOneToMany() ) throw new AssertionFailure("Not implemented for Bags");
- List sn = (List) getSnapshot();
- if ( sn.size()>i && elemType.isSame( sn.get(i), entry ) ) {
- //a shortcut if its location didn't change!
+ final List sn = (List) getSnapshot();
+ if ( sn.size() > i && elemType.isSame( sn.get( i ), entry ) ) {
+ //a shortcut if its location didn't change!
return false;
}
else {
//search for it
//note that this code is incorrect for other than one-to-many
- Iterator olditer = sn.iterator();
- while ( olditer.hasNext() ) {
- Object old = olditer.next();
- if ( elemType.isSame( old, entry ) ) return false;
+ for ( Object old : sn ) {
+ if ( elemType.isSame( old, entry ) ) {
+ return false;
+ }
}
return true;
}
}
+ @Override
public boolean isRowUpdatePossible() {
return false;
}
+ @Override
public boolean needsUpdating(Object entry, int i, Type elemType) {
- //if ( !persister.isOneToMany() ) throw new AssertionFailure("Not implemented for Bags");
return false;
}
- /**
- * @see java.util.Collection#size()
- */
+ @Override
public int size() {
return readSize() ? getCachedSize() : bag.size();
}
- /**
- * @see java.util.Collection#isEmpty()
- */
+ @Override
public boolean isEmpty() {
return readSize() ? getCachedSize()==0 : bag.isEmpty();
}
- /**
- * @see java.util.Collection#contains(Object)
- */
+ @Override
+ @SuppressWarnings("UnnecessaryUnboxing")
public boolean contains(Object object) {
- Boolean exists = readElementExistence(object);
- return exists==null ?
- bag.contains(object) :
- exists.booleanValue();
+ final Boolean exists = readElementExistence( object );
+ return exists == null ? bag.contains( object ) : exists.booleanValue();
}
- /**
- * @see java.util.Collection#iterator()
- */
+ @Override
public Iterator iterator() {
read();
return new IteratorProxy( bag.iterator() );
}
- /**
- * @see java.util.Collection#toArray()
- */
+ @Override
public Object[] toArray() {
read();
return bag.toArray();
}
- /**
- * @see java.util.Collection#toArray(Object[])
- */
+ @Override
public Object[] toArray(Object[] a) {
read();
- return bag.toArray(a);
+ return bag.toArray( a );
}
- /**
- * @see java.util.Collection#add(Object)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public boolean add(Object object) {
if ( !isOperationQueueEnabled() ) {
write();
- return bag.add(object);
+ return bag.add( object );
}
else {
- queueOperation( new SimpleAdd(object) );
+ queueOperation( new SimpleAdd( object ) );
return true;
}
}
- /**
- * @see java.util.Collection#remove(Object)
- */
+ @Override
public boolean remove(Object o) {
initialize( true );
if ( bag.remove( o ) ) {
@@ -311,35 +333,33 @@ public class PersistentBag extends AbstractPersistentCollection implements List
}
}
- /**
- * @see java.util.Collection#containsAll(Collection)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public boolean containsAll(Collection c) {
read();
- return bag.containsAll(c);
+ return bag.containsAll( c );
}
- /**
- * @see java.util.Collection#addAll(Collection)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public boolean addAll(Collection values) {
- if ( values.size()==0 ) return false;
+ if ( values.size()==0 ) {
+ return false;
+ }
if ( !isOperationQueueEnabled() ) {
write();
- return bag.addAll(values);
+ return bag.addAll( values );
}
else {
- Iterator iter = values.iterator();
- while ( iter.hasNext() ) {
- queueOperation( new SimpleAdd( iter.next() ) );
+ for ( Object value : values ) {
+ queueOperation( new SimpleAdd( value ) );
}
return values.size()>0;
}
}
- /**
- * @see java.util.Collection#removeAll(Collection)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public boolean removeAll(Collection c) {
if ( c.size()>0 ) {
initialize( true );
@@ -356,9 +376,8 @@ public class PersistentBag extends AbstractPersistentCollection implements List
}
}
- /**
- * @see java.util.Collection#retainAll(Collection)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public boolean retainAll(Collection c) {
initialize( true );
if ( bag.retainAll( c ) ) {
@@ -370,9 +389,8 @@ public class PersistentBag extends AbstractPersistentCollection implements List
}
}
- /**
- * @see java.util.Collection#clear()
- */
+ @Override
+ @SuppressWarnings("unchecked")
public void clear() {
if ( isClearQueueEnabled() ) {
queueOperation( new Clear() );
@@ -386,160 +404,161 @@ public class PersistentBag extends AbstractPersistentCollection implements List
}
}
+ @Override
public Object getIndex(Object entry, int i, CollectionPersister persister) {
throw new UnsupportedOperationException("Bags don't have indexes");
}
+ @Override
public Object getElement(Object entry) {
return entry;
}
+ @Override
public Object getSnapshotElement(Object entry, int i) {
- List sn = (List) getSnapshot();
- return sn.get(i);
+ final List sn = (List) getSnapshot();
+ return sn.get( i );
}
+ /**
+ * Count how many times the given object occurs in the elements
+ *
+ * @param o The object to check
+ *
+ * @return The number of occurences.
+ */
+ @SuppressWarnings("UnusedDeclaration")
public int occurrences(Object o) {
read();
- Iterator iter = bag.iterator();
- int result=0;
- while ( iter.hasNext() ) {
- if ( o.equals( iter.next() ) ) result++;
+ final Iterator itr = bag.iterator();
+ int result = 0;
+ while ( itr.hasNext() ) {
+ if ( o.equals( itr.next() ) ) {
+ result++;
+ }
}
return result;
}
// List OPERATIONS:
- /**
- * @see java.util.List#add(int, Object)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public void add(int i, Object o) {
write();
- bag.add(i, o);
+ bag.add( i, o );
}
- /**
- * @see java.util.List#addAll(int, Collection)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public boolean addAll(int i, Collection c) {
- if ( c.size()>0 ) {
+ if ( c.size() > 0 ) {
write();
- return bag.addAll(i, c);
+ return bag.addAll( i, c );
}
else {
return false;
}
}
- /**
- * @see java.util.List#get(int)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public Object get(int i) {
read();
- return bag.get(i);
+ return bag.get( i );
}
- /**
- * @see java.util.List#indexOf(Object)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public int indexOf(Object o) {
read();
- return bag.indexOf(o);
+ return bag.indexOf( o );
}
- /**
- * @see java.util.List#lastIndexOf(Object)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public int lastIndexOf(Object o) {
read();
- return bag.lastIndexOf(o);
+ return bag.lastIndexOf( o );
}
- /**
- * @see java.util.List#listIterator()
- */
+ @Override
+ @SuppressWarnings("unchecked")
public ListIterator listIterator() {
read();
return new ListIteratorProxy( bag.listIterator() );
}
- /**
- * @see java.util.List#listIterator(int)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public ListIterator listIterator(int i) {
read();
- return new ListIteratorProxy( bag.listIterator(i) );
+ return new ListIteratorProxy( bag.listIterator( i ) );
}
- /**
- * @see java.util.List#remove(int)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public Object remove(int i) {
write();
- return bag.remove(i);
+ return bag.remove( i );
}
- /**
- * @see java.util.List#set(int, Object)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public Object set(int i, Object o) {
write();
- return bag.set(i, o);
+ return bag.set( i, o );
}
- /**
- * @see java.util.List#subList(int, int)
- */
+ @Override
+ @SuppressWarnings("unchecked")
public List subList(int start, int end) {
read();
- return new ListProxy( bag.subList(start, end) );
+ return new ListProxy( bag.subList( start, end ) );
}
+ @Override
+ public boolean entryExists(Object entry, int i) {
+ return entry!=null;
+ }
+
+ @Override
public String toString() {
read();
return bag.toString();
}
- /*public boolean equals(Object other) {
- read();
- return bag.equals(other);
- }
-
- public int hashCode(Object other) {
- read();
- return bag.hashCode();
- }*/
-
- public boolean entryExists(Object entry, int i) {
- return entry!=null;
- }
-
/**
* Bag does not respect the collection API and do an
* JVM instance comparison to do the equals.
* The semantic is broken not to have to initialize a
* collection for a simple equals() operation.
* @see java.lang.Object#equals(java.lang.Object)
+ *
+ * {@inheritDoc}
*/
+ @Override
public boolean equals(Object obj) {
- return super.equals(obj);
+ return super.equals( obj );
}
- /**
- * @see java.lang.Object#hashCode()
- */
+ @Override
public int hashCode() {
return super.hashCode();
}
final class Clear implements DelayedOperation {
+ @Override
public void operate() {
bag.clear();
}
+
+ @Override
public Object getAddedInstance() {
return null;
}
+
+ @Override
public Object getOrphan() {
throw new UnsupportedOperationException("queued clear cannot be used with orphan delete");
}
@@ -551,12 +570,19 @@ public class PersistentBag extends AbstractPersistentCollection implements List
public SimpleAdd(Object value) {
this.value = value;
}
+
+ @Override
+ @SuppressWarnings("unchecked")
public void operate() {
- bag.add(value);
+ bag.add( value );
}
+
+ @Override
public Object getAddedInstance() {
return value;
}
+
+ @Override
public Object getOrphan() {
return null;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIdentifierBag.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIdentifierBag.java
index beac3d457b..bacd39429f 100644
--- a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIdentifierBag.java
+++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIdentifierBag.java
@@ -53,37 +53,53 @@ import org.hibernate.type.Type;
* @author Gavin King
*/
public class PersistentIdentifierBag extends AbstractPersistentCollection implements List {
+ protected List
+ *
* IMPL NOTE: There is meant to be a one-to-one correspondence between a {@link org.hibernate.internal.SessionImpl}
* and a PersistentContext. Event listeners and other Session collaborators then use the PersistentContext to drive
* their processing.
@@ -90,14 +89,13 @@ import org.hibernate.type.CollectionType;
* @author Steve Ebersole
*/
public class StatefulPersistenceContext implements PersistenceContext {
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ StatefulPersistenceContext.class.getName()
+ );
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, StatefulPersistenceContext.class.getName() );
-
- private static final boolean tracing = LOG.isTraceEnabled();
-
- public static final Object NO_ROW = new MarkerObject( "NO_ROW" );
-
- public static final int INIT_COLL_SIZE = 8;
+ private static final boolean TRACE_ENABLED = LOG.isTraceEnabled();
+ private static final int INIT_COLL_SIZE = 8;
private SessionImplementor session;
@@ -144,12 +142,12 @@ public class StatefulPersistenceContext implements PersistenceContext {
// May be empty or not contains all relation
private Map parentsByChild;
- private int cascading = 0;
- private int loadCounter = 0;
- private boolean flushing = false;
+ private int cascading;
+ private int loadCounter;
+ private boolean flushing;
- private boolean defaultReadOnly = false;
- private boolean hasNonReadOnlyEntities = false;
+ private boolean defaultReadOnly;
+ private boolean hasNonReadOnlyEntities;
private LoadContexts loadContexts;
private BatchFetchQueue batchFetchQueue;
@@ -280,8 +278,8 @@ public class StatefulPersistenceContext implements PersistenceContext {
@Override
public void setEntryStatus(EntityEntry entry, Status status) {
- entry.setStatus(status);
- setHasNonReadOnlyEnties(status);
+ entry.setStatus( status );
+ setHasNonReadOnlyEnties( status );
}
private void setHasNonReadOnlyEnties(Status status) {
@@ -303,25 +301,25 @@ public class StatefulPersistenceContext implements PersistenceContext {
/**
* Get the current state of the entity as known to the underlying
* database, or null if there is no corresponding row
+ *
+ * {@inheritDoc}
*/
@Override
- public Object[] getDatabaseSnapshot(Serializable id, EntityPersister persister)
- throws HibernateException {
+ public Object[] getDatabaseSnapshot(Serializable id, EntityPersister persister) throws HibernateException {
final EntityKey key = session.generateEntityKey( id, persister );
- Object cached = entitySnapshotsByKey.get(key);
- if (cached!=null) {
- return cached==NO_ROW ? null : (Object[]) cached;
+ final Object cached = entitySnapshotsByKey.get( key );
+ if ( cached != null ) {
+ return cached == NO_ROW ? null : (Object[]) cached;
}
else {
- Object[] snapshot = persister.getDatabaseSnapshot( id, session );
- entitySnapshotsByKey.put( key, snapshot==null ? NO_ROW : snapshot );
+ final Object[] snapshot = persister.getDatabaseSnapshot( id, session );
+ entitySnapshotsByKey.put( key, snapshot == null ? NO_ROW : snapshot );
return snapshot;
}
}
@Override
- public Object[] getNaturalIdSnapshot(Serializable id, EntityPersister persister)
- throws HibernateException {
+ public Object[] getNaturalIdSnapshot(Serializable id, EntityPersister persister) throws HibernateException {
if ( !persister.hasNaturalIdentifier() ) {
return null;
}
@@ -350,7 +348,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
// snapshot-cached.
final int[] props = persister.getNaturalIdentifierProperties();
final Object[] entitySnapshot = getDatabaseSnapshot( id, persister );
- if ( entitySnapshot == NO_ROW ) {
+ if ( entitySnapshot == NO_ROW || entitySnapshot == null ) {
return null;
}
@@ -371,124 +369,82 @@ public class StatefulPersistenceContext implements PersistenceContext {
return session.getFactory().getEntityPersister( persister.getRootEntityName() );
}
- /**
- * Retrieve the cached database snapshot for the requested entity key.
- *
- * This differs from {@link #getDatabaseSnapshot} is two important respects:
- *
no snapshot is obtained from the database if not already cached
- *
an entry of {@link #NO_ROW} here is interpretet as an exception
- *
- * @param key The entity key for which to retrieve the cached snapshot
- * @return The cached snapshot
- * @throws IllegalStateException if the cached snapshot was == {@link #NO_ROW}.
- */
@Override
public Object[] getCachedDatabaseSnapshot(EntityKey key) {
- Object snapshot = entitySnapshotsByKey.get( key );
+ final Object snapshot = entitySnapshotsByKey.get( key );
if ( snapshot == NO_ROW ) {
- throw new IllegalStateException( "persistence context reported no row snapshot for " + MessageHelper.infoString( key.getEntityName(), key.getIdentifier() ) );
+ throw new IllegalStateException(
+ "persistence context reported no row snapshot for "
+ + MessageHelper.infoString( key.getEntityName(), key.getIdentifier() )
+ );
}
- return ( Object[] ) snapshot;
+ return (Object[]) snapshot;
}
@Override
public void addEntity(EntityKey key, Object entity) {
- entitiesByKey.put(key, entity);
- getBatchFetchQueue().removeBatchLoadableEntityKey(key);
+ entitiesByKey.put( key, entity );
+ getBatchFetchQueue().removeBatchLoadableEntityKey( key );
}
- /**
- * Get the entity instance associated with the given
- * EntityKey
- */
@Override
public Object getEntity(EntityKey key) {
- return entitiesByKey.get(key);
+ return entitiesByKey.get( key );
}
@Override
public boolean containsEntity(EntityKey key) {
- return entitiesByKey.containsKey(key);
+ return entitiesByKey.containsKey( key );
}
- /**
- * Remove an entity from the session cache, also clear
- * up other state associated with the entity, all except
- * for the EntityEntry
- */
@Override
public Object removeEntity(EntityKey key) {
- Object entity = entitiesByKey.remove(key);
- Iterator iter = entitiesByUniqueKey.values().iterator();
- while ( iter.hasNext() ) {
- if ( iter.next()==entity ) iter.remove();
+ final Object entity = entitiesByKey.remove( key );
+ final Iterator itr = entitiesByUniqueKey.values().iterator();
+ while ( itr.hasNext() ) {
+ if ( itr.next() == entity ) {
+ itr.remove();
+ }
}
// Clear all parent cache
parentsByChild.clear();
- entitySnapshotsByKey.remove(key);
- nullifiableEntityKeys.remove(key);
- getBatchFetchQueue().removeBatchLoadableEntityKey(key);
- getBatchFetchQueue().removeSubselect(key);
+ entitySnapshotsByKey.remove( key );
+ nullifiableEntityKeys.remove( key );
+ getBatchFetchQueue().removeBatchLoadableEntityKey( key );
+ getBatchFetchQueue().removeSubselect( key );
return entity;
}
- /**
- * Get an entity cached by unique key
- */
@Override
public Object getEntity(EntityUniqueKey euk) {
- return entitiesByUniqueKey.get(euk);
+ return entitiesByUniqueKey.get( euk );
}
- /**
- * Add an entity to the cache by unique key
- */
@Override
public void addEntity(EntityUniqueKey euk, Object entity) {
- entitiesByUniqueKey.put(euk, entity);
+ entitiesByUniqueKey.put( euk, entity );
}
- /**
- * Retrieve the EntityEntry representation of the given entity.
- *
- * @param entity The entity for which to locate the EntityEntry.
- * @return The EntityEntry for the given entity.
- */
@Override
public EntityEntry getEntry(Object entity) {
return entityEntryContext.getEntityEntry( entity );
-// return entityEntries.get(entity);
}
- /**
- * Remove an entity entry from the session cache
- */
@Override
public EntityEntry removeEntry(Object entity) {
return entityEntryContext.removeEntityEntry( entity );
-// return entityEntries.remove(entity);
}
- /**
- * Is there an EntityEntry for this instance?
- */
@Override
public boolean isEntryFor(Object entity) {
return entityEntryContext.hasEntityEntry( entity );
-// return entityEntries.containsKey(entity);
}
- /**
- * Get the collection entry for a persistent collection
- */
@Override
public CollectionEntry getCollectionEntry(PersistentCollection coll) {
- return collectionEntries.get(coll);
+ return collectionEntries.get( coll );
}
- /**
- * Adds an entity to the internal caches.
- */
@Override
public EntityEntry addEntity(
final Object entity,
@@ -517,11 +473,6 @@ public class StatefulPersistenceContext implements PersistenceContext {
);
}
-
- /**
- * Generates an appropriate EntityEntry instance and adds it
- * to the event source's internal caches.
- */
@Override
public EntityEntry addEntry(
final Object entity,
@@ -536,7 +487,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
final boolean disableVersionIncrement,
boolean lazyPropertiesAreUnfetched) {
- EntityEntry e = new EntityEntry(
+ final EntityEntry e = new EntityEntry(
status,
loadedState,
rowId,
@@ -555,13 +506,13 @@ public class StatefulPersistenceContext implements PersistenceContext {
entityEntryContext.addEntityEntry( entity, e );
// entityEntries.put(entity, e);
- setHasNonReadOnlyEnties(status);
+ setHasNonReadOnlyEnties( status );
return e;
}
@Override
public boolean containsCollection(PersistentCollection collection) {
- return collectionEntries.containsKey(collection);
+ return collectionEntries.containsKey( collection );
}
@Override
@@ -569,23 +520,16 @@ public class StatefulPersistenceContext implements PersistenceContext {
return proxiesByKey.containsValue( entity );
}
- /**
- * Takes the given object and, if it represents a proxy, reassociates it with this event source.
- *
- * @param value The possible proxy to be reassociated.
- * @return Whether the passed value represented an actual proxy which got initialized.
- * @throws MappingException
- */
@Override
public boolean reassociateIfUninitializedProxy(Object value) throws MappingException {
if ( value instanceof ElementWrapper ) {
value = ( (ElementWrapper) value ).getElement();
}
- if ( !Hibernate.isInitialized(value) ) {
- HibernateProxy proxy = (HibernateProxy) value;
- LazyInitializer li = proxy.getHibernateLazyInitializer();
- reassociateProxy(li, proxy);
+ if ( !Hibernate.isInitialized( value ) ) {
+ final HibernateProxy proxy = (HibernateProxy) value;
+ final LazyInitializer li = proxy.getHibernateLazyInitializer();
+ reassociateProxy( li, proxy );
return true;
}
else {
@@ -593,10 +537,6 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
}
- /**
- * If a deleted entity instance is re-saved, and it has a proxy, we need to
- * reset the identifier of the proxy
- */
@Override
public void reassociateProxy(Object value, Serializable id) throws MappingException {
if ( value instanceof ElementWrapper ) {
@@ -605,10 +545,10 @@ public class StatefulPersistenceContext implements PersistenceContext {
if ( value instanceof HibernateProxy ) {
LOG.debugf( "Setting proxy identifier: %s", id );
- HibernateProxy proxy = (HibernateProxy) value;
- LazyInitializer li = proxy.getHibernateLazyInitializer();
- li.setIdentifier(id);
- reassociateProxy(li, proxy);
+ final HibernateProxy proxy = (HibernateProxy) value;
+ final LazyInitializer li = proxy.getHibernateLazyInitializer();
+ li.setIdentifier( id );
+ reassociateProxy( li, proxy );
}
}
@@ -630,11 +570,6 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
}
- /**
- * Get the entity instance underlying the given proxy, throwing
- * an exception if the proxy is uninitialized. If the given object
- * is not a proxy, simply return the argument.
- */
@Override
public Object unproxy(Object maybeProxy) throws HibernateException {
if ( maybeProxy instanceof ElementWrapper ) {
@@ -642,28 +577,21 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
if ( maybeProxy instanceof HibernateProxy ) {
- HibernateProxy proxy = (HibernateProxy) maybeProxy;
- LazyInitializer li = proxy.getHibernateLazyInitializer();
+ final HibernateProxy proxy = (HibernateProxy) maybeProxy;
+ final LazyInitializer li = proxy.getHibernateLazyInitializer();
if ( li.isUninitialized() ) {
throw new PersistentObjectException(
- "object was an uninitialized proxy for " +
- li.getEntityName()
+ "object was an uninitialized proxy for " + li.getEntityName()
);
}
- return li.getImplementation(); //unwrap the object
+ //unwrap the object and return
+ return li.getImplementation();
}
else {
return maybeProxy;
}
}
- /**
- * Possibly unproxy the given reference and reassociate it with the current session.
- *
- * @param maybeProxy The reference to be unproxied if it currently represents a proxy.
- * @return The unproxied instance.
- * @throws HibernateException
- */
@Override
public Object unproxyAndReassociate(Object maybeProxy) throws HibernateException {
if ( maybeProxy instanceof ElementWrapper ) {
@@ -671,25 +599,20 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
if ( maybeProxy instanceof HibernateProxy ) {
- HibernateProxy proxy = (HibernateProxy) maybeProxy;
- LazyInitializer li = proxy.getHibernateLazyInitializer();
- reassociateProxy(li, proxy);
- return li.getImplementation(); //initialize + unwrap the object
+ final HibernateProxy proxy = (HibernateProxy) maybeProxy;
+ final LazyInitializer li = proxy.getHibernateLazyInitializer();
+ reassociateProxy( li, proxy );
+ //initialize + unwrap the object and return it
+ return li.getImplementation();
}
else {
return maybeProxy;
}
}
- /**
- * Attempts to check whether the given key represents an entity already loaded within the
- * current session.
- * @param object The entity reference against which to perform the uniqueness check.
- * @throws HibernateException
- */
@Override
public void checkUniqueness(EntityKey key, Object object) throws HibernateException {
- Object entity = getEntity(key);
+ final Object entity = getEntity( key );
if ( entity == object ) {
throw new AssertionFailure( "object already associated, but no entry was found" );
}
@@ -698,36 +621,26 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
}
- /**
- * If the existing proxy is insufficiently "narrow" (derived), instantiate a new proxy
- * and overwrite the registration of the old one. This breaks == and occurs only for
- * "class" proxies rather than "interface" proxies. Also init the proxy to point to
- * the given target implementation if necessary.
- *
- * @param proxy The proxy instance to be narrowed.
- * @param persister The persister for the proxied entity.
- * @param key The internal cache key for the proxied entity.
- * @param object (optional) the actual proxied entity instance.
- * @return An appropriately narrowed instance.
- * @throws HibernateException
- */
@Override
+ @SuppressWarnings("unchecked")
public Object narrowProxy(Object proxy, EntityPersister persister, EntityKey key, Object object)
throws HibernateException {
final Class concreteProxyClass = persister.getConcreteProxyClass();
- boolean alreadyNarrow = concreteProxyClass.isAssignableFrom( proxy.getClass() );
+ final boolean alreadyNarrow = concreteProxyClass.isAssignableFrom( proxy.getClass() );
if ( !alreadyNarrow ) {
LOG.narrowingProxy( concreteProxyClass );
if ( object != null ) {
- proxiesByKey.remove(key);
- return object; //return the proxied object
+ proxiesByKey.remove( key );
+ //return the proxied object
+ return object;
}
else {
proxy = persister.createProxy( key.getIdentifier(), session );
- Object proxyOrig = proxiesByKey.put(key, proxy); //overwrite old proxy
+ //overwrite old proxy
+ final Object proxyOrig = proxiesByKey.put( key, proxy );
if ( proxyOrig != null ) {
if ( ! ( proxyOrig instanceof HibernateProxy ) ) {
throw new AssertionFailure(
@@ -735,8 +648,8 @@ public class StatefulPersistenceContext implements PersistenceContext {
);
}
// set the read-only/modifiable mode in the new proxy to what it was in the original proxy
- boolean readOnlyOrig = ( ( HibernateProxy ) proxyOrig ).getHibernateLazyInitializer().isReadOnly();
- ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().setReadOnly( readOnlyOrig );
+ final boolean readOnlyOrig = ( (HibernateProxy) proxyOrig ).getHibernateLazyInitializer().isReadOnly();
+ ( (HibernateProxy) proxy ).getHibernateLazyInitializer().setReadOnly( readOnlyOrig );
}
return proxy;
}
@@ -744,45 +657,28 @@ public class StatefulPersistenceContext implements PersistenceContext {
else {
if ( object != null ) {
- LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer();
- li.setImplementation(object);
+ final LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer();
+ li.setImplementation( object );
}
-
return proxy;
-
}
-
}
- /**
- * Return the existing proxy associated with the given EntityKey, or the
- * third argument (the entity associated with the key) if no proxy exists. Init
- * the proxy to the target implementation, if necessary.
- */
@Override
- public Object proxyFor(EntityPersister persister, EntityKey key, Object impl)
- throws HibernateException {
+ public Object proxyFor(EntityPersister persister, EntityKey key, Object impl) throws HibernateException {
if ( !persister.hasProxy() ) {
return impl;
}
- Object proxy = proxiesByKey.get( key );
+ final Object proxy = proxiesByKey.get( key );
return ( proxy != null ) ? narrowProxy( proxy, persister, key, impl ) : impl;
}
- /**
- * Return the existing proxy associated with the given EntityKey, or the
- * argument (the entity associated with the key) if no proxy exists.
- * (slower than the form above)
- */
@Override
public Object proxyFor(Object impl) throws HibernateException {
- EntityEntry e = getEntry(impl);
+ final EntityEntry e = getEntry( impl );
return proxyFor( e.getPersister(), e.getEntityKey(), impl );
}
- /**
- * Get the entity that owns this persistent collection
- */
@Override
public Object getCollectionOwner(Serializable key, CollectionPersister collectionPersister) throws MappingException {
// todo : we really just need to add a split in the notions of:
@@ -811,7 +707,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
// find the corresponding owner instance
// a) try by EntityUniqueKey
if ( collectionType.getLHSPropertyName() != null ) {
- Object owner = getEntity(
+ final Object owner = getEntity(
new EntityUniqueKey(
ownerPersister.getEntityName(),
collectionType.getLHSPropertyName(),
@@ -846,35 +742,23 @@ public class StatefulPersistenceContext implements PersistenceContext {
return getEntity( session.generateEntityKey( key, collectionPersister.getOwnerEntityPersister() ) );
}
- /**
- * Get the entity that owned this persistent collection when it was loaded
- *
- * @param collection The persistent collection
- * @return the owner, if its entity ID is available from the collection's loaded key
- * and the owner entity is in the persistence context; otherwise, returns null
- */
@Override
public Object getLoadedCollectionOwnerOrNull(PersistentCollection collection) {
- CollectionEntry ce = getCollectionEntry( collection );
+ final CollectionEntry ce = getCollectionEntry( collection );
if ( ce.getLoadedPersister() == null ) {
- return null; // early exit...
+ return null;
}
+
Object loadedOwner = null;
// TODO: an alternative is to check if the owner has changed; if it hasn't then
// return collection.getOwner()
- Serializable entityId = getLoadedCollectionOwnerIdOrNull( ce );
+ final Serializable entityId = getLoadedCollectionOwnerIdOrNull( ce );
if ( entityId != null ) {
loadedOwner = getCollectionOwner( entityId, ce.getLoadedPersister() );
}
return loadedOwner;
}
- /**
- * Get the ID for the entity that owned this persistent collection when it was loaded
- *
- * @param collection The persistent collection
- * @return the owner ID if available from the collection's loaded key; otherwise, returns null
- */
@Override
public Serializable getLoadedCollectionOwnerIdOrNull(PersistentCollection collection) {
return getLoadedCollectionOwnerIdOrNull( getCollectionEntry( collection ) );
@@ -895,39 +779,28 @@ public class StatefulPersistenceContext implements PersistenceContext {
return ce.getLoadedPersister().getCollectionType().getIdOfOwnerOrNull( ce.getLoadedKey(), session );
}
- /**
- * add a collection we just loaded up (still needs initializing)
- */
@Override
public void addUninitializedCollection(CollectionPersister persister, PersistentCollection collection, Serializable id) {
- CollectionEntry ce = new CollectionEntry(collection, persister, id, flushing);
- addCollection(collection, ce, id);
+ final CollectionEntry ce = new CollectionEntry( collection, persister, id, flushing );
+ addCollection( collection, ce, id );
if ( persister.getBatchSize() > 1 ) {
getBatchFetchQueue().addBatchLoadableCollection( collection, ce );
}
}
- /**
- * add a detached uninitialized collection
- */
@Override
public void addUninitializedDetachedCollection(CollectionPersister persister, PersistentCollection collection) {
- CollectionEntry ce = new CollectionEntry( persister, collection.getKey() );
+ final CollectionEntry ce = new CollectionEntry( persister, collection.getKey() );
addCollection( collection, ce, collection.getKey() );
if ( persister.getBatchSize() > 1 ) {
getBatchFetchQueue().addBatchLoadableCollection( collection, ce );
}
}
- /**
- * Add a new collection (ie. a newly created one, just instantiated by the
- * application, with no database state or snapshot)
- * @param collection The collection to be associated with the persistence context
- */
@Override
public void addNewCollection(CollectionPersister persister, PersistentCollection collection)
- throws HibernateException {
- addCollection(collection, persister);
+ throws HibernateException {
+ addCollection( collection, persister );
}
/**
@@ -939,11 +812,11 @@ public class StatefulPersistenceContext implements PersistenceContext {
*/
private void addCollection(PersistentCollection coll, CollectionEntry entry, Serializable key) {
collectionEntries.put( coll, entry );
- CollectionKey collectionKey = new CollectionKey( entry.getLoadedPersister(), key );
- PersistentCollection old = collectionsByKey.put( collectionKey, coll );
+ final CollectionKey collectionKey = new CollectionKey( entry.getLoadedPersister(), key );
+ final PersistentCollection old = collectionsByKey.put( collectionKey, coll );
if ( old != null ) {
if ( old == coll ) {
- throw new AssertionFailure("bug adding collection twice");
+ throw new AssertionFailure( "bug adding collection twice" );
}
// or should it actually throw an exception?
old.unsetSession( session );
@@ -960,36 +833,29 @@ public class StatefulPersistenceContext implements PersistenceContext {
* @param persister The collection persister
*/
private void addCollection(PersistentCollection collection, CollectionPersister persister) {
- CollectionEntry ce = new CollectionEntry( persister, collection );
+ final CollectionEntry ce = new CollectionEntry( persister, collection );
collectionEntries.put( collection, ce );
}
- /**
- * add an (initialized) collection that was created by another session and passed
- * into update() (ie. one with a snapshot and existing state on the database)
- */
@Override
public void addInitializedDetachedCollection(CollectionPersister collectionPersister, PersistentCollection collection)
- throws HibernateException {
+ throws HibernateException {
if ( collection.isUnreferenced() ) {
//treat it just like a new collection
addCollection( collection, collectionPersister );
}
else {
- CollectionEntry ce = new CollectionEntry( collection, session.getFactory() );
+ final CollectionEntry ce = new CollectionEntry( collection, session.getFactory() );
addCollection( collection, ce, collection.getKey() );
}
}
- /**
- * add a collection we just pulled out of the cache (does not need initializing)
- */
@Override
public CollectionEntry addInitializedCollection(CollectionPersister persister, PersistentCollection collection, Serializable id)
- throws HibernateException {
- CollectionEntry ce = new CollectionEntry(collection, persister, id, flushing);
- ce.postInitialize(collection);
- addCollection(collection, ce, id);
+ throws HibernateException {
+ final CollectionEntry ce = new CollectionEntry( collection, persister, id, flushing );
+ ce.postInitialize( collection );
+ addCollection( collection, ce, id );
return ce;
}
@@ -1001,28 +867,21 @@ public class StatefulPersistenceContext implements PersistenceContext {
return collectionsByKey.get( collectionKey );
}
- /**
- * Register a collection for non-lazy loading at the end of the
- * two-phase load
- */
@Override
public void addNonLazyCollection(PersistentCollection collection) {
- nonlazyCollections.add(collection);
+ nonlazyCollections.add( collection );
}
- /**
- * Force initialization of all non-lazy collections encountered during
- * the current two-phase load (actually, this is a no-op, unless this
- * is the "outermost" load)
- */
@Override
public void initializeNonLazyCollections() throws HibernateException {
if ( loadCounter == 0 ) {
- if (tracing)
- LOG.trace( "Initializing non-lazy collections" );
+ if ( TRACE_ENABLED ) {
+ LOG.trace( "Initializing non-lazy collections" );
+ }
//do this work only at the very highest level of the load
- loadCounter++; //don't let this method be called recursively
+ //don't let this method be called recursively
+ loadCounter++;
try {
int size;
while ( ( size = nonlazyCollections.size() ) > 0 ) {
@@ -1037,20 +896,11 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
}
-
- /**
- * Get the PersistentCollection object for an array
- */
@Override
public PersistentCollection getCollectionHolder(Object array) {
- return arrayHolders.get(array);
+ return arrayHolders.get( array );
}
- /**
- * Register a PersistentCollection object for an array.
- * Associates a holder with an array - MUST be called after loading
- * array, since the array instance is not created until endLoad().
- */
@Override
public void addCollectionHolder(PersistentCollection holder) {
//TODO:refactor + make this method private
@@ -1059,22 +909,14 @@ public class StatefulPersistenceContext implements PersistenceContext {
@Override
public PersistentCollection removeCollectionHolder(Object array) {
- return arrayHolders.remove(array);
+ return arrayHolders.remove( array );
}
- /**
- * Get the snapshot of the pre-flush collection state
- */
@Override
public Serializable getSnapshot(PersistentCollection coll) {
- return getCollectionEntry(coll).getSnapshot();
+ return getCollectionEntry( coll ).getSnapshot();
}
- /**
- * Get the collection entry for a collection passed to filter,
- * which might be a collection wrapper, an array, or an unwrapped
- * collection. Return null if there is no entry.
- */
@Override
public CollectionEntry getCollectionEntryOrNull(Object collection) {
PersistentCollection coll;
@@ -1083,14 +925,14 @@ public class StatefulPersistenceContext implements PersistenceContext {
//if (collection==null) throw new TransientObjectException("Collection was not yet persistent");
}
else {
- coll = getCollectionHolder(collection);
+ coll = getCollectionHolder( collection );
if ( coll == null ) {
//it might be an unwrapped collection reference!
//try to find a wrapper (slowish)
- Iterator wrappers = collectionEntries.keyIterator();
+ final Iterator wrappers = collectionEntries.keyIterator();
while ( wrappers.hasNext() ) {
- PersistentCollection pc = wrappers.next();
- if ( pc.isWrapper(collection) ) {
+ final PersistentCollection pc = wrappers.next();
+ if ( pc.isWrapper( collection ) ) {
coll = pc;
break;
}
@@ -1098,34 +940,19 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
}
- return (coll == null) ? null : getCollectionEntry(coll);
+ return (coll == null) ? null : getCollectionEntry( coll );
}
- /**
- * Get an existing proxy by key
- */
@Override
public Object getProxy(EntityKey key) {
- return proxiesByKey.get(key);
+ return proxiesByKey.get( key );
}
- /**
- * Add a proxy to the session cache
- */
@Override
public void addProxy(EntityKey key, Object proxy) {
- proxiesByKey.put(key, proxy);
+ proxiesByKey.put( key, proxy );
}
- /**
- * Remove a proxy from the session cache.
- *
- * Additionally, ensure that any load optimization references
- * such as batch or subselect loading get cleaned up as well.
- *
- * @param key The key of the entity proxy to be removed
- * @return The proxy reference.
- */
@Override
public Object removeProxy(EntityKey key) {
if ( batchFetchQueue != null ) {
@@ -1135,9 +962,6 @@ public class StatefulPersistenceContext implements PersistenceContext {
return proxiesByKey.remove( key );
}
- /**
- * Retrieve the set of EntityKeys representing nullifiable references
- */
@Override
public HashSet getNullifiableEntityKeys() {
return nullifiableEntityKeys;
@@ -1222,20 +1046,10 @@ public class StatefulPersistenceContext implements PersistenceContext {
return loadCounter == 0;
}
- /**
- * Returns a string representation of the object.
- *
- * @return a string representation of the object.
- */
@Override
- public String toString() {
- return new StringBuilder()
- .append("PersistenceContext[entityKeys=")
- .append(entitiesByKey.keySet())
- .append(",collectionKeys=")
- .append(collectionsByKey.keySet())
- .append("]")
- .toString();
+ public String toString() {
+ return "PersistenceContext[entityKeys=" + entitiesByKey.keySet()
+ + ",collectionKeys=" + collectionsByKey.keySet() + "]";
}
@Override
@@ -1243,27 +1057,6 @@ public class StatefulPersistenceContext implements PersistenceContext {
return entityEntryContext.reentrantSafeEntityEntries();
}
- /**
- * Search this persistence context for an associated entity instance which is considered the "owner" of
- * the given childEntity, and return that owner's id value. This is performed in the scenario of a
- * uni-directional, non-inverse one-to-many collection (which means that the collection elements do not maintain
- * a direct reference to the owner).
- *
- * As such, the processing here is basically to loop over every entity currently associated with this persistence
- * context and for those of the correct entity (sub) type to extract its collection role property value and see
- * if the child is contained within that collection. If so, we have found the owner; if not, we go on.
- *
- * Also need to account for mergeMap which acts as a local copy cache managed for the duration of a merge
- * operation. It represents a map of the detached entity instances pointing to the corresponding managed instance.
- *
- * @param entityName The entity name for the entity type which would own the child
- * @param propertyName The name of the property on the owning entity type which would name this child association.
- * @param childEntity The child entity instance for which to locate the owner instance id.
- * @param mergeMap A map of non-persistent instances from an on-going merge operation (possibly null).
- *
- * @return The id of the entityName instance which is said to own the child; null if an appropriate owner not
- * located.
- */
@Override
public Serializable getOwnerId(String entityName, String propertyName, Object childEntity, Map mergeMap) {
final String collectionRole = entityName + '.' + propertyName;
@@ -1271,24 +1064,23 @@ public class StatefulPersistenceContext implements PersistenceContext {
final CollectionPersister collectionPersister = session.getFactory().getCollectionPersister( collectionRole );
// try cache lookup first
- Object parent = parentsByChild.get( childEntity );
+ final Object parent = parentsByChild.get( childEntity );
if ( parent != null ) {
final EntityEntry entityEntry = entityEntryContext.getEntityEntry( parent );
-// final EntityEntry entityEntry = entityEntries.get( parent );
//there maybe more than one parent, filter by type
- if ( persister.isSubclassEntityName(entityEntry.getEntityName() )
+ if ( persister.isSubclassEntityName( entityEntry.getEntityName() )
&& isFoundInParent( propertyName, childEntity, persister, collectionPersister, parent ) ) {
return getEntry( parent ).getId();
}
else {
- parentsByChild.remove( childEntity ); // remove wrong entry
+ // remove wrong entry
+ parentsByChild.remove( childEntity );
}
}
//not found in case, proceed
// iterate all the entities currently associated with the persistence context.
for ( Entry me : reentrantSafeEntityEntries() ) {
-// for ( Entry me : IdentityMap.concurrentEntries( entityEntries ) ) {
final EntityEntry entityEntry = me.getValue();
// does this entity entry pertain to the entity persister in which we are interested (owner)?
if ( persister.isSubclassEntityName( entityEntry.getEntityName() ) ) {
@@ -1305,8 +1097,8 @@ public class StatefulPersistenceContext implements PersistenceContext {
if ( !found && mergeMap != null ) {
//check if the detached object being merged is the parent
- Object unmergedInstance = mergeMap.get( entityEntryInstance );
- Object unmergedChild = mergeMap.get( childEntity );
+ final Object unmergedInstance = mergeMap.get( entityEntryInstance );
+ final Object unmergedChild = mergeMap.get( childEntity );
if ( unmergedInstance != null && unmergedChild != null ) {
found = isFoundInParent(
propertyName,
@@ -1367,66 +1159,60 @@ public class StatefulPersistenceContext implements PersistenceContext {
EntityPersister persister,
CollectionPersister collectionPersister,
Object potentialParent) {
- Object collection = persister.getPropertyValue( potentialParent, property );
+ final Object collection = persister.getPropertyValue( potentialParent, property );
return collection != null
&& Hibernate.isInitialized( collection )
&& collectionPersister.getCollectionType().contains( collection, childEntity, session );
}
- /**
- * Search the persistence context for an index of the child object,
- * given a collection role
- */
@Override
public Object getIndexInOwner(String entity, String property, Object childEntity, Map mergeMap) {
-
- EntityPersister persister = session.getFactory()
- .getEntityPersister(entity);
- CollectionPersister cp = session.getFactory()
- .getCollectionPersister(entity + '.' + property);
+ final EntityPersister persister = session.getFactory().getEntityPersister( entity );
+ final CollectionPersister cp = session.getFactory().getCollectionPersister( entity + '.' + property );
// try cache lookup first
- Object parent = parentsByChild.get(childEntity);
- if (parent != null) {
+ final Object parent = parentsByChild.get( childEntity );
+ if ( parent != null ) {
final EntityEntry entityEntry = entityEntryContext.getEntityEntry( parent );
-// final EntityEntry entityEntry = entityEntries.get(parent);
//there maybe more than one parent, filter by type
if ( persister.isSubclassEntityName( entityEntry.getEntityName() ) ) {
- Object index = getIndexInParent(property, childEntity, persister, cp, parent);
+ Object index = getIndexInParent( property, childEntity, persister, cp, parent );
if (index==null && mergeMap!=null) {
- Object unmergedInstance = mergeMap.get(parent);
- Object unmergedChild = mergeMap.get(childEntity);
- if ( unmergedInstance!=null && unmergedChild!=null ) {
- index = getIndexInParent(property, unmergedChild, persister, cp, unmergedInstance);
+ final Object unMergedInstance = mergeMap.get( parent );
+ final Object unMergedChild = mergeMap.get( childEntity );
+ if ( unMergedInstance != null && unMergedChild != null ) {
+ index = getIndexInParent( property, unMergedChild, persister, cp, unMergedInstance );
}
}
- if (index!=null) {
+ if ( index != null ) {
return index;
}
}
else {
- parentsByChild.remove(childEntity); // remove wrong entry
+ // remove wrong entry
+ parentsByChild.remove( childEntity );
}
}
//Not found in cache, proceed
for ( Entry me : reentrantSafeEntityEntries() ) {
- EntityEntry ee = me.getValue();
+ final EntityEntry ee = me.getValue();
if ( persister.isSubclassEntityName( ee.getEntityName() ) ) {
- Object instance = me.getKey();
+ final Object instance = me.getKey();
- Object index = getIndexInParent(property, childEntity, persister, cp, instance);
-
- if (index==null && mergeMap!=null) {
- Object unmergedInstance = mergeMap.get(instance);
- Object unmergedChild = mergeMap.get(childEntity);
- if ( unmergedInstance!=null && unmergedChild!=null ) {
- index = getIndexInParent(property, unmergedChild, persister, cp, unmergedInstance);
+ Object index = getIndexInParent( property, childEntity, persister, cp, instance );
+ if ( index==null && mergeMap!=null ) {
+ final Object unMergedInstance = mergeMap.get( instance );
+ final Object unMergedChild = mergeMap.get( childEntity );
+ if ( unMergedInstance != null && unMergedChild!=null ) {
+ index = getIndexInParent( property, unMergedChild, persister, cp, unMergedInstance );
}
}
- if (index!=null) return index;
+ if ( index != null ) {
+ return index;
+ }
}
}
return null;
@@ -1438,30 +1224,23 @@ public class StatefulPersistenceContext implements PersistenceContext {
EntityPersister persister,
CollectionPersister collectionPersister,
Object potentialParent){
- Object collection = persister.getPropertyValue( potentialParent, property );
- if ( collection!=null && Hibernate.isInitialized(collection) ) {
- return collectionPersister.getCollectionType().indexOf(collection, childEntity);
+ final Object collection = persister.getPropertyValue( potentialParent, property );
+ if ( collection != null && Hibernate.isInitialized( collection ) ) {
+ return collectionPersister.getCollectionType().indexOf( collection, childEntity );
}
else {
return null;
}
}
- /**
- * Record the fact that the association belonging to the keyed
- * entity is null.
- */
@Override
public void addNullProperty(EntityKey ownerKey, String propertyName) {
- nullAssociations.add( new AssociationKey(ownerKey, propertyName) );
+ nullAssociations.add( new AssociationKey( ownerKey, propertyName ) );
}
- /**
- * Is the association property belonging to the keyed entity null?
- */
@Override
public boolean isPropertyNull(EntityKey ownerKey, String propertyName) {
- return nullAssociations.contains( new AssociationKey(ownerKey, propertyName) );
+ return nullAssociations.contains( new AssociationKey( ownerKey, propertyName ) );
}
private void clearNullProperties() {
@@ -1475,10 +1254,10 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
boolean isReadOnly;
if ( entityOrProxy instanceof HibernateProxy ) {
- isReadOnly = ( ( HibernateProxy ) entityOrProxy ).getHibernateLazyInitializer().isReadOnly();
+ isReadOnly = ( (HibernateProxy) entityOrProxy ).getHibernateLazyInitializer().isReadOnly();
}
else {
- EntityEntry ee = getEntry( entityOrProxy );
+ final EntityEntry ee = getEntry( entityOrProxy );
if ( ee == null ) {
throw new TransientObjectException("Instance was not associated with this persistence context" );
}
@@ -1496,7 +1275,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
return;
}
if ( object instanceof HibernateProxy ) {
- HibernateProxy proxy = ( HibernateProxy ) object;
+ final HibernateProxy proxy = (HibernateProxy) object;
setProxyReadOnly( proxy, readOnly );
if ( Hibernate.isInitialized( proxy ) ) {
setEntityReadOnly(
@@ -1509,9 +1288,9 @@ public class StatefulPersistenceContext implements PersistenceContext {
setEntityReadOnly( object, readOnly );
// PersistenceContext.proxyFor( entity ) returns entity if there is no proxy for that entity
// so need to check the return value to be sure it is really a proxy
- Object maybeProxy = getSession().getPersistenceContext().proxyFor( object );
+ final Object maybeProxy = getSession().getPersistenceContext().proxyFor( object );
if ( maybeProxy instanceof HibernateProxy ) {
- setProxyReadOnly( ( HibernateProxy ) maybeProxy, readOnly );
+ setProxyReadOnly( (HibernateProxy) maybeProxy, readOnly );
}
}
}
@@ -1525,11 +1304,11 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
private void setEntityReadOnly(Object entity, boolean readOnly) {
- EntityEntry entry = getEntry(entity);
- if (entry == null) {
- throw new TransientObjectException("Instance was not associated with this persistence context" );
+ final EntityEntry entry = getEntry( entity );
+ if ( entry == null ) {
+ throw new TransientObjectException( "Instance was not associated with this persistence context" );
}
- entry.setReadOnly(readOnly, entity );
+ entry.setReadOnly( readOnly, entity );
hasNonReadOnlyEntities = hasNonReadOnlyEntities || ! readOnly;
}
@@ -1543,16 +1322,16 @@ public class StatefulPersistenceContext implements PersistenceContext {
addEntity( newKey, entity );
addEntry(
entity,
- oldEntry.getStatus(),
- oldEntry.getLoadedState(),
- oldEntry.getRowId(),
- generatedId,
- oldEntry.getVersion(),
- oldEntry.getLockMode(),
- oldEntry.isExistsInDatabase(),
- oldEntry.getPersister(),
- oldEntry.isBeingReplicated(),
- oldEntry.isLoadedWithLazyPropertiesUnfetched()
+ oldEntry.getStatus(),
+ oldEntry.getLoadedState(),
+ oldEntry.getRowId(),
+ generatedId,
+ oldEntry.getVersion(),
+ oldEntry.getLockMode(),
+ oldEntry.isExistsInDatabase(),
+ oldEntry.getPersister(),
+ oldEntry.isBeingReplicated(),
+ oldEntry.isLoadedWithLazyPropertiesUnfetched()
);
}
@@ -1565,97 +1344,106 @@ public class StatefulPersistenceContext implements PersistenceContext {
*/
public void serialize(ObjectOutputStream oos) throws IOException {
final boolean tracing = LOG.isTraceEnabled();
- if ( tracing ) LOG.trace( "Serializing persistent-context" );
+ if ( tracing ) {
+ LOG.trace( "Serializing persistence-context" );
+ }
oos.writeBoolean( defaultReadOnly );
oos.writeBoolean( hasNonReadOnlyEntities );
oos.writeInt( entitiesByKey.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + entitiesByKey.size() + "] entitiesByKey entries");
- Iterator itr = entitiesByKey.entrySet().iterator();
- while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
- ( ( EntityKey ) entry.getKey() ).serialize( oos );
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + entitiesByKey.size() + "] entitiesByKey entries" );
+ }
+ for ( Map.Entry entry : entitiesByKey.entrySet() ) {
+ entry.getKey().serialize( oos );
oos.writeObject( entry.getValue() );
}
oos.writeInt( entitiesByUniqueKey.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + entitiesByUniqueKey.size() + "] entitiesByUniqueKey entries");
- itr = entitiesByUniqueKey.entrySet().iterator();
- while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
- ( ( EntityUniqueKey ) entry.getKey() ).serialize( oos );
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + entitiesByUniqueKey.size() + "] entitiesByUniqueKey entries" );
+ }
+ for ( Map.Entry entry : entitiesByUniqueKey.entrySet() ) {
+ entry.getKey().serialize( oos );
oos.writeObject( entry.getValue() );
}
oos.writeInt( proxiesByKey.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + proxiesByKey.size() + "] proxiesByKey entries");
- itr = proxiesByKey.entrySet().iterator();
- while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
- ( (EntityKey) entry.getKey() ).serialize( oos );
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + proxiesByKey.size() + "] proxiesByKey entries" );
+ }
+ for ( Map.Entry entry : proxiesByKey.entrySet() ) {
+ entry.getKey().serialize( oos );
oos.writeObject( entry.getValue() );
}
oos.writeInt( entitySnapshotsByKey.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + entitySnapshotsByKey.size() + "] entitySnapshotsByKey entries");
- itr = entitySnapshotsByKey.entrySet().iterator();
- while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
- ( ( EntityKey ) entry.getKey() ).serialize( oos );
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + entitySnapshotsByKey.size() + "] entitySnapshotsByKey entries" );
+ }
+ for ( Map.Entry entry : entitySnapshotsByKey.entrySet() ) {
+ entry.getKey().serialize( oos );
oos.writeObject( entry.getValue() );
}
entityEntryContext.serialize( oos );
-// oos.writeInt( entityEntries.size() );
-// if ( tracing ) LOG.trace("Starting serialization of [" + entityEntries.size() + "] entityEntries entries");
-// itr = entityEntries.entrySet().iterator();
-// while ( itr.hasNext() ) {
-// Map.Entry entry = ( Map.Entry ) itr.next();
-// oos.writeObject( entry.getKey() );
-// ( ( EntityEntry ) entry.getValue() ).serialize( oos );
-// }
oos.writeInt( collectionsByKey.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + collectionsByKey.size() + "] collectionsByKey entries");
- itr = collectionsByKey.entrySet().iterator();
- while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
- ( ( CollectionKey ) entry.getKey() ).serialize( oos );
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + collectionsByKey.size() + "] collectionsByKey entries" );
+ }
+ for ( Map.Entry entry : collectionsByKey.entrySet() ) {
+ entry.getKey().serialize( oos );
oos.writeObject( entry.getValue() );
}
oos.writeInt( collectionEntries.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + collectionEntries.size() + "] collectionEntries entries");
- itr = collectionEntries.entrySet().iterator();
- while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + collectionEntries.size() + "] collectionEntries entries" );
+ }
+ for ( Map.Entry entry : collectionEntries.entrySet() ) {
oos.writeObject( entry.getKey() );
- ( ( CollectionEntry ) entry.getValue() ).serialize( oos );
+ entry.getValue().serialize( oos );
}
oos.writeInt( arrayHolders.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + arrayHolders.size() + "] arrayHolders entries");
- itr = arrayHolders.entrySet().iterator();
- while ( itr.hasNext() ) {
- Map.Entry entry = ( Map.Entry ) itr.next();
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + arrayHolders.size() + "] arrayHolders entries" );
+ }
+ for ( Map.Entry entry : arrayHolders.entrySet() ) {
oos.writeObject( entry.getKey() );
oos.writeObject( entry.getValue() );
}
oos.writeInt( nullifiableEntityKeys.size() );
- if ( tracing ) LOG.trace("Starting serialization of [" + nullifiableEntityKeys.size() + "] nullifiableEntityKey entries");
+ if ( tracing ) {
+ LOG.trace( "Starting serialization of [" + nullifiableEntityKeys.size() + "] nullifiableEntityKey entries" );
+ }
for ( EntityKey entry : nullifiableEntityKeys ) {
entry.serialize( oos );
}
}
+ /**
+ * Used by the owning session to explicitly control deserialization of the persistence context.
+ *
+ * @param ois The stream from which the persistence context should be read
+ * @param session The owning session
+ *
+ * @return The deserialized StatefulPersistenceContext
+ *
+ * @throws IOException deserialization errors.
+ * @throws ClassNotFoundException deserialization errors.
+ */
public static StatefulPersistenceContext deserialize(
ObjectInputStream ois,
SessionImplementor session) throws IOException, ClassNotFoundException {
final boolean tracing = LOG.isTraceEnabled();
- if ( tracing ) LOG.trace("Serializing persistent-context");
- StatefulPersistenceContext rtn = new StatefulPersistenceContext( session );
+ if ( tracing ) {
+ LOG.trace( "Serializing persistent-context" );
+ }
+ final StatefulPersistenceContext rtn = new StatefulPersistenceContext( session );
// during deserialization, we need to reconnect all proxies and
// collections to this session, as well as the EntityEntry and
@@ -1668,21 +1456,27 @@ public class StatefulPersistenceContext implements PersistenceContext {
rtn.hasNonReadOnlyEntities = ois.readBoolean();
int count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] entitiesByKey entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] entitiesByKey entries" );
+ }
rtn.entitiesByKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count );
for ( int i = 0; i < count; i++ ) {
rtn.entitiesByKey.put( EntityKey.deserialize( ois, session ), ois.readObject() );
}
count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] entitiesByUniqueKey entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] entitiesByUniqueKey entries" );
+ }
rtn.entitiesByUniqueKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count );
for ( int i = 0; i < count; i++ ) {
rtn.entitiesByUniqueKey.put( EntityUniqueKey.deserialize( ois, session ), ois.readObject() );
}
count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] proxiesByKey entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] proxiesByKey entries" );
+ }
//noinspection unchecked
rtn.proxiesByKey = new ConcurrentReferenceHashMap(
count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count,
@@ -1693,60 +1487,65 @@ public class StatefulPersistenceContext implements PersistenceContext {
null
);
for ( int i = 0; i < count; i++ ) {
- EntityKey ek = EntityKey.deserialize( ois, session );
- Object proxy = ois.readObject();
+ final EntityKey ek = EntityKey.deserialize( ois, session );
+ final Object proxy = ois.readObject();
if ( proxy instanceof HibernateProxy ) {
- ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().setSession( session );
+ ( (HibernateProxy) proxy ).getHibernateLazyInitializer().setSession( session );
rtn.proxiesByKey.put( ek, proxy );
- } else {
- if ( tracing ) LOG.trace("Encountered prunded proxy");
}
- // otherwise, the proxy was pruned during the serialization process
+ else {
+ // otherwise, the proxy was pruned during the serialization process
+ if ( tracing ) {
+ LOG.trace( "Encountered pruned proxy" );
+ }
+ }
}
count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] entitySnapshotsByKey entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] entitySnapshotsByKey entries" );
+ }
rtn.entitySnapshotsByKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count );
for ( int i = 0; i < count; i++ ) {
rtn.entitySnapshotsByKey.put( EntityKey.deserialize( ois, session ), ois.readObject() );
}
rtn.entityEntryContext = EntityEntryContext.deserialize( ois, rtn );
-// count = ois.readInt();
-// if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] entityEntries entries");
-// rtn.entityEntries = IdentityMap.instantiateSequenced( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count );
-// for ( int i = 0; i < count; i++ ) {
-// Object entity = ois.readObject();
-// EntityEntry entry = EntityEntry.deserialize( ois, rtn );
-// rtn.entityEntries.put( entity, entry );
-// }
count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] collectionsByKey entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] collectionsByKey entries" );
+ }
rtn.collectionsByKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count );
for ( int i = 0; i < count; i++ ) {
rtn.collectionsByKey.put( CollectionKey.deserialize( ois, session ), (PersistentCollection) ois.readObject() );
}
count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] collectionEntries entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] collectionEntries entries" );
+ }
rtn.collectionEntries = IdentityMap.instantiateSequenced( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count );
for ( int i = 0; i < count; i++ ) {
- final PersistentCollection pc = ( PersistentCollection ) ois.readObject();
+ final PersistentCollection pc = (PersistentCollection) ois.readObject();
final CollectionEntry ce = CollectionEntry.deserialize( ois, session );
pc.setCurrentSession( session );
rtn.collectionEntries.put( pc, ce );
}
count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] arrayHolders entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] arrayHolders entries" );
+ }
rtn.arrayHolders = new IdentityHashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count );
for ( int i = 0; i < count; i++ ) {
rtn.arrayHolders.put( ois.readObject(), (PersistentCollection) ois.readObject() );
}
count = ois.readInt();
- if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] nullifiableEntityKey entries");
+ if ( tracing ) {
+ LOG.trace( "Starting deserialization of [" + count + "] nullifiableEntityKey entries" );
+ }
rtn.nullifiableEntityKeys = new HashSet();
for ( int i = 0; i < count; i++ ) {
rtn.nullifiableEntityKeys.add( EntityKey.deserialize( ois, session ) );
@@ -1762,12 +1561,12 @@ public class StatefulPersistenceContext implements PersistenceContext {
@Override
public void addChildParent(Object child, Object parent) {
- parentsByChild.put(child, parent);
+ parentsByChild.put( child, parent );
}
@Override
public void removeChildParent(Object child) {
- parentsByChild.remove(child);
+ parentsByChild.remove( child );
}
@@ -1797,7 +1596,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
// again, we only really care if the entity is cached
if ( persister.hasCache() ) {
if ( insertedKeysMap != null ) {
- List insertedEntityIds = insertedKeysMap.get( persister.getRootEntityName() );
+ final List insertedEntityIds = insertedKeysMap.get( persister.getRootEntityName() );
if ( insertedEntityIds != null ) {
return insertedEntityIds.contains( id );
}
@@ -1835,7 +1634,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
// from a single load event. The first put journal would come from the natural id resolution;
// the second comes from the entity loading. In this condition, we want to avoid the multiple
// 'put' stats incrementing.
- boolean justAddedLocally = naturalIdXrefDelegate.cacheNaturalIdCrossReference( persister, id, naturalIdValues );
+ final boolean justAddedLocally = naturalIdXrefDelegate.cacheNaturalIdCrossReference( persister, id, naturalIdValues );
if ( justAddedLocally && persister.hasNaturalIdCache() ) {
managedSharedCacheEntries( persister, id, naturalIdValues, null, CachedNaturalIdValueSource.LOAD );
@@ -1898,8 +1697,9 @@ public class StatefulPersistenceContext implements PersistenceContext {
switch ( source ) {
case LOAD: {
- if (naturalIdCacheAccessStrategy.get(naturalIdCacheKey, session.getTimestamp()) != null) {
- return; // prevent identical re-cachings
+ if ( naturalIdCacheAccessStrategy.get( naturalIdCacheKey, session.getTimestamp() ) != null ) {
+ // prevent identical re-cachings
+ return;
}
final boolean put = naturalIdCacheAccessStrategy.putFromLoad(
naturalIdCacheKey,
@@ -1937,7 +1737,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
}
else {
- naturalIdCacheAccessStrategy.remove(naturalIdCacheKey);
+ naturalIdCacheAccessStrategy.remove( naturalIdCacheKey );
}
}
}
@@ -1947,8 +1747,9 @@ public class StatefulPersistenceContext implements PersistenceContext {
}
case UPDATE: {
final NaturalIdCacheKey previousCacheKey = new NaturalIdCacheKey( previousNaturalIdValues, persister, session );
- if (naturalIdCacheKey.equals(previousCacheKey)) {
- return; // prevent identical re-caching, solves HHH-7309
+ if ( naturalIdCacheKey.equals( previousCacheKey ) ) {
+ // prevent identical re-caching, solves HHH-7309
+ return;
}
final SoftLock removalLock = naturalIdCacheAccessStrategy.lockItem( previousCacheKey, null );
naturalIdCacheAccessStrategy.remove( previousCacheKey );
@@ -1982,6 +1783,9 @@ public class StatefulPersistenceContext implements PersistenceContext {
break;
}
+ default: {
+ LOG.debug( "Unexpected CachedNaturalIdValueSource [" + source + "]" );
+ }
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/TwoPhaseLoad.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/TwoPhaseLoad.java
index 3d6f83404d..df2190b570 100755
--- a/hibernate-core/src/main/java/org/hibernate/engine/internal/TwoPhaseLoad.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/TwoPhaseLoad.java
@@ -57,17 +57,19 @@ import org.hibernate.type.Type;
import org.hibernate.type.TypeHelper;
/**
- * Functionality relating to Hibernate's two-phase loading process,
- * that may be reused by persisters that do not use the Loader
- * framework
+ * Functionality relating to the Hibernate two-phase loading process, that may be reused by persisters
+ * that do not use the Loader framework
*
* @author Gavin King
*/
public final class TwoPhaseLoad {
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ TwoPhaseLoad.class.getName()
+ );
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, TwoPhaseLoad.class.getName() );
-
- private TwoPhaseLoad() {}
+ private TwoPhaseLoad() {
+ }
/**
* Register the "hydrated" state of an entity instance, after the first step of 2-phase loading.
@@ -75,19 +77,26 @@ public final class TwoPhaseLoad {
* Add the "hydrated state" (an array) of an uninitialized entity to the session. We don't try
* to resolve any associations yet, because there might be other entities waiting to be
* read from the JDBC result set we are currently processing
+ *
+ * @param persister The persister for the hydrated entity
+ * @param id The entity identifier
+ * @param values The entity values
+ * @param rowId The rowId for the entity
+ * @param object An optional instance for the entity being loaded
+ * @param lockMode The lock mode
+ * @param lazyPropertiesAreUnFetched Whether properties defined as lazy are yet un-fetched
+ * @param session The Session
*/
public static void postHydrate(
- final EntityPersister persister,
- final Serializable id,
- final Object[] values,
- final Object rowId,
- final Object object,
- final LockMode lockMode,
- final boolean lazyPropertiesAreUnfetched,
- final SessionImplementor session)
- throws HibernateException {
-
- Object version = Versioning.getVersion( values, persister );
+ final EntityPersister persister,
+ final Serializable id,
+ final Object[] values,
+ final Object rowId,
+ final Object object,
+ final LockMode lockMode,
+ final boolean lazyPropertiesAreUnFetched,
+ final SessionImplementor session) {
+ final Object version = Versioning.getVersion( values, persister );
session.getPersistenceContext().addEntry(
object,
Status.LOADING,
@@ -99,47 +108,41 @@ public final class TwoPhaseLoad {
true,
persister,
false,
- lazyPropertiesAreUnfetched
+ lazyPropertiesAreUnFetched
);
if ( version != null && LOG.isTraceEnabled() ) {
- String versionStr = persister.isVersioned()
+ final String versionStr = persister.isVersioned()
? persister.getVersionType().toLoggableString( version, session.getFactory() )
: "null";
- LOG.tracev( "Version: {0}", versionStr );
+ LOG.tracef( "Version: %s", versionStr );
}
-
}
/**
* Perform the second step of 2-phase load. Fully initialize the entity
* instance.
- *
+ *
* After processing a JDBC result set, we "resolve" all the associations
* between the entities which were instantiated and had their state
* "hydrated" into an array
+ *
+ * @param entity The entity being loaded
+ * @param readOnly Is the entity being loaded as read-only
+ * @param session The Session
+ * @param preLoadEvent The (re-used) pre-load event
*/
public static void initializeEntity(
final Object entity,
final boolean readOnly,
final SessionImplementor session,
- final PreLoadEvent preLoadEvent,
- final PostLoadEvent postLoadEvent) throws HibernateException {
+ final PreLoadEvent preLoadEvent) {
final PersistenceContext persistenceContext = session.getPersistenceContext();
- final EntityEntry entityEntry = persistenceContext.getEntry(entity);
+ final EntityEntry entityEntry = persistenceContext.getEntry( entity );
if ( entityEntry == null ) {
throw new AssertionFailure( "possible non-threadsafe access to the session" );
}
- final EntityPersister persister = entityEntry.getPersister();
- final Serializable id = entityEntry.getId();
-
-// persistenceContext.getNaturalIdHelper().startingLoad( persister, id );
-// try {
- doInitializeEntity( entity, entityEntry, readOnly, session, preLoadEvent, postLoadEvent );
-// }
-// finally {
-// persistenceContext.getNaturalIdHelper().endingLoad( persister, id );
-// }
+ doInitializeEntity( entity, entityEntry, readOnly, session, preLoadEvent );
}
private static void doInitializeEntity(
@@ -147,12 +150,11 @@ public final class TwoPhaseLoad {
final EntityEntry entityEntry,
final boolean readOnly,
final SessionImplementor session,
- final PreLoadEvent preLoadEvent,
- final PostLoadEvent postLoadEvent) throws HibernateException {
+ final PreLoadEvent preLoadEvent) throws HibernateException {
final PersistenceContext persistenceContext = session.getPersistenceContext();
- EntityPersister persister = entityEntry.getPersister();
- Serializable id = entityEntry.getId();
- Object[] hydratedState = entityEntry.getLoadedState();
+ final EntityPersister persister = entityEntry.getPersister();
+ final Serializable id = entityEntry.getId();
+ final Object[] hydratedState = entityEntry.getLoadedState();
final boolean debugEnabled = LOG.isDebugEnabled();
if ( debugEnabled ) {
@@ -162,7 +164,7 @@ public final class TwoPhaseLoad {
);
}
- Type[] types = persister.getPropertyTypes();
+ final Type[] types = persister.getPropertyTypes();
for ( int i = 0; i < hydratedState.length; i++ ) {
final Object value = hydratedState[i];
if ( value!=LazyPropertyInitializer.UNFETCHED_PROPERTY && value!=BackrefPropertyAccessor.UNKNOWN ) {
@@ -196,9 +198,9 @@ public final class TwoPhaseLoad {
);
}
- Object version = Versioning.getVersion(hydratedState, persister);
- CacheEntry entry = persister.buildCacheEntry( entity, hydratedState, version, session );
- CacheKey cacheKey = session.generateCacheKey( id, persister.getIdentifierType(), persister.getRootEntityName() );
+ final Object version = Versioning.getVersion( hydratedState, persister );
+ final CacheEntry entry = persister.buildCacheEntry( entity, hydratedState, version, session );
+ final CacheKey cacheKey = session.generateCacheKey( id, persister.getIdentifierType(), persister.getRootEntityName() );
// explicit handling of caching for rows just inserted and then somehow forced to be read
// from the database *within the same transaction*. usually this is done by
@@ -215,7 +217,7 @@ public final class TwoPhaseLoad {
);
}
else {
- boolean put = persister.getCacheAccessStrategy().putFromLoad(
+ final boolean put = persister.getCacheAccessStrategy().putFromLoad(
cacheKey,
persister.getCacheEntryStructure().structure( entry ),
session.getTimestamp(),
@@ -242,11 +244,11 @@ public final class TwoPhaseLoad {
isReallyReadOnly = true;
}
else {
- Object proxy = persistenceContext.getProxy( entityEntry.getEntityKey() );
+ final Object proxy = persistenceContext.getProxy( entityEntry.getEntityKey() );
if ( proxy != null ) {
// there is already a proxy for this impl
// only set the status to read-only if the proxy is read-only
- isReallyReadOnly = ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().isReadOnly();
+ isReallyReadOnly = ( (HibernateProxy) proxy ).getHibernateLazyInitializer().isReadOnly();
}
}
if ( isReallyReadOnly ) {
@@ -254,7 +256,7 @@ public final class TwoPhaseLoad {
//performance optimization, but not really
//important, except for entities with huge
//mutable property values
- persistenceContext.setEntryStatus(entityEntry, Status.READ_ONLY);
+ persistenceContext.setEntryStatus( entityEntry, Status.READ_ONLY );
}
else {
//take a snapshot
@@ -262,10 +264,11 @@ public final class TwoPhaseLoad {
hydratedState,
persister.getPropertyTypes(),
persister.getPropertyUpdateability(),
- hydratedState, //after setting values to object, entityMode
+ //after setting values to object
+ hydratedState,
session
);
- persistenceContext.setEntryStatus(entityEntry, Status.MANAGED);
+ persistenceContext.setEntryStatus( entityEntry, Status.MANAGED );
}
persister.afterInitialize(
@@ -291,13 +294,12 @@ public final class TwoPhaseLoad {
* the Set collections are added to the persistence context by Loader.
* Without the split, LazyInitializationExceptions can occur in the Entity's
* postLoad if it acts upon the collection.
- *
- *
+ *
* HHH-6043
*
- * @param entity
- * @param session
- * @param postLoadEvent
+ * @param entity The entity
+ * @param session The Session
+ * @param postLoadEvent The (re-used) post-load event
*/
public static void postLoad(
final Object entity,
@@ -307,15 +309,11 @@ public final class TwoPhaseLoad {
if ( session.isEventSource() ) {
final PersistenceContext persistenceContext
= session.getPersistenceContext();
- final EntityEntry entityEntry = persistenceContext.getEntry(entity);
- final Serializable id = entityEntry.getId();
-
- postLoadEvent.setEntity( entity ).setId( entityEntry.getId() )
- .setPersister( entityEntry.getPersister() );
+ final EntityEntry entityEntry = persistenceContext.getEntry( entity );
- final EventListenerGroup listenerGroup
- = session
- .getFactory()
+ postLoadEvent.setEntity( entity ).setId( entityEntry.getId() ).setPersister( entityEntry.getPersister() );
+
+ final EventListenerGroup listenerGroup = session.getFactory()
.getServiceRegistry()
.getService( EventListenerRegistry.class )
.getEventListenerGroup( EventType.POST_LOAD );
@@ -339,15 +337,21 @@ public final class TwoPhaseLoad {
*
* Create a "temporary" entry for a newly instantiated entity. The entity is uninitialized,
* but we need the mapping from id to instance in order to guarantee uniqueness.
+ *
+ * @param key The entity key
+ * @param object The entity instance
+ * @param persister The entity persister
+ * @param lockMode The lock mode
+ * @param lazyPropertiesAreUnFetched Are lazy properties still un-fetched?
+ * @param session The Session
*/
public static void addUninitializedEntity(
final EntityKey key,
final Object object,
final EntityPersister persister,
final LockMode lockMode,
- final boolean lazyPropertiesAreUnfetched,
- final SessionImplementor session
- ) {
+ final boolean lazyPropertiesAreUnFetched,
+ final SessionImplementor session) {
session.getPersistenceContext().addEntity(
object,
Status.LOADING,
@@ -358,19 +362,29 @@ public final class TwoPhaseLoad {
true,
persister,
false,
- lazyPropertiesAreUnfetched
- );
+ lazyPropertiesAreUnFetched
+ );
}
+ /**
+ * Same as {@link #addUninitializedEntity}, but here for an entity from the second level cache
+ *
+ * @param key The entity key
+ * @param object The entity instance
+ * @param persister The entity persister
+ * @param lockMode The lock mode
+ * @param lazyPropertiesAreUnFetched Are lazy properties still un-fetched?
+ * @param version The version
+ * @param session The Session
+ */
public static void addUninitializedCachedEntity(
final EntityKey key,
final Object object,
final EntityPersister persister,
final LockMode lockMode,
- final boolean lazyPropertiesAreUnfetched,
+ final boolean lazyPropertiesAreUnFetched,
final Object version,
- final SessionImplementor session
- ) {
+ final SessionImplementor session) {
session.getPersistenceContext().addEntity(
object,
Status.LOADING,
@@ -381,7 +395,7 @@ public final class TwoPhaseLoad {
true,
persister,
false,
- lazyPropertiesAreUnfetched
+ lazyPropertiesAreUnFetched
);
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/UnsavedValueFactory.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/UnsavedValueFactory.java
index 23d8e5c517..5950c7f663 100755
--- a/hibernate-core/src/main/java/org/hibernate/engine/internal/UnsavedValueFactory.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/UnsavedValueFactory.java
@@ -37,13 +37,24 @@ import org.hibernate.type.Type;
import org.hibernate.type.VersionType;
/**
+ * Helper for dealing with unsaved value handling
+ *
* @author Gavin King
*/
public class UnsavedValueFactory {
-
+
+ /**
+ * Instantiate a class using the provided Constructor
+ *
+ * @param constructor The constructor
+ *
+ * @return The instantiated object
+ *
+ * @throws InstantiationException if something went wrong
+ */
private static Object instantiate(Constructor constructor) {
try {
- return constructor.newInstance( (Object[]) null );
+ return constructor.newInstance();
}
catch (Exception e) {
throw new InstantiationException( "could not instantiate test object", constructor.getDeclaringClass(), e );
@@ -54,22 +65,28 @@ public class UnsavedValueFactory {
* Return an IdentifierValue for the specified unsaved-value. If none is specified,
* guess the unsaved value by instantiating a test instance of the class and
* reading it's id property, or if that is not possible, using the java default
- * value for the type
+ * value for the type
+ *
+ * @param unsavedValue The mapping defined unsaved value
+ * @param identifierGetter The getter for the entity identifier attribute
+ * @param identifierType The mapping type for the identifier
+ * @param constructor The constructor for the entity
+ *
+ * @return The appropriate IdentifierValue
*/
public static IdentifierValue getUnsavedIdentifierValue(
- String unsavedValue,
+ String unsavedValue,
Getter identifierGetter,
Type identifierType,
Constructor constructor) {
-
if ( unsavedValue == null ) {
- if ( identifierGetter!=null && constructor!=null ) {
+ if ( identifierGetter != null && constructor != null ) {
// use the id value of a newly instantiated instance as the unsaved-value
- Serializable defaultValue = (Serializable) identifierGetter.get( instantiate(constructor) );
+ final Serializable defaultValue = (Serializable) identifierGetter.get( instantiate( constructor ) );
return new IdentifierValue( defaultValue );
}
else if ( identifierGetter != null && (identifierType instanceof PrimitiveType) ) {
- Serializable defaultValue = ( ( PrimitiveType ) identifierType ).getDefaultValue();
+ final Serializable defaultValue = ( (PrimitiveType) identifierType ).getDefaultValue();
return new IdentifierValue( defaultValue );
}
else {
@@ -90,7 +107,7 @@ public class UnsavedValueFactory {
}
else {
try {
- return new IdentifierValue( ( Serializable ) ( ( IdentifierType ) identifierType ).stringToObject( unsavedValue ) );
+ return new IdentifierValue( (Serializable) ( (IdentifierType) identifierType ).stringToObject( unsavedValue ) );
}
catch ( ClassCastException cce ) {
throw new MappingException( "Bad identifier type: " + identifierType.getName() );
@@ -101,6 +118,19 @@ public class UnsavedValueFactory {
}
}
+ /**
+ * Return an IdentifierValue for the specified unsaved-value. If none is specified,
+ * guess the unsaved value by instantiating a test instance of the class and
+ * reading it's version property value, or if that is not possible, using the java default
+ * value for the type
+ *
+ * @param versionUnsavedValue The mapping defined unsaved value
+ * @param versionGetter The version attribute getter
+ * @param versionType The mapping type for the version
+ * @param constructor The constructor for the entity
+ *
+ * @return The appropriate VersionValue
+ */
public static VersionValue getUnsavedVersionValue(
String versionUnsavedValue,
Getter versionGetter,
@@ -109,12 +139,12 @@ public class UnsavedValueFactory {
if ( versionUnsavedValue == null ) {
if ( constructor!=null ) {
- Object defaultValue = versionGetter.get( instantiate(constructor) );
+ final Object defaultValue = versionGetter.get( instantiate( constructor ) );
// if the version of a newly instantiated object is not the same
// as the version seed value, use that as the unsaved-value
- return versionType.isEqual( versionType.seed( null ), defaultValue ) ?
- VersionValue.UNDEFINED :
- new VersionValue( defaultValue );
+ return versionType.isEqual( versionType.seed( null ), defaultValue )
+ ? VersionValue.UNDEFINED
+ : new VersionValue( defaultValue );
}
else {
return VersionValue.UNDEFINED;
@@ -133,7 +163,8 @@ public class UnsavedValueFactory {
// this should not happen since the DTD prevents it
throw new MappingException( "Could not parse version unsaved-value: " + versionUnsavedValue );
}
-
}
+ private UnsavedValueFactory() {
+ }
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/Versioning.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/Versioning.java
index 5cf6fdcd51..dd72581fea 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/internal/Versioning.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/Versioning.java
@@ -36,38 +36,16 @@ import org.hibernate.type.VersionType;
* @author Gavin King
*/
public final class Versioning {
-
- // todo : replace these constants with references to org.hibernate.annotations.OptimisticLockType enum
-
- /**
- * Apply no optimistic locking
- */
- public static final int OPTIMISTIC_LOCK_NONE = -1;
-
- /**
- * Apply optimistic locking based on the defined version or timestamp
- * property.
- */
- public static final int OPTIMISTIC_LOCK_VERSION = 0;
-
- /**
- * Apply optimistic locking based on the a current vs. snapshot comparison
- * of all properties.
- */
- public static final int OPTIMISTIC_LOCK_ALL = 2;
-
- /**
- * Apply optimistic locking based on the a current vs. snapshot comparison
- * of dirty properties.
- */
- public static final int OPTIMISTIC_LOCK_DIRTY = 1;
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, Versioning.class.getName() );
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ Versioning.class.getName()
+ );
/**
* Private constructor disallowing instantiation.
*/
- private Versioning() {}
+ private Versioning() {
+ }
/**
* Create an initial optimistic locking value according the {@link VersionType}
@@ -78,8 +56,8 @@ public final class Versioning {
* @return The initial optimistic locking value
*/
private static Object seed(VersionType versionType, SessionImplementor session) {
- Object seed = versionType.seed( session );
- LOG.tracev( "Seeding: {0}", seed );
+ final Object seed = versionType.seed( session );
+ LOG.tracef( "Seeding: %s", seed );
return seed;
}
@@ -96,11 +74,11 @@ public final class Versioning {
* otherwise.
*/
public static boolean seedVersion(
- Object[] fields,
- int versionProperty,
- VersionType versionType,
- SessionImplementor session) {
- Object initialVersion = fields[versionProperty];
+ Object[] fields,
+ int versionProperty,
+ VersionType versionType,
+ SessionImplementor session) {
+ final Object initialVersion = fields[versionProperty];
if (
initialVersion==null ||
// This next bit is to allow for both unsaved-value="negative"
@@ -126,11 +104,15 @@ public final class Versioning {
* @param session The originating session
* @return The incremented optimistic locking value.
*/
+ @SuppressWarnings("unchecked")
public static Object increment(Object version, VersionType versionType, SessionImplementor session) {
- Object next = versionType.next( version, session );
+ final Object next = versionType.next( version, session );
if ( LOG.isTraceEnabled() ) {
- LOG.tracev( "Incrementing: {0} to {1}", versionType.toLoggableString( version, session.getFactory() ),
- versionType.toLoggableString( next, session.getFactory() ) );
+ LOG.tracef(
+ "Incrementing: %s to %s",
+ versionType.toLoggableString( version, session.getFactory() ),
+ versionType.toLoggableString( next, session.getFactory() )
+ );
}
return next;
}
@@ -178,8 +160,8 @@ public final class Versioning {
if ( hasDirtyCollections ) {
return true;
}
- for ( int i = 0; i < dirtyProperties.length; i++ ) {
- if ( propertyVersionability[ dirtyProperties[i] ] ) {
+ for ( int dirtyProperty : dirtyProperties ) {
+ if ( propertyVersionability[dirtyProperty] ) {
return true;
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/package-info.java
new file mode 100644
index 0000000000..d834aad232
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/package-info.java
@@ -0,0 +1,30 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2013, Red Hat Inc. 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 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
+ */
+
+/**
+ * Support for many of the internal workings of Hibernate.
+ *
+ * See also the {@link org.hibernate.internal} package.
+ */
+package org.hibernate.engine.internal;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java
index 3475b2310c..fa1c554ac3 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java
@@ -47,7 +47,7 @@ public class BlobProxy implements InvocationHandler {
private static final Class[] PROXY_INTERFACES = new Class[] { Blob.class, BlobImplementer.class };
private BinaryStream binaryStream;
- private boolean needsReset = false;
+ private boolean needsReset;
/**
* Constructor used to build {@link Blob} from byte array.
@@ -75,7 +75,7 @@ public class BlobProxy implements InvocationHandler {
}
private InputStream getStream() throws SQLException {
- InputStream stream = binaryStream.getInputStream();
+ final InputStream stream = binaryStream.getInputStream();
try {
if ( needsReset ) {
stream.reset();
@@ -92,8 +92,7 @@ public class BlobProxy implements InvocationHandler {
* {@inheritDoc}
*
* @throws UnsupportedOperationException if any methods other than
- * {@link Blob#length}, {@link Blob#getUnderlyingStream},
- * {@link Blob#getBinaryStream}, {@link Blob#getBytes}, {@link Blob#free},
+ * {@link Blob#length}, {@link Blob#getBinaryStream}, {@link Blob#getBytes}, {@link Blob#free},
* or toString/equals/hashCode are invoked.
*/
@Override
@@ -113,14 +112,14 @@ public class BlobProxy implements InvocationHandler {
return getStream();
}
else if ( argCount == 2 ) {
- long start = (Long) args[0];
+ final long start = (Long) args[0];
if ( start < 1 ) {
throw new SQLException( "Start position 1-based; must be 1 or more." );
}
if ( start > getLength() ) {
throw new SQLException( "Start position [" + start + "] cannot exceed overall CLOB length [" + getLength() + "]" );
}
- int length = (Integer) args[1];
+ final int length = (Integer) args[1];
if ( length < 0 ) {
// java docs specifically say for getBinaryStream(long,int) that the start+length must not exceed the
// total length, however that is at odds with the getBytes(long,int) behavior.
@@ -131,11 +130,11 @@ public class BlobProxy implements InvocationHandler {
}
if ( "getBytes".equals( methodName ) ) {
if ( argCount == 2 ) {
- long start = (Long) args[0];
+ final long start = (Long) args[0];
if ( start < 1 ) {
throw new SQLException( "Start position 1-based; must be 1 or more." );
}
- int length = (Integer) args[1];
+ final int length = (Integer) args[1];
if ( length < 0 ) {
throw new SQLException( "Length must be great-than-or-equal to zero." );
}
@@ -167,11 +166,7 @@ public class BlobProxy implements InvocationHandler {
* @return The generated proxy.
*/
public static Blob generateProxy(byte[] bytes) {
- return ( Blob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new BlobProxy( bytes )
- );
+ return (Blob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new BlobProxy( bytes ) );
}
/**
@@ -183,11 +178,7 @@ public class BlobProxy implements InvocationHandler {
* @return The generated proxy.
*/
public static Blob generateProxy(InputStream stream, long length) {
- return ( Blob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new BlobProxy( stream, length )
- );
+ return (Blob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new BlobProxy( stream, length ) );
}
/**
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ClobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ClobProxy.java
index 34b601c4d4..5faf45cbb5 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ClobProxy.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ClobProxy.java
@@ -48,7 +48,7 @@ public class ClobProxy implements InvocationHandler {
private static final Class[] PROXY_INTERFACES = new Class[] { Clob.class, ClobImplementer.class };
private final CharacterStream characterStream;
- private boolean needsReset = false;
+ private boolean needsReset;
/**
* Constructor used to build {@link Clob} from string data.
@@ -88,8 +88,8 @@ public class ClobProxy implements InvocationHandler {
protected String getSubString(long start, int length) {
final String string = characterStream.asString();
// semi-naive implementation
- int endIndex = Math.min( ((int)start)+length, string.length() );
- return string.substring( (int)start, endIndex );
+ final int endIndex = Math.min( ( (int) start ) + length, string.length() );
+ return string.substring( (int) start, endIndex );
}
/**
@@ -118,14 +118,14 @@ public class ClobProxy implements InvocationHandler {
return getCharacterStream();
}
else if ( argCount == 2 ) {
- long start = (Long) args[0];
+ final long start = (Long) args[0];
if ( start < 1 ) {
throw new SQLException( "Start position 1-based; must be 1 or more." );
}
if ( start > getLength() ) {
throw new SQLException( "Start position [" + start + "] cannot exceed overall CLOB length [" + getLength() + "]" );
}
- int length = (Integer) args[1];
+ final int length = (Integer) args[1];
if ( length < 0 ) {
// java docs specifically say for getCharacterStream(long,int) that the start+length must not exceed the
// total length, however that is at odds with the getSubString(long,int) behavior.
@@ -135,14 +135,14 @@ public class ClobProxy implements InvocationHandler {
}
}
if ( "getSubString".equals( methodName ) && argCount == 2 ) {
- long start = (Long) args[0];
+ final long start = (Long) args[0];
if ( start < 1 ) {
throw new SQLException( "Start position 1-based; must be 1 or more." );
}
if ( start > getLength() ) {
throw new SQLException( "Start position [" + start + "] cannot exceed overall CLOB length [" + getLength() + "]" );
}
- int length = (Integer) args[1];
+ final int length = (Integer) args[1];
if ( length < 0 ) {
throw new SQLException( "Length must be great-than-or-equal to zero." );
}
@@ -185,11 +185,7 @@ public class ClobProxy implements InvocationHandler {
* @return The generated proxy.
*/
public static Clob generateProxy(String string) {
- return ( Clob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new ClobProxy( string )
- );
+ return (Clob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new ClobProxy( string ) );
}
/**
@@ -201,11 +197,7 @@ public class ClobProxy implements InvocationHandler {
* @return The generated proxy.
*/
public static Clob generateProxy(Reader reader, long length) {
- return ( Clob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new ClobProxy( reader, length )
- );
+ return (Clob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new ClobProxy( reader, length ) );
}
/**
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ColumnNameCache.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ColumnNameCache.java
index 934e2c6c55..c1b006958c 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ColumnNameCache.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ColumnNameCache.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.engine.jdbc;
+
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
@@ -33,24 +34,42 @@ import java.util.concurrent.ConcurrentHashMap;
* @author Steve Ebersole
*/
public class ColumnNameCache {
- public static final float LOAD_FACTOR = .75f;
+ private static final float LOAD_FACTOR = .75f;
private final Map columnNameToIndexCache;
+ /**
+ * Constructs a ColumnNameCache
+ *
+ * @param columnCount The number of columns to be cached.
+ */
public ColumnNameCache(int columnCount) {
// should *not* need to grow beyond the size of the total number of columns in the rs
- this.columnNameToIndexCache = new ConcurrentHashMap( columnCount + (int)( columnCount * LOAD_FACTOR ) + 1, LOAD_FACTOR );
+ this.columnNameToIndexCache = new ConcurrentHashMap(
+ columnCount + (int)( columnCount * LOAD_FACTOR ) + 1,
+ LOAD_FACTOR
+ );
}
+ /**
+ * Resolve the column name/alias to its index
+ *
+ * @param columnName The name/alias of the column
+ * @param rs The ResultSet
+ *
+ * @return The index
+ *
+ * @throws SQLException INdicates a problems accessing the underlying JDBC ResultSet
+ */
public int getIndexForColumnName(String columnName, ResultSet rs) throws SQLException {
- Integer cached = columnNameToIndexCache.get( columnName );
+ final Integer cached = columnNameToIndexCache.get( columnName );
if ( cached != null ) {
return cached;
}
else {
- int index = rs.findColumn( columnName );
+ final int index = rs.findColumn( columnName );
columnNameToIndexCache.put( columnName, index);
return index;
}
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ContextualLobCreator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ContextualLobCreator.java
index fb2416e2c2..14859aed60 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ContextualLobCreator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ContextualLobCreator.java
@@ -43,6 +43,11 @@ import org.hibernate.JDBCException;
public class ContextualLobCreator extends AbstractLobCreator implements LobCreator {
private LobCreationContext lobCreationContext;
+ /**
+ * Constructs a ContextualLobCreator
+ *
+ * @param lobCreationContext The context for performing LOB creation
+ */
public ContextualLobCreator(LobCreationContext lobCreationContext) {
this.lobCreationContext = lobCreationContext;
}
@@ -59,7 +64,7 @@ public class ContextualLobCreator extends AbstractLobCreator implements LobCreat
@Override
public Blob createBlob(byte[] bytes) {
try {
- Blob blob = createBlob();
+ final Blob blob = createBlob();
blob.setBytes( 1, bytes );
return blob;
}
@@ -87,7 +92,7 @@ public class ContextualLobCreator extends AbstractLobCreator implements LobCreat
@Override
public Clob createClob(String string) {
try {
- Clob clob = createClob();
+ final Clob clob = createClob();
clob.setString( 1, string );
return clob;
}
@@ -115,7 +120,7 @@ public class ContextualLobCreator extends AbstractLobCreator implements LobCreat
@Override
public NClob createNClob(String string) {
try {
- NClob nclob = createNClob();
+ final NClob nclob = createNClob();
nclob.setString( 1, string );
return nclob;
}
@@ -131,19 +136,31 @@ public class ContextualLobCreator extends AbstractLobCreator implements LobCreat
return NonContextualLobCreator.INSTANCE.createNClob( reader, length );
}
+ /**
+ * Callback for performing contextual BLOB creation
+ */
public static final LobCreationContext.Callback CREATE_BLOB_CALLBACK = new LobCreationContext.Callback() {
+ @Override
public Blob executeOnConnection(Connection connection) throws SQLException {
return connection.createBlob();
}
};
+ /**
+ * Callback for performing contextual CLOB creation
+ */
public static final LobCreationContext.Callback CREATE_CLOB_CALLBACK = new LobCreationContext.Callback() {
+ @Override
public Clob executeOnConnection(Connection connection) throws SQLException {
return connection.createClob();
}
};
+ /**
+ * Callback for performing contextual NCLOB creation
+ */
public static final LobCreationContext.Callback CREATE_NCLOB_CALLBACK = new LobCreationContext.Callback() {
+ @Override
public NClob executeOnConnection(Connection connection) throws SQLException {
return connection.createNClob();
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/LobCreationContext.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/LobCreationContext.java
index 42a764e7b8..1276676eba 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/LobCreationContext.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/LobCreationContext.java
@@ -39,8 +39,10 @@ public interface LobCreationContext {
* Perform whatever actions are necessary using the provided JDBC {@link Connection}.
*
* @param connection The JDBC {@link Connection}.
+ *
* @return The created LOB.
- * @throws SQLException
+ *
+ * @throws SQLException Indicates trouble accessing the JDBC driver to create the LOB
*/
public T executeOnConnection(Connection connection) throws SQLException;
}
@@ -49,6 +51,9 @@ public interface LobCreationContext {
* Execute the given callback, making sure it has access to a viable JDBC {@link Connection}.
*
* @param callback The callback to execute .
+ * @param The Java type of the type of LOB being created. One of {@link java.sql.Blob},
+ * {@link java.sql.Clob}, {@link java.sql.NClob}
+ *
* @return The LOB created by the callback.
*/
public T execute(Callback callback);
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobImplementer.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobImplementer.java
index f7de45cda4..9676ea2778 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobImplementer.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobImplementer.java
@@ -23,7 +23,6 @@
*/
package org.hibernate.engine.jdbc;
-
/**
* Marker interface for non-contextually created java.sql.NClob instances..
*
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobProxy.java
index 4f9227891d..5f44978694 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobProxy.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobProxy.java
@@ -25,7 +25,6 @@ package org.hibernate.engine.jdbc;
import java.io.Reader;
import java.lang.reflect.Proxy;
-import java.sql.Clob;
import java.sql.NClob;
import org.hibernate.internal.util.ClassLoaderHelper;
@@ -40,6 +39,9 @@ import org.hibernate.internal.util.ClassLoaderHelper;
* @author Steve Ebersole
*/
public class NClobProxy extends ClobProxy {
+ /**
+ * The interfaces used to generate the proxy
+ */
public static final Class[] PROXY_INTERFACES = new Class[] { NClob.class, NClobImplementer.class };
protected NClobProxy(String string) {
@@ -58,15 +60,11 @@ public class NClobProxy extends ClobProxy {
* @return The generated proxy.
*/
public static NClob generateProxy(String string) {
- return ( NClob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new ClobProxy( string )
- );
+ return (NClob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new ClobProxy( string ) );
}
/**
- * Generates a {@link Clob} proxy using a character reader of given length.
+ * Generates a {@link java.sql.NClob} proxy using a character reader of given length.
*
* @param reader The character reader
* @param length The length of the character reader
@@ -74,11 +72,7 @@ public class NClobProxy extends ClobProxy {
* @return The generated proxy.
*/
public static NClob generateProxy(Reader reader, long length) {
- return ( NClob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new ClobProxy( reader, length )
- );
+ return (NClob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new ClobProxy( reader, length ) );
}
/**
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NonContextualLobCreator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NonContextualLobCreator.java
index 93b5ec9db0..886e2493f5 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NonContextualLobCreator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NonContextualLobCreator.java
@@ -37,6 +37,9 @@ import java.sql.NClob;
* @author Gail Badner
*/
public class NonContextualLobCreator extends AbstractLobCreator implements LobCreator {
+ /**
+ * Singleton access
+ */
public static final NonContextualLobCreator INSTANCE = new NonContextualLobCreator();
private NonContextualLobCreator() {
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ReaderInputStream.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ReaderInputStream.java
index 4c2fb9e248..9c6aa52573 100755
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ReaderInputStream.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ReaderInputStream.java
@@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.engine.jdbc;
+
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
@@ -33,11 +34,17 @@ import java.io.Reader;
*/
public class ReaderInputStream extends InputStream {
private Reader reader;
-
+
+ /**
+ * Constructs a ReaderInputStream from a Reader
+ *
+ * @param reader The reader to expose as an InputStream
+ */
public ReaderInputStream(Reader reader) {
this.reader = reader;
}
-
+
+ @Override
public int read() throws IOException {
return reader.read();
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java
index 4b0b21ea3f..d162fbb2a6 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java
@@ -44,10 +44,12 @@ import org.hibernate.internal.util.ClassLoaderHelper;
* @author Gail Badner
*/
public class ResultSetWrapperProxy implements InvocationHandler {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, ResultSetWrapperProxy.class.getName());
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ ResultSetWrapperProxy.class.getName()
+ );
private static final Class[] PROXY_INTERFACES = new Class[] { ResultSet.class };
- private static final SqlExceptionHelper sqlExceptionHelper = new SqlExceptionHelper();
+ private static final SqlExceptionHelper SQL_EXCEPTION_HELPER = new SqlExceptionHelper();
private final ResultSet rs;
private final ColumnNameCache columnNameCache;
@@ -65,7 +67,7 @@ public class ResultSetWrapperProxy implements InvocationHandler {
* @return The generated proxy.
*/
public static ResultSet generateProxy(ResultSet resultSet, ColumnNameCache columnNameCache) {
- return ( ResultSet ) Proxy.newProxyInstance(
+ return (ResultSet) Proxy.newProxyInstance(
getProxyClassLoader(),
PROXY_INTERFACES,
new ResultSetWrapperProxy( resultSet, columnNameCache )
@@ -90,26 +92,22 @@ public class ResultSetWrapperProxy implements InvocationHandler {
@SuppressWarnings( {"UnnecessaryBoxing"})
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ( "findColumn".equals( method.getName() ) ) {
- return Integer.valueOf( findColumn( ( String ) args[0] ) );
+ return Integer.valueOf( findColumn( (String) args[0] ) );
}
if ( isFirstArgColumnLabel( method, args ) ) {
try {
- int columnIndex = findColumn( ( String ) args[0] );
+ final int columnIndex = findColumn( (String) args[0] );
return invokeMethod(
- locateCorrespondingColumnIndexMethod( method ), buildColumnIndexMethodArgs( args, columnIndex )
+ locateCorrespondingColumnIndexMethod( method ),
+ buildColumnIndexMethodArgs( args, columnIndex )
);
}
catch ( SQLException ex ) {
- StringBuilder buf = new StringBuilder()
- .append( "Exception getting column index for column: [" )
- .append( args[0] )
- .append( "].\nReverting to using: [" )
- .append( args[0] )
- .append( "] as first argument for method: [" )
- .append( method )
- .append( "]" );
- sqlExceptionHelper.logExceptions( ex, buf.toString() );
+ final String msg = "Exception getting column index for column: [" + args[0] +
+ "].\nReverting to using: [" + args[0] +
+ "] as first argument for method: [" + method + "]";
+ SQL_EXCEPTION_HELPER.logExceptions( ex, msg );
}
catch ( NoSuchMethodException ex ) {
LOG.unableToSwitchToMethodUsingColumnIndex( method );
@@ -129,7 +127,7 @@ public class ResultSetWrapperProxy implements InvocationHandler {
return columnNameCache.getIndexForColumnName( columnName, rs );
}
- private boolean isFirstArgColumnLabel(Method method, Object args[]) {
+ private boolean isFirstArgColumnLabel(Method method, Object[] args) {
// method name should start with either get or update
if ( ! ( method.getName().startsWith( "get" ) || method.getName().startsWith( "update" ) ) ) {
return false;
@@ -158,7 +156,7 @@ public class ResultSetWrapperProxy implements InvocationHandler {
* @throws NoSuchMethodException Should never happen, but...
*/
private Method locateCorrespondingColumnIndexMethod(Method columnNameMethod) throws NoSuchMethodException {
- Class actualParameterTypes[] = new Class[columnNameMethod.getParameterTypes().length];
+ final Class[] actualParameterTypes = new Class[columnNameMethod.getParameterTypes().length];
actualParameterTypes[0] = int.class;
System.arraycopy(
columnNameMethod.getParameterTypes(),
@@ -172,13 +170,13 @@ public class ResultSetWrapperProxy implements InvocationHandler {
@SuppressWarnings( {"UnnecessaryBoxing"})
private Object[] buildColumnIndexMethodArgs(Object[] incomingArgs, int columnIndex) {
- Object actualArgs[] = new Object[incomingArgs.length];
+ final Object[] actualArgs = new Object[incomingArgs.length];
actualArgs[0] = Integer.valueOf( columnIndex );
System.arraycopy( incomingArgs, 1, actualArgs, 1, incomingArgs.length - 1 );
return actualArgs;
}
- private Object invokeMethod(Method method, Object args[]) throws Throwable {
+ private Object invokeMethod(Method method, Object[] args) throws Throwable {
try {
return method.invoke( rs, args );
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableBlobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableBlobProxy.java
index 0d8209ef72..37796b530c 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableBlobProxy.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableBlobProxy.java
@@ -43,7 +43,7 @@ import org.hibernate.internal.util.ClassLoaderHelper;
public class SerializableBlobProxy implements InvocationHandler, Serializable {
private static final Class[] PROXY_INTERFACES = new Class[] { Blob.class, WrappedBlob.class, Serializable.class };
- private transient final Blob blob;
+ private final transient Blob blob;
/**
* Builds a serializable {@link Blob} wrapper around the given {@link Blob}.
@@ -55,6 +55,11 @@ public class SerializableBlobProxy implements InvocationHandler, Serializable {
this.blob = blob;
}
+ /**
+ * Access to the wrapped Blob reference
+ *
+ * @return The wrapped Blob reference
+ */
public Blob getWrappedBlob() {
if ( blob == null ) {
throw new IllegalStateException( "Blobs may not be accessed after serialization" );
@@ -88,11 +93,7 @@ public class SerializableBlobProxy implements InvocationHandler, Serializable {
* @return The generated proxy.
*/
public static Blob generateProxy(Blob blob) {
- return ( Blob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new SerializableBlobProxy( blob )
- );
+ return (Blob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new SerializableBlobProxy( blob ) );
}
/**
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableClobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableClobProxy.java
index 8b499e5c25..f5a490ae14 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableClobProxy.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableClobProxy.java
@@ -43,7 +43,7 @@ import org.hibernate.internal.util.ClassLoaderHelper;
public class SerializableClobProxy implements InvocationHandler, Serializable {
private static final Class[] PROXY_INTERFACES = new Class[] { Clob.class, WrappedClob.class, Serializable.class };
- private transient final Clob clob;
+ private final transient Clob clob;
/**
* Builds a serializable {@link java.sql.Clob} wrapper around the given {@link java.sql.Clob}.
@@ -55,6 +55,11 @@ public class SerializableClobProxy implements InvocationHandler, Serializable {
this.clob = clob;
}
+ /**
+ * Access to the wrapped Clob reference
+ *
+ * @return The wrapped Clob reference
+ */
public Clob getWrappedClob() {
if ( clob == null ) {
throw new IllegalStateException( "Clobs may not be accessed after serialization" );
@@ -87,11 +92,7 @@ public class SerializableClobProxy implements InvocationHandler, Serializable {
* @return The generated proxy.
*/
public static Clob generateProxy(Clob clob) {
- return ( Clob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new SerializableClobProxy( clob )
- );
+ return (Clob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new SerializableClobProxy( clob ) );
}
/**
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableNClobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableNClobProxy.java
index cde389cb01..7044058392 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableNClobProxy.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableNClobProxy.java
@@ -35,6 +35,16 @@ import java.sql.NClob;
public class SerializableNClobProxy extends SerializableClobProxy {
private static final Class[] PROXY_INTERFACES = new Class[] { NClob.class, WrappedNClob.class };
+ /**
+ * Deprecated.
+ *
+ * @param clob The possible NClob reference
+ *
+ * @return {@code true} if the the Clob is a NClob as well
+ *
+ * @deprecated ORM baselines on JDK 1.6, so optional support for NClob (JDK 1,6 addition) is no longer needed.
+ */
+ @Deprecated
public static boolean isNClob(Clob clob) {
return NClob.class.isInstance( clob );
}
@@ -57,11 +67,7 @@ public class SerializableNClobProxy extends SerializableClobProxy {
* @return The generated proxy.
*/
public static NClob generateProxy(NClob nclob) {
- return ( NClob ) Proxy.newProxyInstance(
- getProxyClassLoader(),
- PROXY_INTERFACES,
- new SerializableNClobProxy( nclob )
- );
+ return (NClob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new SerializableNClobProxy( nclob ) );
}
/**
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/StreamUtils.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/StreamUtils.java
index 205030b03e..fd7f9178fa 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/StreamUtils.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/StreamUtils.java
@@ -35,14 +35,38 @@ import java.io.Writer;
* @author Steve Ebersole
*/
public class StreamUtils {
+ /**
+ * Default size to use for reading buffers.
+ */
public static final int DEFAULT_CHUNK_SIZE = 1024;
+ /**
+ * Copy the inputStream to the outputStream. Uses a buffer of the default size ({@link #DEFAULT_CHUNK_SIZE}).
+ *
+ * @param inputStream The input stream to read
+ * @param outputStream The output stream to write to
+ *
+ * @return The number of bytes read
+ *
+ * @throws IOException If a problem occurred accessing either stream
+ */
public static long copy(InputStream inputStream, OutputStream outputStream) throws IOException {
return copy( inputStream, outputStream, DEFAULT_CHUNK_SIZE );
}
+ /**
+ * Copy the inputStream to the outputStream using a buffer of the specified size
+ *
+ * @param inputStream The input stream to read
+ * @param outputStream The output stream to write to
+ * @param bufferSize The size of the buffer to use for reading
+ *
+ * @return The number of bytes read
+ *
+ * @throws IOException If a problem occurred accessing either stream
+ */
public static long copy(InputStream inputStream, OutputStream outputStream, int bufferSize) throws IOException {
- byte[] buffer = new byte[bufferSize];
+ final byte[] buffer = new byte[bufferSize];
long count = 0;
int n;
while ( -1 != ( n = inputStream.read( buffer ) ) ) {
@@ -50,15 +74,35 @@ public class StreamUtils {
count += n;
}
return count;
-
}
+ /**
+ * Copy the reader to the writer. Uses a buffer of the default size ({@link #DEFAULT_CHUNK_SIZE}).
+ *
+ * @param reader The reader to read from
+ * @param writer The writer to write to
+ *
+ * @return The number of bytes read
+ *
+ * @throws IOException If a problem occurred accessing reader or writer
+ */
public static long copy(Reader reader, Writer writer) throws IOException {
return copy( reader, writer, DEFAULT_CHUNK_SIZE );
}
+ /**
+ * Copy the reader to the writer using a buffer of the specified size
+ *
+ * @param reader The reader to read from
+ * @param writer The writer to write to
+ * @param bufferSize The size of the buffer to use for reading
+ *
+ * @return The number of bytes read
+ *
+ * @throws IOException If a problem occurred accessing either stream
+ */
public static long copy(Reader reader, Writer writer, int bufferSize) throws IOException {
- char[] buffer = new char[bufferSize];
+ final char[] buffer = new char[bufferSize];
long count = 0;
int n;
while ( -1 != ( n = reader.read( buffer ) ) ) {
@@ -66,6 +110,8 @@ public class StreamUtils {
count += n;
}
return count;
+ }
+ private StreamUtils() {
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/WrappedNClob.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/WrappedNClob.java
index 41c801e160..8e7d084a59 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/WrappedNClob.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/WrappedNClob.java
@@ -26,12 +26,24 @@ package org.hibernate.engine.jdbc;
import java.sql.NClob;
/**
+ * Contract for {@link NClob} wrappers.
+ *
* @author Steve Ebersole
*/
public interface WrappedNClob extends WrappedClob {
+ /**
+ * {@inheritDoc}
+ *
+ * @deprecated Use {@link #getWrappedNClob()} instead
+ */
@Override
@Deprecated
public NClob getWrappedClob();
+ /**
+ * Retrieve the wrapped {@link java.sql.Blob} reference
+ *
+ * @return The wrapped {@link java.sql.Blob} reference
+ */
public NClob getWrappedNClob();
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java
index 4d18551cde..bff82b93e0 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java
@@ -45,11 +45,14 @@ import org.hibernate.internal.CoreMessageLogger;
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
public abstract class AbstractBatchImpl implements Batch {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, AbstractBatchImpl.class.getName());
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ AbstractBatchImpl.class.getName()
+ );
private final BatchKey key;
private final JdbcCoordinator jdbcCoordinator;
+
private LinkedHashMap statements = new LinkedHashMap();
private LinkedHashSet observers = new LinkedHashSet();
@@ -191,7 +194,7 @@ public abstract class AbstractBatchImpl implements Batch {
@Override
public void release() {
- if ( getStatements() != null && !getStatements().isEmpty() ) {
+ if ( getStatements() != null && !getStatements().isEmpty() ) {
LOG.batchContainedStatementsOnRelease();
}
releaseStatements();
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java
index 0cff7e330a..32e085832c 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java
@@ -27,6 +27,8 @@ import org.hibernate.engine.jdbc.batch.spi.BatchKey;
import org.hibernate.jdbc.Expectation;
/**
+ * Normal implementation of BatchKey
+ *
* @author Steve Ebersole
*/
public class BasicBatchKey implements BatchKey {
@@ -34,19 +36,12 @@ public class BasicBatchKey implements BatchKey {
private final int statementCount;
private final Expectation expectation;
-// public BasicBatchKey(String comparison, int statementCount, Expectation expectation) {
-// this.comparison = comparison;
-// this.statementCount = statementCount;
-// this.expectations = new Expectation[statementCount];
-// Arrays.fill( this.expectations, expectation );
-// }
-//
-// public BasicBatchKey(String comparison, Expectation... expectations) {
-// this.comparison = comparison;
-// this.statementCount = expectations.length;
-// this.expectations = expectations;
-// }
-
+ /**
+ * Constructs a BasicBatchKey
+ *
+ * @param comparison A string used to compare batch keys.
+ * @param expectation The expectation for the batch
+ */
public BasicBatchKey(String comparison, Expectation expectation) {
this.comparison = comparison;
this.statementCount = 1;
@@ -72,13 +67,8 @@ public class BasicBatchKey implements BatchKey {
return false;
}
- BasicBatchKey that = (BasicBatchKey) o;
-
- if ( !comparison.equals( that.comparison ) ) {
- return false;
- }
-
- return true;
+ final BasicBatchKey that = (BasicBatchKey) o;
+ return comparison.equals( that.comparison );
}
@Override
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java
index 725f090124..1c46bb292d 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java
@@ -42,23 +42,34 @@ import org.hibernate.service.spi.Configurable;
* @author Steve Ebersole
*/
public class BatchBuilderImpl implements BatchBuilder, Configurable {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, BatchBuilderImpl.class.getName() );
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ BatchBuilderImpl.class.getName()
+ );
private int size;
+ /**
+ * Constructs a BatchBuilderImpl
+ */
public BatchBuilderImpl() {
}
+ /**
+ * Constructs a BatchBuilderImpl
+ *
+ * @param size The batch size to use.
+ */
+ public BatchBuilderImpl(int size) {
+ this.size = size;
+ }
+
@Override
public void configure(Map configurationValues) {
size = ConfigurationHelper.getInt( Environment.STATEMENT_BATCH_SIZE, configurationValues, size );
}
- public BatchBuilderImpl(int size) {
- this.size = size;
- }
-
+ @SuppressWarnings("UnusedDeclaration")
public void setJdbcBatchSize(int size) {
this.size = size;
}
@@ -73,12 +84,14 @@ public class BatchBuilderImpl implements BatchBuilder, Configurable {
@Override
public String getManagementDomain() {
- return null; // use Hibernate default domain
+ // use Hibernate default domain
+ return null;
}
@Override
public String getManagementServiceType() {
- return null; // use Hibernate default scheme
+ // use Hibernate default scheme
+ return null;
}
@Override
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderInitiator.java
index ab001aeeb9..e90eeb4735 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderInitiator.java
@@ -39,7 +39,14 @@ import org.hibernate.service.spi.ServiceRegistryImplementor;
* @author Steve Ebersole
*/
public class BatchBuilderInitiator implements StandardServiceInitiator {
+ /**
+ * Singleton access
+ */
public static final BatchBuilderInitiator INSTANCE = new BatchBuilderInitiator();
+
+ /**
+ * Names the BatchBuilder implementation to use.
+ */
public static final String BUILDER = "hibernate.jdbc.batch.builder";
@Override
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java
index 4af15f8562..dc948c6596 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java
@@ -40,8 +40,10 @@ import org.hibernate.internal.CoreMessageLogger;
* @author Steve Ebersole
*/
public class BatchingBatch extends AbstractBatchImpl {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, BatchingBatch.class.getName() );
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ BatchingBatch.class.getName()
+ );
// IMPL NOTE : Until HHH-5797 is fixed, there will only be 1 statement in a batch
@@ -49,6 +51,13 @@ public class BatchingBatch extends AbstractBatchImpl {
private int batchPosition;
private int statementPosition;
+ /**
+ * Constructs a BatchingBatch
+ *
+ * @param key The batch key
+ * @param jdbcCoordinator The JDBC jdbcCoordinator
+ * @param batchSize The batch size.
+ */
public BatchingBatch(
BatchKey key,
JdbcCoordinator jdbcCoordinator,
@@ -125,7 +134,7 @@ public class BatchingBatch extends AbstractBatchImpl {
}
private void checkRowCounts(int[] rowCounts, PreparedStatement ps) throws SQLException, HibernateException {
- int numberOfRowCounts = rowCounts.length;
+ final int numberOfRowCounts = rowCounts.length;
if ( numberOfRowCounts != batchPosition ) {
LOG.unexpectedRowCounts();
}
@@ -133,4 +142,4 @@ public class BatchingBatch extends AbstractBatchImpl {
getKey().getExpectation().verifyOutcome( rowCounts[i], ps, i );
}
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java
index 54de89428b..09cbf753c3 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java
@@ -40,8 +40,10 @@ import org.hibernate.internal.CoreMessageLogger;
* @author Steve Ebersole
*/
public class NonBatchingBatch extends AbstractBatchImpl {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, NonBatchingBatch.class.getName() );
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ NonBatchingBatch.class.getName()
+ );
private JdbcCoordinator jdbcCoordinator;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/package-info.java
new file mode 100644
index 0000000000..09bc7430f0
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Internals for JDBC batching support.
+ */
+package org.hibernate.engine.jdbc.batch.internal;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/spi/package-info.java
new file mode 100644
index 0000000000..3719ea4ba8
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/spi/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines contracts for JDBC batching support.
+ */
+package org.hibernate.engine.jdbc.batch.spi;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java
index e372021080..b458dd2ce3 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java
@@ -32,36 +32,49 @@ import java.util.Map;
import java.util.Properties;
import java.util.Set;
-import org.jboss.logging.Logger;
-
import org.hibernate.HibernateException;
import org.hibernate.MultiTenancyStrategy;
import org.hibernate.boot.registry.StandardServiceInitiator;
-import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
+import org.hibernate.boot.registry.selector.spi.StrategySelector;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.beans.BeanInfoHelper;
import org.hibernate.service.spi.ServiceRegistryImplementor;
+import org.jboss.logging.Logger;
/**
* Instantiates and configures an appropriate {@link ConnectionProvider}.
*
* @author Gavin King
* @author Steve Ebersole
+ * @author Brett Meyer
*/
public class ConnectionProviderInitiator implements StandardServiceInitiator {
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ ConnectionProviderInitiator.class.getName()
+ );
+
+ /**
+ * Singleton access
+ */
public static final ConnectionProviderInitiator INSTANCE = new ConnectionProviderInitiator();
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class,
- ConnectionProviderInitiator.class.getName());
- public static final String C3P0_PROVIDER_CLASS_NAME =
- "org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider";
+ /**
+ * The strategy for c3p0 connection pooling
+ */
+ public static final String C3P0_STRATEGY = "c3p0";
- public static final String PROXOOL_PROVIDER_CLASS_NAME =
- "org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider";
+ /**
+ * The strategy for proxool connection pooling
+ */
+ public static final String PROXOOL_STRATEGY = "proxool";
+ /**
+ * No idea. Is this even still used?
+ */
public static final String INJECTION_DATA = "hibernate.connection_provider.injection_data";
// mapping from legacy connection provider name to actual
@@ -83,14 +96,6 @@ public class ConnectionProviderInitiator implements StandardServiceInitiator properties) {
- Properties result = new Properties();
+ final Properties result = new Properties();
for ( Map.Entry entry : properties.entrySet() ) {
if ( ! ( String.class.isInstance( entry.getKey() ) ) || ! String.class.isInstance( entry.getValue() ) ) {
continue;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DatasourceConnectionProviderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DatasourceConnectionProviderImpl.java
index f3428d5373..0df5921f5b 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DatasourceConnectionProviderImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DatasourceConnectionProviderImpl.java
@@ -50,7 +50,6 @@ import org.hibernate.service.spi.Stoppable;
* @author Steve Ebersole
*/
public class DatasourceConnectionProviderImpl implements ConnectionProvider, Configurable, Stoppable {
-
private DataSource dataSource;
private String user;
private String pass;
@@ -68,6 +67,7 @@ public class DatasourceConnectionProviderImpl implements ConnectionProvider, Con
}
@InjectService( required = false )
+ @SuppressWarnings("UnusedDeclaration")
public void setJndiService(JndiService jndiService) {
this.jndiService = jndiService;
}
@@ -94,9 +94,7 @@ public class DatasourceConnectionProviderImpl implements ConnectionProvider, Con
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public void configure(Map configValues) {
if ( this.dataSource == null ) {
final Object dataSource = configValues.get( Environment.DATASOURCE );
@@ -127,14 +125,13 @@ public class DatasourceConnectionProviderImpl implements ConnectionProvider, Con
available = true;
}
+ @Override
public void stop() {
available = false;
dataSource = null;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Connection getConnection() throws SQLException {
if ( !available ) {
throw new HibernateException( "Provider is closed!" );
@@ -142,16 +139,12 @@ public class DatasourceConnectionProviderImpl implements ConnectionProvider, Con
return useCredentials ? dataSource.getConnection( user, pass ) : dataSource.getConnection();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public void closeConnection(Connection connection) throws SQLException {
connection.close();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean supportsAggressiveRelease() {
return true;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DriverManagerConnectionProviderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DriverManagerConnectionProviderImpl.java
index 809162d896..9ad85c0803 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DriverManagerConnectionProviderImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DriverManagerConnectionProviderImpl.java
@@ -98,11 +98,12 @@ public class DriverManagerConnectionProviderImpl
throw new UnknownUnwrapTypeException( unwrapType );
}
}
+
@Override
public void configure(Map configurationValues) {
LOG.usingHibernateBuiltInConnectionPool();
- String driverClassName = (String) configurationValues.get( AvailableSettings.DRIVER );
+ final String driverClassName = (String) configurationValues.get( AvailableSettings.DRIVER );
if ( driverClassName == null ) {
LOG.jdbcDriverNotSpecified( AvailableSettings.DRIVER );
}
@@ -135,19 +136,21 @@ public class DriverManagerConnectionProviderImpl
}
}
- poolSize = ConfigurationHelper.getInt( AvailableSettings.POOL_SIZE, configurationValues, 20 ); // default pool size 20
+ // default pool size 20
+ poolSize = ConfigurationHelper.getInt( AvailableSettings.POOL_SIZE, configurationValues, 20 );
LOG.hibernateConnectionPoolSize( poolSize );
autocommit = ConfigurationHelper.getBoolean( AvailableSettings.AUTOCOMMIT, configurationValues );
LOG.autoCommitMode( autocommit );
isolation = ConfigurationHelper.getInteger( AvailableSettings.ISOLATION, configurationValues );
- if ( isolation != null )
+ if ( isolation != null ) {
LOG.jdbcIsolationLevel( Environment.isolationLevelToString( isolation.intValue() ) );
+ }
url = (String) configurationValues.get( AvailableSettings.URL );
if ( url == null ) {
- String msg = LOG.jdbcUrlNotSpecified( AvailableSettings.URL );
+ final String msg = LOG.jdbcUrlNotSpecified( AvailableSettings.URL );
LOG.error( msg );
throw new HibernateException( msg );
}
@@ -156,11 +159,14 @@ public class DriverManagerConnectionProviderImpl
LOG.usingDriver( driverClassName, url );
// if debug level is enabled, then log the password, otherwise mask it
- if ( debugEnabled )
+ if ( debugEnabled ) {
LOG.connectionProperties( connectionProps );
- else
+ }
+ else {
LOG.connectionProperties( ConfigurationHelper.maskOut( connectionProps, "password" ) );
+ }
}
+
@Override
public void stop() {
LOG.cleaningUpConnectionPool( url );
@@ -176,16 +182,20 @@ public class DriverManagerConnectionProviderImpl
pool.clear();
stopped = true;
}
+
@Override
public Connection getConnection() throws SQLException {
if ( traceEnabled ) LOG.tracev( "Total checked-out connections: {0}", checkedOut.intValue() );
+
// essentially, if we have available connections in the pool, use one...
synchronized (pool) {
if ( !pool.isEmpty() ) {
- int last = pool.size() - 1;
- if ( traceEnabled ) LOG.tracev( "Using pooled JDBC connection, pool size: {0}", last );
- Connection pooled = pool.remove( last );
+ final int last = pool.size() - 1;
+ if ( traceEnabled ) {
+ LOG.tracev( "Using pooled JDBC connection, pool size: {0}", last );
+ }
+ final Connection pooled = pool.remove( last );
if ( isolation != null ) {
pooled.setTransactionIsolation( isolation.intValue() );
}
@@ -199,9 +209,11 @@ public class DriverManagerConnectionProviderImpl
// otherwise we open a new connection...
final boolean debugEnabled = LOG.isDebugEnabled();
- if ( debugEnabled ) LOG.debug( "Opening new JDBC connection" );
+ if ( debugEnabled ) {
+ LOG.debug( "Opening new JDBC connection" );
+ }
- Connection conn;
+ final Connection conn;
if ( driver != null ) {
// If a Driver is available, completely circumvent
// DriverManager#getConnection. It attempts to double check
@@ -218,7 +230,7 @@ public class DriverManagerConnectionProviderImpl
conn.setTransactionIsolation( isolation.intValue() );
}
if ( conn.getAutoCommit() != autocommit ) {
- conn.setAutoCommit(autocommit);
+ conn.setAutoCommit( autocommit );
}
if ( debugEnabled ) {
@@ -228,14 +240,17 @@ public class DriverManagerConnectionProviderImpl
checkedOut.incrementAndGet();
return conn;
}
+
@Override
public void closeConnection(Connection conn) throws SQLException {
checkedOut.decrementAndGet();
// add to the pool if the max size is not yet reached.
synchronized ( pool ) {
- int currentSize = pool.size();
+ final int currentSize = pool.size();
if ( currentSize < poolSize ) {
- if ( traceEnabled ) LOG.tracev( "Returning connection to pool, pool size: {0}", ( currentSize + 1 ) );
+ if ( traceEnabled ) {
+ LOG.tracev( "Returning connection to pool, pool size: {0}", ( currentSize + 1 ) );
+ }
pool.add( conn );
return;
}
@@ -251,6 +266,7 @@ public class DriverManagerConnectionProviderImpl
}
super.finalize();
}
+
@Override
public boolean supportsAggressiveRelease() {
return false;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/MultiTenantConnectionProviderInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/MultiTenantConnectionProviderInitiator.java
index ec8aae21d2..03952a0b4d 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/MultiTenantConnectionProviderInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/MultiTenantConnectionProviderInitiator.java
@@ -38,12 +38,18 @@ import org.hibernate.service.spi.ServiceException;
import org.hibernate.service.spi.ServiceRegistryImplementor;
/**
+ * A service initiator for the MultiTenantConnectionProvider service
+ *
* @author Steve Ebersole
*/
public class MultiTenantConnectionProviderInitiator implements StandardServiceInitiator {
- public static final MultiTenantConnectionProviderInitiator INSTANCE = new MultiTenantConnectionProviderInitiator();
private static final Logger log = Logger.getLogger( MultiTenantConnectionProviderInitiator.class );
+ /**
+ * Singleton access
+ */
+ public static final MultiTenantConnectionProviderInitiator INSTANCE = new MultiTenantConnectionProviderInitiator();
+
@Override
public Class getServiceInitiated() {
return MultiTenantConnectionProvider.class;
@@ -55,6 +61,7 @@ public class MultiTenantConnectionProviderInitiator implements StandardServiceIn
final MultiTenancyStrategy strategy = MultiTenancyStrategy.determineMultiTenancyStrategy( configurationValues );
if ( strategy == MultiTenancyStrategy.NONE || strategy == MultiTenancyStrategy.DISCRIMINATOR ) {
// nothing to do, but given the separate hierarchies have to handle this here.
+ return null;
}
final Object configValue = configurationValues.get( AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER );
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/package-info.java
new file mode 100644
index 0000000000..397a72a46f
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Internals for accessing JDBC Connections
+ */
+package org.hibernate.engine.jdbc.connections.internal;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/ConnectionProvider.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/ConnectionProvider.java
index 762d5b4613..ea47422c5e 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/ConnectionProvider.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/ConnectionProvider.java
@@ -25,7 +25,6 @@ package org.hibernate.engine.jdbc.connections.spi;
import java.sql.Connection;
import java.sql.SQLException;
-import org.hibernate.HibernateException;
import org.hibernate.service.Service;
import org.hibernate.service.spi.Wrapped;
@@ -46,7 +45,7 @@ public interface ConnectionProvider extends Service, Wrapped {
* @return The obtained JDBC connection
*
* @throws SQLException Indicates a problem opening a connection
- * @throws HibernateException Indicates a problem otherwise obtaining a connection.
+ * @throws org.hibernate.HibernateException Indicates a problem otherwise obtaining a connection.
*/
public Connection getConnection() throws SQLException;
@@ -56,7 +55,7 @@ public interface ConnectionProvider extends Service, Wrapped {
* @param conn The JDBC connection to release
*
* @throws SQLException Indicates a problem closing the connection
- * @throws HibernateException Indicates a problem otherwise releasing a connection.
+ * @throws org.hibernate.HibernateException Indicates a problem otherwise releasing a connection.
*/
public void closeConnection(Connection conn) throws SQLException;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/DataSourceBasedMultiTenantConnectionProviderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/DataSourceBasedMultiTenantConnectionProviderImpl.java
index cb387f1421..e13325ce77 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/DataSourceBasedMultiTenantConnectionProviderImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/DataSourceBasedMultiTenantConnectionProviderImpl.java
@@ -56,6 +56,9 @@ public class DataSourceBasedMultiTenantConnectionProviderImpl
extends AbstractDataSourceBasedMultiTenantConnectionProviderImpl
implements ServiceRegistryAwareService, Stoppable {
+ /**
+ * Identifies the DataSource name to use for {@link #selectAnyDataSource} handling
+ */
public static final String TENANT_IDENTIFIER_TO_USE_FOR_ANY_KEY = "hibernate.multi_tenant.datasource.identifier_for_any";
private Map dataSourceMap;
@@ -100,13 +103,13 @@ public class DataSourceBasedMultiTenantConnectionProviderImpl
throw new HibernateException( "Could not locate JndiService from DataSourceBasedMultiTenantConnectionProviderImpl" );
}
- Object namedObject = jndiService.locate( jndiName );
+ final Object namedObject = jndiService.locate( jndiName );
if ( namedObject == null ) {
throw new HibernateException( "JNDI name [" + jndiName + "] could not be resolved" );
}
if ( DataSource.class.isInstance( namedObject ) ) {
- int loc = jndiName.lastIndexOf( "/" );
+ final int loc = jndiName.lastIndexOf( "/" );
this.baseJndiNamespace = jndiName.substring( 0, loc );
this.tenantIdentifierForAny = jndiName.substring( loc + 1 );
dataSourceMap().put( tenantIdentifierForAny, (DataSource) namedObject );
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/MultiTenantConnectionProvider.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/MultiTenantConnectionProvider.java
index 860d926c0b..b9fe64dff3 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/MultiTenantConnectionProvider.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/MultiTenantConnectionProvider.java
@@ -30,6 +30,9 @@ import org.hibernate.service.Service;
import org.hibernate.service.spi.Wrapped;
/**
+ * A specialized Connection provider contract used when the application is using multi-tenancy support requiring
+ * tenant aware connections.
+ *
* @author Steve Ebersole
*/
public interface MultiTenantConnectionProvider extends Service, Wrapped {
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/package-info.java
new file mode 100644
index 0000000000..84342f8c58
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines contracts for accessing JDBC Connections
+ */
+package org.hibernate.engine.jdbc.connections.spi;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/RefCursorSupportInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/RefCursorSupportInitiator.java
index 2a74fe146e..ba02e87a78 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/RefCursorSupportInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/RefCursorSupportInitiator.java
@@ -30,9 +30,14 @@ import org.hibernate.engine.jdbc.cursor.spi.RefCursorSupport;
import org.hibernate.service.spi.ServiceRegistryImplementor;
/**
+ * Service initiator for RefCursorSupport service
+ *
* @author Steve Ebersole
*/
public class RefCursorSupportInitiator implements StandardServiceInitiator {
+ /**
+ * Singleton access
+ */
public static final RefCursorSupportInitiator INSTANCE = new RefCursorSupportInitiator();
@Override
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java
index 056d06bd69..4e00bb9296 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java
@@ -39,6 +39,8 @@ import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.service.spi.InjectService;
/**
+ * Standard implementation of RefCursorSupport
+ *
* @author Steve Ebersole
*/
public class StandardRefCursorSupport implements RefCursorSupport {
@@ -46,6 +48,11 @@ public class StandardRefCursorSupport implements RefCursorSupport {
private JdbcServices jdbcServices;
+ /**
+ * Hook for service registry to be able to inject JdbcServices
+ *
+ * @param jdbcServices The JdbcServices service
+ */
@InjectService
@SuppressWarnings("UnusedDeclaration")
public void injectJdbcServices(JdbcServices jdbcServices) {
@@ -160,6 +167,13 @@ public class StandardRefCursorSupport implements RefCursorSupport {
}
}
+ /**
+ * Does this JDBC metadata indicate that the driver defines REF_CURSOR support?
+ *
+ * @param meta The JDBC metadata
+ *
+ * @return {@code true} if the metadata indicates that the driver defines REF_CURSOR support
+ */
@SuppressWarnings("UnnecessaryUnboxing")
public static boolean supportsRefCursors(DatabaseMetaData meta) {
// Standard JDBC REF_CURSOR support was not added until Java 8, so we need to use reflection to attempt to
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/package-info.java
new file mode 100644
index 0000000000..211dbd1302
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Internals for JDBC REF_CURSOR support.
+ */
+package org.hibernate.engine.jdbc.cursor.internal;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/RefCursorSupport.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/RefCursorSupport.java
index 7785f0954f..ad7263e752 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/RefCursorSupport.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/RefCursorSupport.java
@@ -29,6 +29,8 @@ import java.sql.ResultSet;
import org.hibernate.service.Service;
/**
+ * Contract for JDBC REF_CURSOR support.
+ *
* @author Steve Ebersole
*/
public interface RefCursorSupport extends Service {
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/package-info.java
new file mode 100644
index 0000000000..6f9a0e635c
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines contracts for JDBC REF_CURSOR support.
+ */
+package org.hibernate.engine.jdbc.cursor.spi;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/BasicDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/BasicDialectResolver.java
index fb617d72c2..b96c41ee28 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/BasicDialectResolver.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/BasicDialectResolver.java
@@ -40,22 +40,39 @@ import org.hibernate.engine.jdbc.dialect.spi.AbstractDatabaseMetaDataDialectReso
*/
@Deprecated
public class BasicDialectResolver extends AbstractDatabaseMetaDataDialectResolver {
+ /**
+ * Constant indicating no version info was given
+ */
public static final int VERSION_INSENSITIVE_VERSION = -9999;
private final String matchingName;
private final int matchingVersion;
private final Class dialectClass;
+ /**
+ * Constructs a BasicDialectResolver
+ *
+ * @param matchingName The name of the driver to match on
+ * @param dialectClass The Dialect class to use on match
+ */
public BasicDialectResolver(String matchingName, Class dialectClass) {
this( matchingName, VERSION_INSENSITIVE_VERSION, dialectClass );
}
+ /**
+ * Constructs a BasicDialectResolver
+ *
+ * @param matchingName The name of the driver to match on
+ * @param matchingVersion The version of the driver to match on
+ * @param dialectClass The Dialect class to use on match
+ */
public BasicDialectResolver(String matchingName, int matchingVersion, Class dialectClass) {
this.matchingName = matchingName;
this.matchingVersion = matchingVersion;
this.dialectClass = dialectClass;
}
+ @Override
protected final Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException {
final String databaseName = metaData.getDatabaseProductName();
final int databaseMajorVersion = metaData.getDatabaseMajorVersion();
@@ -63,7 +80,7 @@ public class BasicDialectResolver extends AbstractDatabaseMetaDataDialectResolve
if ( matchingName.equalsIgnoreCase( databaseName )
&& ( matchingVersion == VERSION_INSENSITIVE_VERSION || matchingVersion == databaseMajorVersion ) ) {
try {
- return ( Dialect ) dialectClass.newInstance();
+ return (Dialect) dialectClass.newInstance();
}
catch ( HibernateException e ) {
// conceivable that the dialect ctor could throw HibernateExceptions, so don't re-wrap
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverInitiator.java
index 9ad43d9ca2..3fb14158d0 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverInitiator.java
@@ -35,9 +35,14 @@ import org.hibernate.service.spi.ServiceException;
import org.hibernate.service.spi.ServiceRegistryImplementor;
/**
+ * Initiator for the DatabaseInfoDialectResolver service
+ *
* @author Steve Ebersole
*/
public class DatabaseInfoDialectResolverInitiator implements StandardServiceInitiator {
+ /**
+ * Singleton access
+ */
public static final DatabaseInfoDialectResolverInitiator INSTANCE = new DatabaseInfoDialectResolverInitiator();
@Override
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverSet.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverSet.java
index d3816ccd69..d9149a9195 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverSet.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverSet.java
@@ -31,19 +31,36 @@ import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.dialect.spi.DatabaseInfoDialectResolver;
/**
+ * Implements the DatabaseInfoDialectResolver as a chain, allowing multiple delegate DatabaseInfoDialectResolver
+ * implementations to coordinate resolution
+ *
* @author Steve Ebersole
*/
public class DatabaseInfoDialectResolverSet implements DatabaseInfoDialectResolver {
private List delegateResolvers;
+ /**
+ * Constructs a DatabaseInfoDialectResolverSet
+ */
public DatabaseInfoDialectResolverSet() {
this( new ArrayList() );
}
+ /**
+ * Constructs a DatabaseInfoDialectResolverSet
+ *
+ * @param delegateResolvers The set of delegate resolvers
+ */
public DatabaseInfoDialectResolverSet(List delegateResolvers) {
this.delegateResolvers = delegateResolvers;
}
+ /**
+ * Constructs a DatabaseInfoDialectResolverSet
+ *
+ * @param delegateResolvers The set of delegate resolvers
+ */
+ @SuppressWarnings("UnusedDeclaration")
public DatabaseInfoDialectResolverSet(DatabaseInfoDialectResolver... delegateResolvers) {
this( Arrays.asList( delegateResolvers ) );
}
@@ -51,7 +68,7 @@ public class DatabaseInfoDialectResolverSet implements DatabaseInfoDialectResolv
@Override
public Dialect resolve(DatabaseInfo databaseInfo) {
for ( DatabaseInfoDialectResolver resolver : delegateResolvers ) {
- Dialect dialect = resolver.resolve( databaseInfo );
+ final Dialect dialect = resolver.resolve( databaseInfo );
if ( dialect != null ) {
return dialect;
}
@@ -75,6 +92,7 @@ public class DatabaseInfoDialectResolverSet implements DatabaseInfoDialectResolv
*
* @param resolver The resolver to add.
*/
+ @SuppressWarnings("UnusedDeclaration")
public void addResolverAtFirst(DatabaseInfoDialectResolver resolver) {
delegateResolvers.add( 0, resolver );
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectFactoryInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectFactoryInitiator.java
index a207465656..26e67f3bfa 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectFactoryInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectFactoryInitiator.java
@@ -35,6 +35,9 @@ import org.hibernate.service.spi.ServiceRegistryImplementor;
* @author Steve Ebersole
*/
public class DialectFactoryInitiator implements StandardServiceInitiator {
+ /**
+ * Singleton access
+ */
public static final DialectFactoryInitiator INSTANCE = new DialectFactoryInitiator();
@Override
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectResolverSet.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectResolverSet.java
index fc0e4d34f0..81e3cf3be0 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectResolverSet.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectResolverSet.java
@@ -40,29 +40,51 @@ import org.hibernate.internal.CoreMessageLogger;
*
* @author Tomoto Shimizu Washio
* @author Steve Ebersole
+ *
+ * @deprecated See deprecation on {@link DialectResolver}
*/
+@Deprecated
public class DialectResolverSet implements DialectResolver {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, DialectResolverSet.class.getName());
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ DialectResolverSet.class.getName()
+ );
private List resolvers;
+ /**
+ * Deprecated
+ */
public DialectResolverSet() {
this( new ArrayList() );
+ LOG.debug( "DialectResolverSet is deprecated" );
}
+ /**
+ * Deprecated
+ *
+ * @param resolvers The delegate resolvers
+ */
public DialectResolverSet(List resolvers) {
this.resolvers = resolvers;
+ LOG.debug( "DialectResolverSet is deprecated" );
}
+ /**
+ * Deprecated
+ *
+ * @param resolvers The delegate resolvers
+ */
public DialectResolverSet(DialectResolver... resolvers) {
this( Arrays.asList( resolvers ) );
+ LOG.debug( "DialectResolverSet is deprecated" );
}
+ @Override
public Dialect resolveDialect(DatabaseMetaData metaData) throws JDBCConnectionException {
for ( DialectResolver resolver : resolvers ) {
try {
- Dialect dialect = resolver.resolveDialect( metaData );
+ final Dialect dialect = resolver.resolveDialect( metaData );
if ( dialect != null ) {
return dialect;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseInfoDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseInfoDialectResolver.java
index 814c1dd4b1..6b70e520b3 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseInfoDialectResolver.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseInfoDialectResolver.java
@@ -54,9 +54,14 @@ import org.hibernate.engine.jdbc.dialect.spi.DatabaseInfoDialectResolver;
import org.hibernate.internal.CoreMessageLogger;
/**
+ * The standard DatabaseInfoDialectResolver implementation
+ *
* @author Steve Ebersole
*/
public class StandardDatabaseInfoDialectResolver implements DatabaseInfoDialectResolver {
+ /**
+ * Singleton access
+ */
public static final StandardDatabaseInfoDialectResolver INSTANCE = new StandardDatabaseInfoDialectResolver();
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
@@ -159,7 +164,7 @@ public class StandardDatabaseInfoDialectResolver implements DatabaseInfoDialectR
return new InformixDialect();
}
- if ( databaseName.equals("DB2 UDB for AS/400" ) ) {
+ if ( "DB2 UDB for AS/400".equals( databaseName ) ) {
return new DB2400Dialect();
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java
index 2cf8b5cd97..ca2406fe07 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java
@@ -27,7 +27,7 @@ import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import org.hibernate.dialect.Dialect;
-import org.hibernate.dialect.resolver.BasicSQLExceptionConverter;
+import org.hibernate.engine.jdbc.dialect.spi.BasicSQLExceptionConverter;
import org.hibernate.engine.jdbc.dialect.spi.AbstractDatabaseMetaDataDialectResolver;
import org.hibernate.engine.jdbc.dialect.spi.DatabaseInfoDialectResolver;
@@ -39,14 +39,22 @@ import org.hibernate.engine.jdbc.dialect.spi.DatabaseInfoDialectResolver;
public class StandardDatabaseMetaDataDialectResolver extends AbstractDatabaseMetaDataDialectResolver {
private final DatabaseInfoDialectResolver infoResolver;
+ /**
+ * Constructs a StandardDatabaseMetaDataDialectResolver
+ *
+ * @param infoResolver The delegate resolver
+ */
public StandardDatabaseMetaDataDialectResolver(DatabaseInfoDialectResolver infoResolver) {
this.infoResolver = infoResolver;
}
+ /**
+ * A DatabaseInfo implementation wrapping a JDBC DatabaseMetaData reference
+ */
public static final class DatabaseInfoImpl implements DatabaseInfoDialectResolver.DatabaseInfo {
private final DatabaseMetaData databaseMetaData;
- public DatabaseInfoImpl(DatabaseMetaData databaseMetaData) {
+ protected DatabaseInfoImpl(DatabaseMetaData databaseMetaData) {
this.databaseMetaData = databaseMetaData;
}
@@ -82,7 +90,7 @@ public class StandardDatabaseMetaDataDialectResolver extends AbstractDatabaseMet
}
@Override
- protected Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException {
+ protected Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException {
if ( infoResolver == null ) {
return null;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/package-info.java
new file mode 100644
index 0000000000..dc8bdcc5d5
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Internal support for Dialect resolution (from JDBC metadata) and Dialect building.
+ */
+package org.hibernate.engine.jdbc.dialect.internal;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java
index b6db70494a..5226dfe8dd 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java
@@ -30,7 +30,6 @@ import org.jboss.logging.Logger;
import org.hibernate.JDBCException;
import org.hibernate.dialect.Dialect;
-import org.hibernate.dialect.resolver.BasicSQLExceptionConverter;
import org.hibernate.exception.JDBCConnectionException;
import org.hibernate.internal.CoreMessageLogger;
@@ -41,8 +40,7 @@ import org.hibernate.internal.CoreMessageLogger;
* @author Steve Ebersole
*/
public abstract class AbstractDatabaseMetaDataDialectResolver implements DialectResolver {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class,
AbstractDatabaseMetaDataDialectResolver.class.getName()
);
@@ -53,21 +51,22 @@ public abstract class AbstractDatabaseMetaDataDialectResolver implements Dialect
* Here we template the resolution, delegating to {@link #resolveDialectInternal} and handling
* {@link java.sql.SQLException}s properly.
*/
+ @Override
public final Dialect resolveDialect(DatabaseMetaData metaData) {
try {
return resolveDialectInternal( metaData );
}
catch ( SQLException sqlException ) {
- JDBCException jdbcException = BasicSQLExceptionConverter.INSTANCE.convert( sqlException );
- if (jdbcException instanceof JDBCConnectionException) {
+ final JDBCException jdbcException = BasicSQLExceptionConverter.INSTANCE.convert( sqlException );
+ if (jdbcException instanceof JDBCConnectionException) {
throw jdbcException;
}
- LOG.warnf( "%s : %s", BasicSQLExceptionConverter.MSG, sqlException.getMessage() );
- return null;
+ LOG.warnf( "%s : %s", BasicSQLExceptionConverter.MSG, sqlException.getMessage() );
+ return null;
}
catch ( Throwable t ) {
- LOG.unableToExecuteResolver( this, t.getMessage() );
+ LOG.unableToExecuteResolver( this, t.getMessage() );
return null;
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/resolver/BasicSQLExceptionConverter.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/BasicSQLExceptionConverter.java
similarity index 89%
rename from hibernate-core/src/main/java/org/hibernate/dialect/resolver/BasicSQLExceptionConverter.java
rename to hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/BasicSQLExceptionConverter.java
index 52defca1de..ea554a052d 100644
--- a/hibernate-core/src/main/java/org/hibernate/dialect/resolver/BasicSQLExceptionConverter.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/BasicSQLExceptionConverter.java
@@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.dialect.resolver;
+package org.hibernate.engine.jdbc.dialect.spi;
import java.sql.SQLException;
import org.jboss.logging.Logger;
@@ -33,13 +33,25 @@ import org.hibernate.internal.CoreMessageLogger;
/**
* A helper to centralize conversion of {@link java.sql.SQLException}s to {@link org.hibernate.JDBCException}s.
+ *
+ * Used while querying JDBC metadata during bootstrapping
*
* @author Steve Ebersole
*/
public class BasicSQLExceptionConverter {
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ BasicSQLExceptionConverter.class.getName()
+ );
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, BasicSQLExceptionConverter.class.getName() );
+ /**
+ * Singleton access
+ */
public static final BasicSQLExceptionConverter INSTANCE = new BasicSQLExceptionConverter();
+
+ /**
+ * Message
+ */
public static final String MSG = LOG.unableToQueryDatabaseMetadata();
private static final SQLStateConverter CONVERTER = new SQLStateConverter( new ConstraintNameExtracter() );
@@ -58,6 +70,7 @@ public class BasicSQLExceptionConverter {
/**
* {@inheritDoc}
*/
+ @Override
public String extractConstraintName(SQLException sqle) {
return "???";
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DatabaseInfoDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DatabaseInfoDialectResolver.java
index 9eccc26347..a532e35389 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DatabaseInfoDialectResolver.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DatabaseInfoDialectResolver.java
@@ -42,7 +42,13 @@ public interface DatabaseInfoDialectResolver extends Service {
*/
public Dialect resolve(DatabaseInfo databaseInfo);
+ /**
+ * Essentially a "parameter object" for {@link DatabaseInfoDialectResolver#resolve}
+ */
public static interface DatabaseInfo {
+ /**
+ * Constant used to indicate that no version is defined
+ */
public static final int NO_VERSION = -9999;
/**
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DialectResolver.java
index 4cec52fa7b..0fca0dfcc6 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DialectResolver.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DialectResolver.java
@@ -24,8 +24,13 @@
package org.hibernate.engine.jdbc.dialect.spi;
/**
+ * Deprecated
+ *
* @deprecated Deprecated in favor of {@link DatabaseMetaDataDialectResolver} to account for resolving by name versus
* by DatabaseMetaData
+ *
+ * @see DatabaseMetaDataDialectResolver
+ * @see DatabaseInfoDialectResolver
*/
@Deprecated
public interface DialectResolver extends DatabaseMetaDataDialectResolver {
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/package-info.java
new file mode 100644
index 0000000000..53a64d46e9
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Contracts supporting Dialect resolution (from JDBC metadata) and Dialect building.
+ */
+package org.hibernate.engine.jdbc.dialect.spi;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BasicFormatterImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BasicFormatterImpl.java
index 0b2babef47..f0fd816b7b 100755
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BasicFormatterImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BasicFormatterImpl.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -20,7 +20,6 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
- *
*/
package org.hibernate.engine.jdbc.internal;
@@ -84,23 +83,24 @@ public class BasicFormatterImpl implements Formatter {
MISC.add( "on" );
}
- static final String indentString = " ";
- static final String initial = "\n ";
+ private static final String INDENT_STRING = " ";
+ private static final String INITIAL = "\n ";
+ @Override
public String format(String source) {
return new FormatProcess( source ).perform();
}
private static class FormatProcess {
boolean beginLine = true;
- boolean afterBeginBeforeEnd = false;
- boolean afterByOrSetOrFromOrSelect = false;
- boolean afterValues = false;
- boolean afterOn = false;
- boolean afterBetween = false;
- boolean afterInsert = false;
- int inFunction = 0;
- int parensSinceSelect = 0;
+ boolean afterBeginBeforeEnd;
+ boolean afterByOrSetOrFromOrSelect;
+ boolean afterValues;
+ boolean afterOn;
+ boolean afterBetween;
+ boolean afterInsert;
+ int inFunction;
+ int parensSinceSelect;
private LinkedList parenCounts = new LinkedList();
private LinkedList afterByOrFromOrSelects = new LinkedList();
@@ -122,7 +122,7 @@ public class BasicFormatterImpl implements Formatter {
public String perform() {
- result.append( initial );
+ result.append( INITIAL );
while ( tokens.hasMoreTokens() ) {
token = tokens.nextToken();
@@ -134,7 +134,8 @@ public class BasicFormatterImpl implements Formatter {
t = tokens.nextToken();
token += t;
}
- while ( !"'".equals( t ) && tokens.hasMoreTokens() ); // cannot handle single quotes
+ // cannot handle single quotes
+ while ( !"'".equals( t ) && tokens.hasMoreTokens() );
}
else if ( "\"".equals( token ) ) {
String t;
@@ -384,16 +385,16 @@ public class BasicFormatterImpl implements Formatter {
}
private static boolean isWhitespace(String token) {
- return StringHelper.WHITESPACE.indexOf( token ) >= 0;
+ return StringHelper.WHITESPACE.contains( token );
}
private void newline() {
result.append( "\n" );
for ( int i = 0; i < indent; i++ ) {
- result.append( indentString );
+ result.append( INDENT_STRING );
}
beginLine = true;
}
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BinaryStreamImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BinaryStreamImpl.java
index b687105af4..be56516c4a 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BinaryStreamImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BinaryStreamImpl.java
@@ -37,6 +37,11 @@ import org.hibernate.engine.jdbc.BinaryStream;
public class BinaryStreamImpl extends ByteArrayInputStream implements BinaryStream {
private final int length;
+ /**
+ * Constructs a BinaryStreamImpl
+ *
+ * @param bytes The bytes to use backing the stream
+ */
public BinaryStreamImpl(byte[] bytes) {
super( bytes );
this.length = bytes.length;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/CharacterStreamImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/CharacterStreamImpl.java
index a82d5caf57..ea13df4e82 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/CharacterStreamImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/CharacterStreamImpl.java
@@ -41,11 +41,22 @@ public class CharacterStreamImpl implements CharacterStream {
private Reader reader;
private String string;
+ /**
+ * Constructs a CharacterStreamImpl
+ *
+ * @param chars The String of characters to use backing the CharacterStream
+ */
public CharacterStreamImpl(String chars) {
this.string = chars;
this.length = chars.length();
}
+ /**
+ * Constructs a CharacterStreamImpl
+ *
+ * @param reader The Reader containing the characters to use backing the CharacterStream
+ * @param length The length of the stream
+ */
public CharacterStreamImpl(Reader reader, long length) {
this.reader = reader;
this.length = length;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/DDLFormatterImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/DDLFormatterImpl.java
index 538bbc4a16..4a923559d9 100755
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/DDLFormatterImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/DDLFormatterImpl.java
@@ -34,20 +34,16 @@ import org.hibernate.internal.util.StringHelper;
* @author Steve Ebersole
*/
public class DDLFormatterImpl implements Formatter {
+ /**
+ * Singleton access
+ */
public static final DDLFormatterImpl INSTANCE = new DDLFormatterImpl();
- /**
- * Format an SQL statement using simple rules
- *
Insert newline after each comma
- *
Indent three spaces after each inserted newline
- *
- * If the statement contains single/double quotes return unchanged,
- * it is too complex and could be broken by simple formatting.
- *
- * @param sql The statement to be fornmatted.
- */
+ @Override
public String format(String sql) {
- if ( StringHelper.isEmpty( sql ) ) return sql;
+ if ( StringHelper.isEmpty( sql ) ) {
+ return sql;
+ }
if ( sql.toLowerCase().startsWith( "create table" ) ) {
return formatCreateTable( sql );
}
@@ -63,12 +59,12 @@ public class DDLFormatterImpl implements Formatter {
}
private String formatCommentOn(String sql) {
- StringBuilder result = new StringBuilder( 60 ).append( "\n " );
- StringTokenizer tokens = new StringTokenizer( sql, " '[]\"", true );
+ final StringBuilder result = new StringBuilder( 60 ).append( "\n " );
+ final StringTokenizer tokens = new StringTokenizer( sql, " '[]\"", true );
boolean quoted = false;
while ( tokens.hasMoreTokens() ) {
- String token = tokens.nextToken();
+ final String token = tokens.nextToken();
result.append( token );
if ( isQuote( token ) ) {
quoted = !quoted;
@@ -84,12 +80,12 @@ public class DDLFormatterImpl implements Formatter {
}
private String formatAlterTable(String sql) {
- StringBuilder result = new StringBuilder( 60 ).append( "\n " );
- StringTokenizer tokens = new StringTokenizer( sql, " (,)'[]\"", true );
+ final StringBuilder result = new StringBuilder( 60 ).append( "\n " );
+ final StringTokenizer tokens = new StringTokenizer( sql, " (,)'[]\"", true );
boolean quoted = false;
while ( tokens.hasMoreTokens() ) {
- String token = tokens.nextToken();
+ final String token = tokens.nextToken();
if ( isQuote( token ) ) {
quoted = !quoted;
}
@@ -105,13 +101,13 @@ public class DDLFormatterImpl implements Formatter {
}
private String formatCreateTable(String sql) {
- StringBuilder result = new StringBuilder( 60 ).append( "\n " );
- StringTokenizer tokens = new StringTokenizer( sql, "(,)'[]\"", true );
+ final StringBuilder result = new StringBuilder( 60 ).append( "\n " );
+ final StringTokenizer tokens = new StringTokenizer( sql, "(,)'[]\"", true );
int depth = 0;
boolean quoted = false;
while ( tokens.hasMoreTokens() ) {
- String token = tokens.nextToken();
+ final String token = tokens.nextToken();
if ( isQuote( token ) ) {
quoted = !quoted;
result.append( token );
@@ -158,4 +154,4 @@ public class DDLFormatterImpl implements Formatter {
"'".equals( tok );
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/FormatStyle.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/FormatStyle.java
index 80a3e12f01..b077ede88b 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/FormatStyle.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/FormatStyle.java
@@ -23,16 +23,24 @@
*/
package org.hibernate.engine.jdbc.internal;
-
/**
* Represents the the understood types or styles of formatting.
*
* @author Steve Ebersole
*/
public enum FormatStyle {
+ /**
+ * Formatting for SELECT, INSERT, UPDATE and DELETE statements
+ */
BASIC( "basic", new BasicFormatterImpl() ),
- DDL( "ddl", new DDLFormatterImpl() ),
- NONE( "none", new NoFormatImpl() );
+ /**
+ * Formatting for DDL (CREATE, ALTER, DROP, etc) statements
+ */
+ DDL( "ddl", DDLFormatterImpl.INSTANCE ),
+ /**
+ * No formatting
+ */
+ NONE( "none", NoFormatImpl.INSTANCE );
private final String name;
private final Formatter formatter;
@@ -51,6 +59,11 @@ public enum FormatStyle {
}
private static class NoFormatImpl implements Formatter {
+ /**
+ * Singleton access
+ */
+ public static final NoFormatImpl INSTANCE = new NoFormatImpl();
+
public String format(String source) {
return source;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java
index 43241d472c..0591ded2a5 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java
@@ -69,8 +69,9 @@ import org.hibernate.jdbc.WorkExecutorVisitable;
* @author Brett Meyer
*/
public class JdbcCoordinatorImpl implements JdbcCoordinator {
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(
- CoreMessageLogger.class, JdbcCoordinatorImpl.class.getName()
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ JdbcCoordinatorImpl.class.getName()
);
private transient TransactionCoordinator transactionCoordinator;
@@ -82,7 +83,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
private final HashMap> xref = new HashMap>();
private final Set unassociatedResultSets = new HashSet();
- private final SqlExceptionHelper exceptionHelper;
+ private final transient SqlExceptionHelper exceptionHelper;
private Statement lastQuery;
@@ -91,6 +92,12 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
*/
private boolean releasesEnabled = true;
+ /**
+ * Constructs a JdbcCoordinatorImpl
+ *
+ * @param userSuppliedConnection The user supplied connection (may be null)
+ * @param transactionCoordinator The transaction coordinator
+ */
public JdbcCoordinatorImpl(
Connection userSuppliedConnection,
TransactionCoordinator transactionCoordinator) {
@@ -104,6 +111,12 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
this.exceptionHelper = logicalConnection.getJdbcServices().getSqlExceptionHelper();
}
+ /**
+ * Constructs a JdbcCoordinatorImpl
+ *
+ * @param logicalConnection The logical JDBC connection
+ * @param transactionCoordinator The transaction coordinator
+ */
public JdbcCoordinatorImpl(
LogicalConnectionImpl logicalConnection,
TransactionCoordinator transactionCoordinator) {
@@ -139,12 +152,17 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
return sessionFactory().getServiceRegistry().getService( BatchBuilder.class );
}
+ /**
+ * Access to the SqlExceptionHelper
+ *
+ * @return The SqlExceptionHelper
+ */
public SqlExceptionHelper sqlExceptionHelper() {
return transactionEnvironment().getJdbcServices().getSqlExceptionHelper();
}
- private int flushDepth = 0;
+ private int flushDepth;
@Override
public void flushBeginning() {
@@ -197,7 +215,8 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
public void executeBatch() {
if ( currentBatch != null ) {
currentBatch.execute();
- currentBatch.release(); // needed?
+ // needed?
+ currentBatch.release();
}
}
@@ -280,9 +299,9 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
@Override
public T coordinateWork(WorkExecutorVisitable work) {
- Connection connection = getLogicalConnection().getConnection();
+ final Connection connection = getLogicalConnection().getConnection();
try {
- T result = work.accept( new WorkExecutor(), connection );
+ final T result = work.accept( new WorkExecutor(), connection );
afterStatementExecution();
return result;
}
@@ -298,6 +317,13 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
: ! hasRegisteredResources();
}
+ /**
+ * JDK serialization hook
+ *
+ * @param oos The stream into which to write our state
+ *
+ * @throws IOException Trouble accessing the stream
+ */
public void serialize(ObjectOutputStream oos) throws IOException {
if ( ! isReadyForSerialization() ) {
throw new HibernateException( "Cannot serialize Session while connected" );
@@ -305,12 +331,28 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
logicalConnection.serialize( oos );
}
+ /**
+ * JDK deserialization hook
+ *
+ * @param ois The stream into which to write our state
+ * @param transactionContext The transaction context which owns the JdbcCoordinatorImpl to be deserialized.
+ *
+ * @return The deserialized JdbcCoordinatorImpl
+ *
+ * @throws IOException Trouble accessing the stream
+ * @throws ClassNotFoundException Trouble reading the stream
+ */
public static JdbcCoordinatorImpl deserialize(
ObjectInputStream ois,
TransactionContext transactionContext) throws IOException, ClassNotFoundException {
return new JdbcCoordinatorImpl( LogicalConnectionImpl.deserialize( ois, transactionContext ) );
- }
+ }
+ /**
+ * Callback after deserialization from Session is done
+ *
+ * @param transactionCoordinator The transaction coordinator
+ */
public void afterDeserialize(TransactionCoordinatorImpl transactionCoordinator) {
this.transactionCoordinator = transactionCoordinator;
}
@@ -329,7 +371,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
public void registerLastQuery(Statement statement) {
LOG.tracev( "Registering last query statement [{0}]", statement );
if ( statement instanceof JdbcWrapper ) {
- JdbcWrapper wrapper = ( JdbcWrapper ) statement;
+ final JdbcWrapper wrapper = (JdbcWrapper) statement;
registerLastQuery( wrapper.getWrappedObject() );
return;
}
@@ -344,10 +386,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
}
}
catch (SQLException sqle) {
- throw exceptionHelper.convert(
- sqle,
- "Cannot cancel query"
- );
+ throw exceptionHelper.convert( sqle, "Cannot cancel query" );
}
finally {
lastQuery = null;
@@ -357,7 +396,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
@Override
public void release(Statement statement) {
LOG.tracev( "Releasing statement [{0}]", statement );
- Set resultSets = xref.get( statement );
+ final Set resultSets = xref.get( statement );
if ( resultSets != null ) {
for ( ResultSet resultSet : resultSets ) {
close( resultSet );
@@ -412,7 +451,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
if ( LOG.isEnabled( Level.WARN ) && !xref.containsKey( statement ) ) {
LOG.unregisteredStatement();
}
- Set resultSets = xref.get( statement );
+ final Set resultSets = xref.get( statement );
if ( resultSets != null ) {
resultSets.remove( resultSet );
if ( resultSets.isEmpty() ) {
@@ -421,7 +460,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
}
}
else {
- boolean removed = unassociatedResultSets.remove( resultSet );
+ final boolean removed = unassociatedResultSets.remove( resultSet );
if ( !removed ) {
LOG.unregisteredResultSetWithoutStatement();
}
@@ -474,7 +513,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
LOG.tracev( "Closing prepared statement [{0}]", statement );
if ( statement instanceof InvalidatableWrapper ) {
- InvalidatableWrapper wrapper = ( InvalidatableWrapper ) statement;
+ final InvalidatableWrapper wrapper = (InvalidatableWrapper) statement;
close( wrapper.getWrappedObject() );
wrapper.invalidate();
return;
@@ -496,7 +535,8 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
if ( LOG.isDebugEnabled() ) {
LOG.debugf( "Exception clearing maxRows/queryTimeout [%s]", sqle.getMessage() );
}
- return; // EARLY EXIT!!!
+ // EARLY EXIT!!!
+ return;
}
statement.close();
if ( lastQuery == statement ) {
@@ -517,7 +557,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator {
LOG.tracev( "Closing result set [{0}]", resultSet );
if ( resultSet instanceof InvalidatableWrapper ) {
- InvalidatableWrapper wrapper = (InvalidatableWrapper) resultSet;
+ final InvalidatableWrapper wrapper = (InvalidatableWrapper) resultSet;
close( wrapper.getWrappedObject() );
wrapper.invalidate();
return;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java
index 342dfe3651..691536210c 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java
@@ -25,6 +25,8 @@ package org.hibernate.engine.jdbc.internal;
import java.util.Map;
+import org.jboss.logging.Logger;
+
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.LobCreationContext;
@@ -36,6 +38,7 @@ import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.jdbc.spi.ResultSetWrapper;
import org.hibernate.engine.jdbc.spi.SqlExceptionHelper;
import org.hibernate.engine.jdbc.spi.SqlStatementLogger;
+import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.service.spi.Configurable;
import org.hibernate.service.spi.ServiceRegistryAwareService;
@@ -47,6 +50,11 @@ import org.hibernate.service.spi.ServiceRegistryImplementor;
* @author Steve Ebersole
*/
public class JdbcServicesImpl implements JdbcServices, ServiceRegistryAwareService, Configurable {
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ JdbcServicesImpl.class.getName()
+ );
+
private ServiceRegistryImplementor serviceRegistry;
private JdbcEnvironment jdbcEnvironment;
@@ -64,7 +72,6 @@ public class JdbcServicesImpl implements JdbcServices, ServiceRegistryAwareServi
this.jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );
this.connectionProvider = serviceRegistry.getService( ConnectionProvider.class );
-
final boolean showSQL = ConfigurationHelper.getBoolean( Environment.SHOW_SQL, configValues, false );
final boolean formatSQL = ConfigurationHelper.getBoolean( Environment.FORMAT_SQL, configValues, false );
this.sqlStatementLogger = new SqlStatementLogger( showSQL, formatSQL );
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesInitiator.java
index a1704b075a..e415763bca 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesInitiator.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesInitiator.java
@@ -32,11 +32,14 @@ import org.hibernate.service.spi.ServiceRegistryImplementor;
/**
* Standard initiator for the standard {@link JdbcServices} service
*
- * @todo : should this maybe be a SessionFactory service?
+ * TODO : should this maybe be a SessionFactory service?
*
* @author Steve Ebersole
*/
public class JdbcServicesInitiator implements StandardServiceInitiator {
+ /**
+ * Singleton access
+ */
public static final JdbcServicesInitiator INSTANCE = new JdbcServicesInitiator();
@Override
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java
index 7547d069dd..38893bc773 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java
@@ -55,8 +55,10 @@ import org.hibernate.internal.util.collections.CollectionHelper;
* @author Brett Meyer
*/
public class LogicalConnectionImpl implements LogicalConnectionImplementor {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, LogicalConnectionImpl.class.getName() );
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ LogicalConnectionImpl.class.getName()
+ );
private transient Connection physicalConnection;
@@ -69,6 +71,14 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
private boolean isClosed;
+ /**
+ * Constructs a LogicalConnectionImpl
+ *
+ * @param userSuppliedConnection The user-supplied connection
+ * @param connectionReleaseMode The connection release mode to use
+ * @param jdbcServices JdbcServices
+ * @param jdbcConnectionAccess JDBC Connection access
+ */
public LogicalConnectionImpl(
Connection userSuppliedConnection,
ConnectionReleaseMode connectionReleaseMode,
@@ -85,6 +95,9 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
this.physicalConnection = userSuppliedConnection;
}
+ /**
+ * Constructs a LogicalConnectionImpl. This for used from deserialization
+ */
private LogicalConnectionImpl(
ConnectionReleaseMode connectionReleaseMode,
JdbcServices jdbcServices,
@@ -163,7 +176,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
@Override
public Connection close() {
LOG.trace( "Closing logical connection" );
- Connection c = isUserSuppliedConnection ? physicalConnection : null;
+ final Connection c = isUserSuppliedConnection ? physicalConnection : null;
try {
if ( !isUserSuppliedConnection && physicalConnection != null ) {
releaseConnection();
@@ -256,7 +269,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
}
private void releaseNonDurableObservers() {
- Iterator observers = this.observers.iterator();
+ final Iterator observers = this.observers.iterator();
while ( observers.hasNext() ) {
if ( NonDurableConnectionObserver.class.isInstance( observers.next() ) ) {
observers.remove();
@@ -269,7 +282,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
if ( isClosed ) {
throw new IllegalStateException( "cannot manually disconnect because logical connection is already closed" );
}
- Connection c = physicalConnection;
+ final Connection c = physicalConnection;
releaseConnection();
return c;
}
@@ -325,10 +338,17 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
}
}
+ /**
+ * Serialization hook
+ *
+ * @param oos The stream to write out state to
+ *
+ * @throws IOException Problem accessing stream
+ */
public void serialize(ObjectOutputStream oos) throws IOException {
oos.writeBoolean( isUserSuppliedConnection );
oos.writeBoolean( isClosed );
- List durableConnectionObservers = new ArrayList();
+ final List durableConnectionObservers = new ArrayList();
for ( ConnectionObserver observer : observers ) {
if ( ! NonDurableConnectionObserver.class.isInstance( observer ) ) {
durableConnectionObservers.add( observer );
@@ -340,13 +360,24 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
}
}
+ /**
+ * Deserialization hook
+ *
+ * @param ois The stream to read our state from
+ * @param transactionContext The transactionContext which owns this logical connection
+ *
+ * @return The deserialized LogicalConnectionImpl
+ *
+ * @throws IOException Trouble accessing the stream
+ * @throws ClassNotFoundException Trouble reading the stream
+ */
public static LogicalConnectionImpl deserialize(
ObjectInputStream ois,
TransactionContext transactionContext) throws IOException, ClassNotFoundException {
- boolean isUserSuppliedConnection = ois.readBoolean();
- boolean isClosed = ois.readBoolean();
- int observerCount = ois.readInt();
- List observers = CollectionHelper.arrayList( observerCount );
+ final boolean isUserSuppliedConnection = ois.readBoolean();
+ final boolean isClosed = ois.readBoolean();
+ final int observerCount = ois.readInt();
+ final List observers = CollectionHelper.arrayList( observerCount );
for ( int i = 0; i < observerCount; i++ ) {
observers.add( (ConnectionObserver) ois.readObject() );
}
@@ -358,5 +389,5 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor {
isClosed,
observers
);
- }
+ }
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetReturnImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetReturnImpl.java
index d51e2fd034..36caece313 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetReturnImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetReturnImpl.java
@@ -31,12 +31,18 @@ import org.hibernate.engine.jdbc.spi.ResultSetReturn;
import org.hibernate.engine.jdbc.spi.SqlExceptionHelper;
/**
+ * Standard implementation of the ResultSetReturn contract
+ *
* @author Brett Meyer
*/
public class ResultSetReturnImpl implements ResultSetReturn {
-
private final JdbcCoordinator jdbcCoordinator;
+ /**
+ * Constructs a ResultSetReturnImpl
+ *
+ * @param jdbcCoordinator The JdbcCoordinator
+ */
public ResultSetReturnImpl(JdbcCoordinator jdbcCoordinator) {
this.jdbcCoordinator = jdbcCoordinator;
}
@@ -49,11 +55,11 @@ public class ResultSetReturnImpl implements ResultSetReturn {
// this seems needless, Oracle can return an
// OracleCallableStatementWrapper that finds its way to this method,
// rather than extract(CallableStatement). See HHH-8022.
- CallableStatement callableStatement = (CallableStatement) statement;
+ final CallableStatement callableStatement = (CallableStatement) statement;
return extract( callableStatement );
}
try {
- ResultSet rs = statement.executeQuery();
+ final ResultSet rs = statement.executeQuery();
postExtract( rs, statement );
return rs;
}
@@ -66,8 +72,10 @@ public class ResultSetReturnImpl implements ResultSetReturn {
public ResultSet extract(CallableStatement statement) {
try {
// sql logged by StatementPreparerImpl
- ResultSet rs = jdbcCoordinator.getLogicalConnection().getJdbcServices()
- .getDialect().getResultSet( statement );
+ final ResultSet rs = jdbcCoordinator.getLogicalConnection()
+ .getJdbcServices()
+ .getDialect()
+ .getResultSet( statement );
postExtract( rs, statement );
return rs;
}
@@ -78,10 +86,9 @@ public class ResultSetReturnImpl implements ResultSetReturn {
@Override
public ResultSet extract(Statement statement, String sql) {
- jdbcCoordinator.getLogicalConnection().getJdbcServices()
- .getSqlStatementLogger().logStatement( sql );
+ jdbcCoordinator.getLogicalConnection().getJdbcServices().getSqlStatementLogger().logStatement( sql );
try {
- ResultSet rs = statement.executeQuery( sql );
+ final ResultSet rs = statement.executeQuery( sql );
postExtract( rs, statement );
return rs;
}
@@ -99,7 +106,7 @@ public class ResultSetReturnImpl implements ResultSetReturn {
// do nothing until we hit the resultset
}
}
- ResultSet rs = statement.getResultSet();
+ final ResultSet rs = statement.getResultSet();
postExtract( rs, statement );
return rs;
}
@@ -118,7 +125,7 @@ public class ResultSetReturnImpl implements ResultSetReturn {
// do nothing until we hit the resultset
}
}
- ResultSet rs = statement.getResultSet();
+ final ResultSet rs = statement.getResultSet();
postExtract( rs, statement );
return rs;
}
@@ -149,7 +156,7 @@ public class ResultSetReturnImpl implements ResultSetReturn {
}
}
- private final SqlExceptionHelper sqlExceptionHelper() {
+ private SqlExceptionHelper sqlExceptionHelper() {
return jdbcCoordinator.getTransactionCoordinator()
.getTransactionContext()
.getTransactionEnvironment()
@@ -158,7 +165,9 @@ public class ResultSetReturnImpl implements ResultSetReturn {
}
private void postExtract(ResultSet rs, Statement st) {
- if ( rs != null ) jdbcCoordinator.register( rs, st );
+ if ( rs != null ) {
+ jdbcCoordinator.register( rs, st );
+ }
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java
index b76819aced..c5cf9d1bd2 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java
@@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.engine.jdbc.internal;
+
import java.sql.ResultSet;
import org.hibernate.engine.jdbc.ColumnNameCache;
@@ -32,18 +33,20 @@ import org.hibernate.engine.jdbc.spi.ResultSetWrapper;
* Standard Hibernate implementation for wrapping a {@link ResultSet} in a
" column name cache" wrapper.
*
+ * @author Steve Ebersole
* @author Gail Badner
*/
public class ResultSetWrapperImpl implements ResultSetWrapper {
- public static ResultSetWrapper INSTANCE = new ResultSetWrapperImpl();
+ /**
+ * Singleton access
+ */
+ public static final ResultSetWrapper INSTANCE = new ResultSetWrapperImpl();
private ResultSetWrapperImpl() {
}
- /**
- * {@inheritDoc}
- */
+ @Override
public ResultSet wrap(ResultSet resultSet, ColumnNameCache columnNameCache) {
return ResultSetWrapperProxy.generateProxy( resultSet, columnNameCache );
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparerImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparerImpl.java
index ef579209c4..f7ca3a1340 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparerImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparerImpl.java
@@ -37,6 +37,8 @@ import org.hibernate.engine.jdbc.spi.SqlExceptionHelper;
import org.hibernate.engine.jdbc.spi.StatementPreparer;
/**
+ * Standard implementation of StatementPreparer
+ *
* @author Steve Ebersole
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
* @author Brett Meyer
@@ -44,6 +46,11 @@ import org.hibernate.engine.jdbc.spi.StatementPreparer;
class StatementPreparerImpl implements StatementPreparer {
private JdbcCoordinatorImpl jdbcCoordinator;
+ /**
+ * Construct a StatementPreparerImpl
+ *
+ * @param jdbcCoordinator The JdbcCoordinatorImpl
+ */
StatementPreparerImpl(JdbcCoordinatorImpl jdbcCoordinator) {
this.jdbcCoordinator = jdbcCoordinator;
}
@@ -71,7 +78,7 @@ class StatementPreparerImpl implements StatementPreparer {
@Override
public Statement createStatement() {
try {
- Statement statement = connection().createStatement();
+ final Statement statement = connection().createStatement();
jdbcCoordinator.register( statement );
return statement;
}
@@ -141,22 +148,18 @@ class StatementPreparerImpl implements StatementPreparer {
if ( ! settings().isScrollableResultSetsEnabled() ) {
throw new AssertionFailure("scrollable result sets are not enabled");
}
- PreparedStatement ps = new QueryStatementPreparationTemplate( sql ) {
+ final PreparedStatement ps = new QueryStatementPreparationTemplate( sql ) {
public PreparedStatement doPrepare() throws SQLException {
return isCallable
- ? connection().prepareCall(
- sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY
- )
- : connection().prepareStatement(
- sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY
- );
+ ? connection().prepareCall( sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY )
+ : connection().prepareStatement( sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY );
}
}.prepareStatement();
jdbcCoordinator.registerLastQuery( ps );
return ps;
}
else {
- PreparedStatement ps = new QueryStatementPreparationTemplate( sql ) {
+ final PreparedStatement ps = new QueryStatementPreparationTemplate( sql ) {
public PreparedStatement doPrepare() throws SQLException {
return isCallable
? connection().prepareCall( sql )
@@ -179,7 +182,7 @@ class StatementPreparerImpl implements StatementPreparer {
try {
jdbcCoordinator.getLogicalConnection().getJdbcServices().getSqlStatementLogger().logStatement( sql );
- PreparedStatement preparedStatement = doPrepare();
+ final PreparedStatement preparedStatement = doPrepare();
setStatementTimeout( preparedStatement );
postProcess( preparedStatement );
return preparedStatement;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/package-info.java
new file mode 100644
index 0000000000..a83fec0f71
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Internals for supporting various aspects of JDBC interaction
+ */
+package org.hibernate.engine.jdbc.internal;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/package-info.java
new file mode 100644
index 0000000000..acd103dc0b
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Support for various aspects of JDBC interaction
+ */
+package org.hibernate.engine.jdbc;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SqlExceptionHelper.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SqlExceptionHelper.java
index f1d56fb263..26d8b6587c 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SqlExceptionHelper.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SqlExceptionHelper.java
@@ -44,13 +44,15 @@ import org.hibernate.internal.util.StringHelper;
* @author Steve Ebersole
*/
public class SqlExceptionHelper {
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ SqlExceptionHelper.class.getName()
+ );
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, SqlExceptionHelper.class.getName());
+ private static final String DEFAULT_EXCEPTION_MSG = "SQL Exception";
+ private static final String DEFAULT_WARNING_MSG = "SQL Warning";
- public static final String DEFAULT_EXCEPTION_MSG = "SQL Exception";
- public static final String DEFAULT_WARNING_MSG = "SQL Warning";
-
- public static final SQLExceptionConverter DEFAULT_CONVERTER = new SQLStateConverter(
+ private static final SQLExceptionConverter DEFAULT_CONVERTER = new SQLStateConverter(
new ViolatedConstraintNameExtracter() {
public String extractConstraintName(SQLException e) {
return null;
@@ -93,206 +95,236 @@ public class SqlExceptionHelper {
* @param sqlExceptionConverter The converter to use.
*/
public void setSqlExceptionConverter(SQLExceptionConverter sqlExceptionConverter) {
- this.sqlExceptionConverter = ( sqlExceptionConverter == null ? DEFAULT_CONVERTER : sqlExceptionConverter );
+ this.sqlExceptionConverter = (sqlExceptionConverter == null ? DEFAULT_CONVERTER : sqlExceptionConverter);
}
- // SQLException ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ // SQLException ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- /**
- * Convert an SQLException using the current converter, doing some logging first.
- *
- * @param sqlException The exception to convert
- * @param message An error message.
- * @return The converted exception
- */
- public JDBCException convert( SQLException sqlException,
- String message ) {
- return convert(sqlException, message, "n/a");
- }
+ /**
+ * Convert an SQLException using the current converter, doing some logging first.
+ *
+ * @param sqlException The exception to convert
+ * @param message An error message.
+ *
+ * @return The converted exception
+ */
+ public JDBCException convert(SQLException sqlException, String message) {
+ return convert( sqlException, message, "n/a" );
+ }
- /**
- * Convert an SQLException using the current converter, doing some logging first.
- *
- * @param sqlException The exception to convert
- * @param message An error message.
- * @param sql The SQL being executed when the exception occurred
- * @return The converted exception
- */
- public JDBCException convert( SQLException sqlException,
- String message,
- String sql ) {
- logExceptions(sqlException, message + " [" + sql + "]");
- return sqlExceptionConverter.convert(sqlException, message, sql);
- }
+ /**
+ * Convert an SQLException using the current converter, doing some logging first.
+ *
+ * @param sqlException The exception to convert
+ * @param message An error message.
+ * @param sql The SQL being executed when the exception occurred
+ *
+ * @return The converted exception
+ */
+ public JDBCException convert(SQLException sqlException, String message, String sql) {
+ logExceptions( sqlException, message + " [" + sql + "]" );
+ return sqlExceptionConverter.convert( sqlException, message, sql );
+ }
- /**
- * Log the given (and any nested) exception.
- *
- * @param sqlException The exception to log
- * @param message The message text to use as a preamble.
- */
- public void logExceptions( SQLException sqlException,
- String message ) {
- if (LOG.isEnabled(Level.ERROR)) {
- if (LOG.isDebugEnabled()) {
- message = StringHelper.isNotEmpty(message) ? message : DEFAULT_EXCEPTION_MSG;
- LOG.debug( message, sqlException );
- }
- final boolean warnEnabled = LOG.isEnabled( Level.WARN );
- while (sqlException != null) {
- if ( warnEnabled ) {
- StringBuilder buf = new StringBuilder(30).append("SQL Error: ").append(sqlException.getErrorCode()).append(", SQLState: ").append(sqlException.getSQLState());
- LOG.warn(buf.toString());
- }
- LOG.error(sqlException.getMessage());
- sqlException = sqlException.getNextException();
- }
- }
- }
+ /**
+ * Log the given (and any nested) exception.
+ *
+ * @param sqlException The exception to log
+ * @param message The message text to use as a preamble.
+ */
+ public void logExceptions(
+ SQLException sqlException,
+ String message) {
+ if ( LOG.isEnabled( Level.ERROR ) ) {
+ if ( LOG.isDebugEnabled() ) {
+ message = StringHelper.isNotEmpty( message ) ? message : DEFAULT_EXCEPTION_MSG;
+ LOG.debug( message, sqlException );
+ }
+ final boolean warnEnabled = LOG.isEnabled( Level.WARN );
+ while ( sqlException != null ) {
+ if ( warnEnabled ) {
+ LOG.warn( "SQL Error: " + sqlException.getErrorCode() + ", SQLState: " + sqlException.getSQLState() );
+ }
+ LOG.error( sqlException.getMessage() );
+ sqlException = sqlException.getNextException();
+ }
+ }
+ }
- // SQLWarning ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ // SQLWarning ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- /**
- * Contract for handling {@link SQLWarning warnings}
- */
- public static interface WarningHandler {
- /**
- * Should processing be done? Allows short-circuiting if not.
- *
- * @return True to process warnings, false otherwise.
- */
- public boolean doProcess();
+ /**
+ * Contract for handling {@link SQLWarning warnings}
+ */
+ public static interface WarningHandler {
+ /**
+ * Should processing be done? Allows short-circuiting if not.
+ *
+ * @return True to process warnings, false otherwise.
+ */
+ public boolean doProcess();
- /**
- * Prepare for processing of a {@link SQLWarning warning} stack.
- *
- * Note that the warning here is also the first passed to {@link #handleWarning}
- *
- * @param warning The first warning in the stack.
- */
- public void prepare( SQLWarning warning );
+ /**
+ * Prepare for processing of a {@link SQLWarning warning} stack.
+ *
+ * Note that the warning here is also the first passed to {@link #handleWarning}
+ *
+ * @param warning The first warning in the stack.
+ */
+ public void prepare(SQLWarning warning);
- /**
- * Handle an individual warning in the stack.
- *
- * @param warning The warning to handle.
- */
- public void handleWarning( SQLWarning warning );
- }
+ /**
+ * Handle an individual warning in the stack.
+ *
+ * @param warning The warning to handle.
+ */
+ public void handleWarning(SQLWarning warning);
+ }
- /**
- * Basic support for {@link WarningHandler} implementations which log
- */
- public static abstract class WarningHandlerLoggingSupport implements WarningHandler {
- public final void handleWarning( SQLWarning warning ) {
- StringBuilder buf = new StringBuilder(30).append("SQL Warning Code: ").append(warning.getErrorCode()).append(", SQLState: ").append(warning.getSQLState());
- logWarning(buf.toString(), warning.getMessage());
- }
+ /**
+ * Basic support for {@link WarningHandler} implementations which handle {@link SQLWarning warnings}
+ */
+ public abstract static class WarningHandlerLoggingSupport implements WarningHandler {
+ @Override
+ public final void handleWarning(SQLWarning warning) {
+ logWarning(
+ "SQL Warning Code: " + warning.getErrorCode() + ", SQLState: " + warning.getSQLState(),
+ warning.getMessage()
+ );
+ }
- /**
- * Delegate to log common details of a {@link SQLWarning warning}
- *
- * @param description A description of the warning
- * @param message The warning message
- */
- protected abstract void logWarning( String description,
- String message );
- }
+ /**
+ * Delegate to log common details of a {@link SQLWarning warning}
+ *
+ * @param description A description of the warning
+ * @param message The warning message
+ */
+ protected abstract void logWarning(String description, String message);
+ }
- public static class StandardWarningHandler extends WarningHandlerLoggingSupport {
- private final String introMessage;
+ /**
+ * Standard SQLWarning handler for logging warnings
+ */
+ public static class StandardWarningHandler extends WarningHandlerLoggingSupport {
+ private final String introMessage;
- public StandardWarningHandler( String introMessage ) {
- this.introMessage = introMessage;
- }
+ /**
+ * Creates a StandardWarningHandler
+ *
+ * @param introMessage The introduction message for the hierarchy
+ */
+ public StandardWarningHandler(String introMessage) {
+ this.introMessage = introMessage;
+ }
- public boolean doProcess() {
- return LOG.isEnabled(Level.WARN);
- }
+ @Override
+ public boolean doProcess() {
+ return LOG.isEnabled( Level.WARN );
+ }
- public void prepare( SQLWarning warning ) {
- LOG.debug(introMessage, warning);
- }
+ @Override
+ public void prepare(SQLWarning warning) {
+ LOG.debug( introMessage, warning );
+ }
- @Override
- protected void logWarning( String description,
- String message ) {
- LOG.warn(description);
- LOG.warn(message);
- }
- }
+ @Override
+ protected void logWarning(
+ String description,
+ String message) {
+ LOG.warn( description );
+ LOG.warn( message );
+ }
+ }
- public static StandardWarningHandler STANDARD_WARNING_HANDLER = new StandardWarningHandler(DEFAULT_WARNING_MSG);
+ /**
+ * Static access to the standard handler for logging warnings
+ */
+ public static final StandardWarningHandler STANDARD_WARNING_HANDLER = new StandardWarningHandler( DEFAULT_WARNING_MSG );
- public void walkWarnings( SQLWarning warning,
- WarningHandler handler ) {
- if (warning == null || handler.doProcess()) {
- return;
- }
- handler.prepare(warning);
- while (warning != null) {
- handler.handleWarning(warning);
- warning = warning.getNextWarning();
- }
- }
+ /**
+ * Generic algorithm to walk the hierarchy of SQLWarnings
+ *
+ * @param warning The warning to walk
+ * @param handler The handler
+ */
+ public void walkWarnings(
+ SQLWarning warning,
+ WarningHandler handler) {
+ if ( warning == null || handler.doProcess() ) {
+ return;
+ }
+ handler.prepare( warning );
+ while ( warning != null ) {
+ handler.handleWarning( warning );
+ warning = warning.getNextWarning();
+ }
+ }
- /**
- * Standard (legacy) behavior for logging warnings associated with a JDBC {@link Connection} and clearing them.
- *
- * Calls {@link #handleAndClearWarnings(Connection, WarningHandler)} using {@link #STANDARD_WARNING_HANDLER}
- *
- * @param connection The JDBC connection potentially containing warnings
- */
- public void logAndClearWarnings( Connection connection ) {
- handleAndClearWarnings(connection, STANDARD_WARNING_HANDLER);
- }
+ /**
+ * Standard (legacy) behavior for logging warnings associated with a JDBC {@link Connection} and clearing them.
+ *
+ * Calls {@link #handleAndClearWarnings(Connection, WarningHandler)} using {@link #STANDARD_WARNING_HANDLER}
+ *
+ * @param connection The JDBC connection potentially containing warnings
+ */
+ public void logAndClearWarnings(Connection connection) {
+ handleAndClearWarnings( connection, STANDARD_WARNING_HANDLER );
+ }
- /**
- * General purpose handling of warnings associated with a JDBC {@link Connection}.
- *
- * @param connection The JDBC connection potentially containing warnings
- * @param handler The handler for each individual warning in the stack.
- * @see #walkWarnings
- */
- @SuppressWarnings( {"ThrowableResultOfMethodCallIgnored"} )
- public void handleAndClearWarnings( Connection connection,
- WarningHandler handler ) {
- try {
- walkWarnings(connection.getWarnings(), handler);
- } catch (SQLException sqle) {
- // workaround for WebLogic
- LOG.debug("could not log warnings", sqle);
- }
- try {
- // Sybase fail if we don't do that, sigh...
- connection.clearWarnings();
- } catch (SQLException sqle) {
- LOG.debug("could not clear warnings", sqle);
- }
- }
+ /**
+ * General purpose handling of warnings associated with a JDBC {@link Connection}.
+ *
+ * @param connection The JDBC connection potentially containing warnings
+ * @param handler The handler for each individual warning in the stack.
+ *
+ * @see #walkWarnings
+ */
+ @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"})
+ public void handleAndClearWarnings(
+ Connection connection,
+ WarningHandler handler) {
+ try {
+ walkWarnings( connection.getWarnings(), handler );
+ }
+ catch (SQLException sqle) {
+ // workaround for WebLogic
+ LOG.debug( "could not log warnings", sqle );
+ }
+ try {
+ // Sybase fail if we don't do that, sigh...
+ connection.clearWarnings();
+ }
+ catch (SQLException sqle) {
+ LOG.debug( "could not clear warnings", sqle );
+ }
+ }
- /**
- * General purpose handling of warnings associated with a JDBC {@link Statement}.
- *
- * @param statement The JDBC statement potentially containing warnings
- * @param handler The handler for each individual warning in the stack.
- * @see #walkWarnings
- */
- @SuppressWarnings( {"ThrowableResultOfMethodCallIgnored"} )
- public void handleAndClearWarnings( Statement statement,
- WarningHandler handler ) {
- try {
- walkWarnings(statement.getWarnings(), handler);
- } catch (SQLException sqlException) {
- // workaround for WebLogic
- LOG.debug("could not log warnings", sqlException);
- }
- try {
- // Sybase fail if we don't do that, sigh...
- statement.clearWarnings();
- } catch (SQLException sqle) {
- LOG.debug("could not clear warnings", sqle);
- }
- }
+ /**
+ * General purpose handling of warnings associated with a JDBC {@link Statement}.
+ *
+ * @param statement The JDBC statement potentially containing warnings
+ * @param handler The handler for each individual warning in the stack.
+ *
+ * @see #walkWarnings
+ */
+ @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"})
+ public void handleAndClearWarnings(
+ Statement statement,
+ WarningHandler handler) {
+ try {
+ walkWarnings( statement.getWarnings(), handler );
+ }
+ catch (SQLException sqlException) {
+ // workaround for WebLogic
+ LOG.debug( "could not log warnings", sqlException );
+ }
+ try {
+ // Sybase fail if we don't do that, sigh...
+ statement.clearWarnings();
+ }
+ catch (SQLException sqle) {
+ LOG.debug( "could not clear warnings", sqle );
+ }
+ }
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/package-info.java
new file mode 100644
index 0000000000..c55e445fdc
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * SPI contracts for supporting various aspects of JDBC interaction
+ */
+package org.hibernate.engine.jdbc.spi;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/query/spi/NativeSQLQueryPlan.java b/hibernate-core/src/main/java/org/hibernate/engine/query/spi/NativeSQLQueryPlan.java
index e661bfbf4c..84867ca1f4 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/query/spi/NativeSQLQueryPlan.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/query/spi/NativeSQLQueryPlan.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -20,7 +20,6 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
- *
*/
package org.hibernate.engine.query.spi;
@@ -53,22 +52,30 @@ import org.hibernate.type.Type;
* @author Steve Ebersole
*/
public class NativeSQLQueryPlan implements Serializable {
- private final String sourceQuery;
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ NativeSQLQueryPlan.class.getName()
+ );
+ private final String sourceQuery;
private final SQLCustomQuery customQuery;
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, NativeSQLQueryPlan.class.getName());
-
+ /**
+ * Constructs a NativeSQLQueryPlan
+ *
+ * @param specification The query spec
+ * @param factory The SessionFactory
+ */
public NativeSQLQueryPlan(
NativeSQLQuerySpecification specification,
SessionFactoryImplementor factory) {
this.sourceQuery = specification.getQueryString();
-
- customQuery = new SQLCustomQuery(
+ this.customQuery = new SQLCustomQuery(
specification.getQueryString(),
specification.getQueryReturns(),
specification.getQuerySpaces(),
- factory );
+ factory
+ );
}
public String getSourceQuery() {
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/AssociationKey.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/AssociationKey.java
index 5bf26b72b7..90bb0d380d 100755
--- a/hibernate-core/src/main/java/org/hibernate/engine/spi/AssociationKey.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/AssociationKey.java
@@ -35,19 +35,36 @@ import java.io.Serializable;
public final class AssociationKey implements Serializable {
private EntityKey ownerKey;
private String propertyName;
-
+
+ /**
+ * Constructs an AssociationKey
+ *
+ * @param ownerKey The EntityKey of the association owner
+ * @param propertyName The name of the property on the owner which defines the association
+ */
public AssociationKey(EntityKey ownerKey, String propertyName) {
this.ownerKey = ownerKey;
this.propertyName = propertyName;
}
-
- public boolean equals(Object that) {
- AssociationKey key = (AssociationKey) that;
- return key.propertyName.equals(propertyName) &&
- key.ownerKey.equals(ownerKey);
+
+ @Override
+ public boolean equals(Object o) {
+ if ( this == o ) {
+ return true;
+ }
+ if ( o == null || getClass() != o.getClass() ) {
+ return false;
+ }
+
+ final AssociationKey that = (AssociationKey) o;
+ return ownerKey.equals( that.ownerKey )
+ && propertyName.equals( that.propertyName );
}
-
+
+ @Override
public int hashCode() {
- return ownerKey.hashCode() + propertyName.hashCode();
+ int result = ownerKey.hashCode();
+ result = 31 * result + propertyName.hashCode();
+ return result;
}
}
\ No newline at end of file
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionKey.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionKey.java
index 63784e044a..9df614a053 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionKey.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionKey.java
@@ -62,34 +62,26 @@ public final class CollectionKey implements Serializable {
private CollectionKey(
String role,
- Serializable key,
- Type keyType,
- EntityMode entityMode,
- SessionFactoryImplementor factory) {
+ Serializable key,
+ Type keyType,
+ EntityMode entityMode,
+ SessionFactoryImplementor factory) {
this.role = role;
this.key = key;
this.keyType = keyType;
this.entityMode = entityMode;
this.factory = factory;
- this.hashCode = generateHashCode(); //cache the hashcode
+ //cache the hash-code
+ this.hashCode = generateHashCode();
}
- public boolean equals(Object other) {
- CollectionKey that = (CollectionKey) other;
- return that.role.equals(role) &&
- keyType.isEqual(that.key, key, factory);
- }
-
- public int generateHashCode() {
+ private int generateHashCode() {
int result = 17;
result = 37 * result + role.hashCode();
- result = 37 * result + keyType.getHashCode(key, factory);
+ result = 37 * result + keyType.getHashCode( key, factory );
return result;
}
- public int hashCode() {
- return hashCode;
- }
public String getRole() {
return role;
@@ -99,16 +91,38 @@ public final class CollectionKey implements Serializable {
return key;
}
+ @Override
public String toString() {
- return "PluralAttributeKeyBinding" +
- MessageHelper.collectionInfoString( factory.getCollectionPersister(role), key, factory );
+ return "CollectionKey"
+ + MessageHelper.collectionInfoString( factory.getCollectionPersister( role ), key, factory );
}
+ @Override
+ public boolean equals(Object other) {
+ if ( this == other ) {
+ return true;
+ }
+ if ( other == null || getClass() != other.getClass() ) {
+ return false;
+ }
+
+ final CollectionKey that = (CollectionKey) other;
+ return that.role.equals( role )
+ && keyType.isEqual( that.key, key, factory );
+ }
+
+ @Override
+ public int hashCode() {
+ return hashCode;
+ }
+
+
/**
* Custom serialization routine used during serialization of a
* Session/PersistenceContext for increased performance.
*
* @param oos The stream to which we should write the serial data.
+ *
* @throws java.io.IOException
*/
public void serialize(ObjectOutputStream oos) throws IOException {
@@ -124,19 +138,21 @@ public final class CollectionKey implements Serializable {
*
* @param ois The stream from which to read the entry.
* @param session The session being deserialized.
- * @return The deserialized PluralAttributeKeyBinding
+ *
+ * @return The deserialized CollectionKey
+ *
* @throws IOException
* @throws ClassNotFoundException
*/
public static CollectionKey deserialize(
ObjectInputStream ois,
- SessionImplementor session) throws IOException, ClassNotFoundException {
+ SessionImplementor session) throws IOException, ClassNotFoundException {
return new CollectionKey(
- ( String ) ois.readObject(),
- ( Serializable ) ois.readObject(),
- ( Type ) ois.readObject(),
- EntityMode.parse( ( String ) ois.readObject() ),
- ( session == null ? null : session.getFactory() )
+ (String) ois.readObject(),
+ (Serializable) ois.readObject(),
+ (Type) ois.readObject(),
+ EntityMode.parse( (String) ois.readObject() ),
+ (session == null ? null : session.getFactory())
);
}
}
\ No newline at end of file
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/EntityKey.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/EntityKey.java
index 61c1409bf7..b78bebf323 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/spi/EntityKey.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/EntityKey.java
@@ -55,7 +55,7 @@ public final class EntityKey implements Serializable {
/**
* Construct a unique identifier for an entity class instance.
- *
+ *
* NOTE : This signature has changed to accommodate both entity mode and multi-tenancy, both of which relate to
* the Session to which this key belongs. To help minimize the impact of these changes in the future, the
* {@link SessionImplementor#generateEntityKey} method was added to hide the session-specific changes.
@@ -68,7 +68,7 @@ public final class EntityKey implements Serializable {
if ( id == null ) {
throw new AssertionFailure( "null identifier" );
}
- this.identifier = id;
+ this.identifier = id;
this.rootEntityName = persister.getRootEntityName();
this.entityName = persister.getEntityName();
this.tenantId = tenantId;
@@ -92,11 +92,11 @@ public final class EntityKey implements Serializable {
*/
private EntityKey(
Serializable identifier,
- String rootEntityName,
- String entityName,
- Type identifierType,
- boolean batchLoadable,
- SessionFactoryImplementor factory,
+ String rootEntityName,
+ String entityName,
+ Type identifierType,
+ boolean batchLoadable,
+ SessionFactoryImplementor factory,
String tenantId) {
this.identifier = identifier;
this.rootEntityName = rootEntityName;
@@ -129,10 +129,17 @@ public final class EntityKey implements Serializable {
@Override
public boolean equals(Object other) {
- EntityKey otherKey = (EntityKey) other;
- return otherKey.rootEntityName.equals(this.rootEntityName) &&
- identifierType.isEqual(otherKey.identifier, this.identifier, factory) &&
- EqualsHelper.equals( tenantId, otherKey.tenantId );
+ if ( this == other ) {
+ return true;
+ }
+ if ( other == null || getClass() != other.getClass() ) {
+ return false;
+ }
+
+ final EntityKey otherKey = (EntityKey) other;
+ return otherKey.rootEntityName.equals( this.rootEntityName )
+ && identifierType.isEqual( otherKey.identifier, this.identifier, factory )
+ && EqualsHelper.equals( tenantId, otherKey.tenantId );
}
@Override
@@ -142,8 +149,8 @@ public final class EntityKey implements Serializable {
@Override
public String toString() {
- return "EntityKey" +
- MessageHelper.infoString( factory.getEntityPersister( entityName ), identifier, factory );
+ return "EntityKey" +
+ MessageHelper.infoString( factory.getEntityPersister( entityName ), identifier, factory );
}
/**
@@ -177,14 +184,14 @@ public final class EntityKey implements Serializable {
*/
public static EntityKey deserialize(
ObjectInputStream ois,
- SessionImplementor session) throws IOException, ClassNotFoundException {
+ SessionImplementor session) throws IOException, ClassNotFoundException {
return new EntityKey(
- ( Serializable ) ois.readObject(),
- (String) ois.readObject(),
+ (Serializable) ois.readObject(),
(String) ois.readObject(),
- ( Type ) ois.readObject(),
- ois.readBoolean(),
- ( session == null ? null : session.getFactory() ),
+ (String) ois.readObject(),
+ (Type) ois.readObject(),
+ ois.readBoolean(),
+ (session == null ? null : session.getFactory()),
(String) ois.readObject()
);
}
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/LoadQueryInfluencers.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/LoadQueryInfluencers.java
index 4e73ddce39..c62e2d32c9 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/spi/LoadQueryInfluencers.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/LoadQueryInfluencers.java
@@ -52,7 +52,7 @@ public class LoadQueryInfluencers implements Serializable {
* outside the context of any influencers. One such example is
* anything created by the session factory.
*/
- public static LoadQueryInfluencers NONE = new LoadQueryInfluencers();
+ public static final LoadQueryInfluencers NONE = new LoadQueryInfluencers();
private final SessionFactoryImplementor sessionFactory;
private String internalFetchProfile;
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java
index a2b935d577..b8874ae627 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java
@@ -33,6 +33,7 @@ import org.hibernate.LockMode;
import org.hibernate.MappingException;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.loading.internal.LoadContexts;
+import org.hibernate.internal.util.MarkerObject;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
@@ -52,7 +53,11 @@ import org.hibernate.persister.entity.EntityPersister;
*/
@SuppressWarnings( {"JavaDoc"})
public interface PersistenceContext {
-
+ /**
+ * Marker object used to indicate (via reference checking) that no row was returned.
+ */
+ public static final Object NO_ROW = new MarkerObject( "NO_ROW" );
+
@SuppressWarnings( {"UnusedDeclaration"})
public boolean isStateless();
@@ -135,11 +140,15 @@ public interface PersistenceContext {
public Object[] getDatabaseSnapshot(Serializable id, EntityPersister persister);
/**
- * Get the current database state of the entity, using the cached state snapshot if one is available.
- *
- * @param key The entity key
- *
- * @return The entity's (non-cached) snapshot
+ * Retrieve the cached database snapshot for the requested entity key.
+ *
+ * This differs from {@link #getDatabaseSnapshot} is two important respects:
+ *
no snapshot is obtained from the database if not already cached
+ *
an entry of {@link #NO_ROW} here is interpretet as an exception
+ *
+ * @param key The entity key for which to retrieve the cached snapshot
+ * @return The cached snapshot
+ * @throws IllegalStateException if the cached snapshot was == {@link #NO_ROW}.
*/
public Object[] getCachedDatabaseSnapshot(EntityKey key);
@@ -316,7 +325,9 @@ public interface PersistenceContext {
/**
* Attempts to check whether the given key represents an entity already loaded within the
* current session.
+ *
* @param object The entity reference against which to perform the uniqueness check.
+ *
* @throws HibernateException
*/
public void checkUniqueness(EntityKey key, Object object) throws HibernateException;
@@ -467,7 +478,13 @@ public interface PersistenceContext {
public void addProxy(EntityKey key, Object proxy);
/**
- * Remove a proxy from the session cache
+ * Remove a proxy from the session cache.
+ *
+ * Additionally, ensure that any load optimization references
+ * such as batch or subselect loading get cleaned up as well.
+ *
+ * @param key The key of the entity proxy to be removed
+ * @return The proxy reference.
*/
public Object removeProxy(EntityKey key);
@@ -559,10 +576,27 @@ public interface PersistenceContext {
public String toString();
/**
- * Search the persistence context for an owner for the child object,
- * given a collection role
+ * Search this persistence context for an associated entity instance which is considered the "owner" of
+ * the given childEntity, and return that owner's id value. This is performed in the scenario of a
+ * uni-directional, non-inverse one-to-many collection (which means that the collection elements do not maintain
+ * a direct reference to the owner).
+ *
+ * As such, the processing here is basically to loop over every entity currently associated with this persistence
+ * context and for those of the correct entity (sub) type to extract its collection role property value and see
+ * if the child is contained within that collection. If so, we have found the owner; if not, we go on.
+ *
+ * Also need to account for mergeMap which acts as a local copy cache managed for the duration of a merge
+ * operation. It represents a map of the detached entity instances pointing to the corresponding managed instance.
+ *
+ * @param entityName The entity name for the entity type which would own the child
+ * @param propertyName The name of the property on the owning entity type which would name this child association.
+ * @param childEntity The child entity instance for which to locate the owner instance id.
+ * @param mergeMap A map of non-persistent instances from an on-going merge operation (possibly null).
+ *
+ * @return The id of the entityName instance which is said to own the child; null if an appropriate owner not
+ * located.
*/
- public Serializable getOwnerId(String entity, String property, Object childObject, Map mergeMap);
+ public Serializable getOwnerId(String entityName, String propertyName, Object childEntity, Map mergeMap);
/**
* Search the persistence context for an index of the child object,
diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/TypedValue.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/TypedValue.java
index 87c8b48f47..8a9bee28a0 100644
--- a/hibernate-core/src/main/java/org/hibernate/engine/spi/TypedValue.java
+++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/TypedValue.java
@@ -70,12 +70,15 @@ public final class TypedValue implements Serializable {
}
@Override
public boolean equals(Object other) {
- if ( !(other instanceof TypedValue) ) return false;
- TypedValue that = (TypedValue) other;
- /*return that.type.equals(type) &&
- EqualsHelper.equals(that.value, value);*/
- return type.getReturnedClass() == that.type.getReturnedClass() &&
- type.isEqual(that.value, value );
+ if ( this == other ) {
+ return true;
+ }
+ if ( other == null || getClass() != other.getClass() ) {
+ return false;
+ }
+ final TypedValue that = (TypedValue) other;
+ return type.getReturnedClass() == that.type.getReturnedClass()
+ && type.isEqual( that.value, value );
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractFlushingEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractFlushingEventListener.java
index 509125f14b..81f889b50e 100644
--- a/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractFlushingEventListener.java
+++ b/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractFlushingEventListener.java
@@ -34,6 +34,7 @@ import org.hibernate.action.internal.CollectionRemoveAction;
import org.hibernate.action.internal.CollectionUpdateAction;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.internal.Cascade;
+import org.hibernate.engine.internal.CascadePoint;
import org.hibernate.engine.internal.Collections;
import org.hibernate.engine.spi.ActionQueue;
import org.hibernate.engine.spi.CascadingAction;
@@ -159,8 +160,7 @@ public abstract class AbstractFlushingEventListener implements Serializable {
throws HibernateException {
session.getPersistenceContext().incrementCascadeLevel();
try {
- new Cascade( getCascadingAction(), Cascade.BEFORE_FLUSH, session )
- .cascade( persister, object, anything );
+ new Cascade( getCascadingAction(), CascadePoint.BEFORE_FLUSH, session ).cascade( persister, object, anything );
}
finally {
session.getPersistenceContext().decrementCascadeLevel();
diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractSaveEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractSaveEventListener.java
index 4061393f7a..731c90f6be 100644
--- a/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractSaveEventListener.java
+++ b/hibernate-core/src/main/java/org/hibernate/event/internal/AbstractSaveEventListener.java
@@ -36,6 +36,7 @@ import org.hibernate.action.internal.EntityInsertAction;
import org.hibernate.bytecode.instrumentation.spi.FieldInterceptor;
import org.hibernate.classic.Lifecycle;
import org.hibernate.engine.internal.Cascade;
+import org.hibernate.engine.internal.CascadePoint;
import org.hibernate.engine.internal.ForeignKeys;
import org.hibernate.engine.internal.Versioning;
import org.hibernate.engine.spi.CascadingAction;
@@ -422,8 +423,11 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent
// cascade-save to many-to-one BEFORE the parent is saved
source.getPersistenceContext().incrementCascadeLevel();
try {
- new Cascade( getCascadeAction(), Cascade.BEFORE_INSERT_AFTER_DELETE, source )
- .cascade( persister, entity, anything );
+ new Cascade( getCascadeAction(), CascadePoint.BEFORE_INSERT_AFTER_DELETE, source ).cascade(
+ persister,
+ entity,
+ anything
+ );
}
finally {
source.getPersistenceContext().decrementCascadeLevel();
@@ -447,8 +451,11 @@ public abstract class AbstractSaveEventListener extends AbstractReassociateEvent
// cascade-save to collections AFTER the collection owner was saved
source.getPersistenceContext().incrementCascadeLevel();
try {
- new Cascade( getCascadeAction(), Cascade.AFTER_INSERT_BEFORE_DELETE, source )
- .cascade( persister, entity, anything );
+ new Cascade( getCascadeAction(), CascadePoint.AFTER_INSERT_BEFORE_DELETE, source ).cascade(
+ persister,
+ entity,
+ anything
+ );
}
finally {
source.getPersistenceContext().decrementCascadeLevel();
diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultDeleteEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultDeleteEventListener.java
index e993d6b1cf..f7d1a10747 100644
--- a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultDeleteEventListener.java
+++ b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultDeleteEventListener.java
@@ -35,6 +35,7 @@ import org.hibernate.TransientObjectException;
import org.hibernate.action.internal.EntityDeleteAction;
import org.hibernate.classic.Lifecycle;
import org.hibernate.engine.internal.Cascade;
+import org.hibernate.engine.internal.CascadePoint;
import org.hibernate.engine.internal.ForeignKeys;
import org.hibernate.engine.internal.Nullability;
import org.hibernate.engine.spi.CascadingActions;
@@ -321,8 +322,11 @@ public class DefaultDeleteEventListener implements DeleteEventListener {
session.getPersistenceContext().incrementCascadeLevel();
try {
// cascade-delete to collections BEFORE the collection owner is deleted
- new Cascade( CascadingActions.DELETE, Cascade.AFTER_INSERT_BEFORE_DELETE, session )
- .cascade( persister, entity, transientEntities );
+ new Cascade( CascadingActions.DELETE, CascadePoint.AFTER_INSERT_BEFORE_DELETE, session ).cascade(
+ persister,
+ entity,
+ transientEntities
+ );
}
finally {
session.getPersistenceContext().decrementCascadeLevel();
@@ -341,8 +345,11 @@ public class DefaultDeleteEventListener implements DeleteEventListener {
session.getPersistenceContext().incrementCascadeLevel();
try {
// cascade-delete to many-to-one AFTER the parent was deleted
- new Cascade( CascadingActions.DELETE, Cascade.BEFORE_INSERT_AFTER_DELETE, session )
- .cascade( persister, entity, transientEntities );
+ new Cascade( CascadingActions.DELETE, CascadePoint.BEFORE_INSERT_AFTER_DELETE, session ).cascade(
+ persister,
+ entity,
+ transientEntities
+ );
}
finally {
session.getPersistenceContext().decrementCascadeLevel();
diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultEvictEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultEvictEventListener.java
index c9c6ea84c9..453f6ad071 100644
--- a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultEvictEventListener.java
+++ b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultEvictEventListener.java
@@ -29,6 +29,7 @@ import org.jboss.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.engine.internal.Cascade;
+import org.hibernate.engine.internal.CascadePoint;
import org.hibernate.engine.spi.CascadingActions;
import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.EntityKey;
@@ -142,7 +143,6 @@ public class DefaultEvictEventListener implements EvictEventListener {
// This is now handled by removeEntity()
//session.getPersistenceContext().removeDatabaseSnapshot(key);
- new Cascade( CascadingActions.EVICT, Cascade.AFTER_EVICT, session )
- .cascade( persister, object );
+ new Cascade( CascadingActions.EVICT, CascadePoint.AFTER_EVICT, session ).cascade( persister, object );
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultLockEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultLockEventListener.java
index 1c39af11b2..e600b11c27 100644
--- a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultLockEventListener.java
+++ b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultLockEventListener.java
@@ -31,6 +31,7 @@ import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.TransientObjectException;
import org.hibernate.engine.internal.Cascade;
+import org.hibernate.engine.internal.CascadePoint;
import org.hibernate.engine.internal.ForeignKeys;
import org.hibernate.engine.spi.CascadingActions;
import org.hibernate.engine.spi.EntityEntry;
@@ -102,8 +103,11 @@ public class DefaultLockEventListener extends AbstractLockUpgradeEventListener i
EventSource source = event.getSession();
source.getPersistenceContext().incrementCascadeLevel();
try {
- new Cascade( CascadingActions.LOCK, Cascade.AFTER_LOCK, source)
- .cascade( persister, entity, event.getLockOptions() );
+ new Cascade( CascadingActions.LOCK, CascadePoint.AFTER_LOCK, source).cascade(
+ persister,
+ entity,
+ event.getLockOptions()
+ );
}
finally {
source.getPersistenceContext().decrementCascadeLevel();
diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultMergeEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultMergeEventListener.java
index 2a46265d37..6b1f1b85f2 100755
--- a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultMergeEventListener.java
+++ b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultMergeEventListener.java
@@ -35,6 +35,7 @@ import org.hibernate.StaleObjectStateException;
import org.hibernate.WrongClassException;
import org.hibernate.bytecode.instrumentation.spi.FieldInterceptor;
import org.hibernate.engine.internal.Cascade;
+import org.hibernate.engine.internal.CascadePoint;
import org.hibernate.engine.spi.CascadingAction;
import org.hibernate.engine.spi.CascadingActions;
import org.hibernate.engine.spi.EntityEntry;
@@ -437,8 +438,7 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener impleme
) {
source.getPersistenceContext().incrementCascadeLevel();
try {
- new Cascade( getCascadeAction(), Cascade.BEFORE_MERGE, source )
- .cascade(persister, entity, copyCache);
+ new Cascade( getCascadeAction(), CascadePoint.BEFORE_MERGE, source ).cascade( persister, entity, copyCache );
}
finally {
source.getPersistenceContext().decrementCascadeLevel();
diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultRefreshEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultRefreshEventListener.java
index d37818046d..2c4de4a1fd 100644
--- a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultRefreshEventListener.java
+++ b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultRefreshEventListener.java
@@ -34,6 +34,7 @@ import org.hibernate.PersistentObjectException;
import org.hibernate.UnresolvableObjectException;
import org.hibernate.cache.spi.CacheKey;
import org.hibernate.engine.internal.Cascade;
+import org.hibernate.engine.internal.CascadePoint;
import org.hibernate.engine.spi.CascadingActions;
import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.EntityKey;
@@ -118,9 +119,12 @@ public class DefaultRefreshEventListener implements RefreshEventListener {
}
// cascade the refresh prior to refreshing this entity
- refreshedAlready.put(object, object);
- new Cascade( CascadingActions.REFRESH, Cascade.BEFORE_REFRESH, source)
- .cascade( persister, object, refreshedAlready );
+ refreshedAlready.put( object, object );
+ new Cascade( CascadingActions.REFRESH, CascadePoint.BEFORE_REFRESH, source ).cascade(
+ persister,
+ object,
+ refreshedAlready
+ );
if ( e != null ) {
final EntityKey key = source.generateEntityKey( id, persister );
diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultReplicateEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultReplicateEventListener.java
index 910faabf3c..c2e750a07f 100644
--- a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultReplicateEventListener.java
+++ b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultReplicateEventListener.java
@@ -32,6 +32,7 @@ import org.hibernate.LockMode;
import org.hibernate.ReplicationMode;
import org.hibernate.TransientObjectException;
import org.hibernate.engine.internal.Cascade;
+import org.hibernate.engine.internal.CascadePoint;
import org.hibernate.engine.spi.CascadingAction;
import org.hibernate.engine.spi.CascadingActions;
import org.hibernate.engine.spi.EntityKey;
@@ -209,8 +210,11 @@ public class DefaultReplicateEventListener extends AbstractSaveEventListener imp
EventSource source) {
source.getPersistenceContext().incrementCascadeLevel();
try {
- new Cascade( CascadingActions.REPLICATE, Cascade.AFTER_UPDATE, source )
- .cascade( persister, entity, replicationMode );
+ new Cascade( CascadingActions.REPLICATE, CascadePoint.AFTER_UPDATE, source ).cascade(
+ persister,
+ entity,
+ replicationMode
+ );
}
finally {
source.getPersistenceContext().decrementCascadeLevel();
diff --git a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultSaveOrUpdateEventListener.java b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultSaveOrUpdateEventListener.java
index 7948e31c4a..3b6e769203 100755
--- a/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultSaveOrUpdateEventListener.java
+++ b/hibernate-core/src/main/java/org/hibernate/event/internal/DefaultSaveOrUpdateEventListener.java
@@ -34,6 +34,7 @@ import org.hibernate.PersistentObjectException;
import org.hibernate.TransientObjectException;
import org.hibernate.classic.Lifecycle;
import org.hibernate.engine.internal.Cascade;
+import org.hibernate.engine.internal.CascadePoint;
import org.hibernate.engine.spi.CascadingAction;
import org.hibernate.engine.spi.CascadingActions;
import org.hibernate.engine.spi.EntityEntry;
@@ -359,11 +360,10 @@ public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener
* @param entity The entity being updated.
*/
private void cascadeOnUpdate(SaveOrUpdateEvent event, EntityPersister persister, Object entity) {
- EventSource source = event.getSession();
+ final EventSource source = event.getSession();
source.getPersistenceContext().incrementCascadeLevel();
try {
- new Cascade( CascadingActions.SAVE_UPDATE, Cascade.AFTER_UPDATE, source )
- .cascade( persister, entity );
+ new Cascade( CascadingActions.SAVE_UPDATE, CascadePoint.AFTER_UPDATE, source ).cascade( persister, entity );
}
finally {
source.getPersistenceContext().decrementCascadeLevel();
diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/QueryExecutionRequestException.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/QueryExecutionRequestException.java
index c20f56e9fc..f55bdaf782 100644
--- a/hibernate-core/src/main/java/org/hibernate/hql/internal/QueryExecutionRequestException.java
+++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/QueryExecutionRequestException.java
@@ -33,5 +33,8 @@ import org.hibernate.QueryException;
public class QueryExecutionRequestException extends QueryException {
public QueryExecutionRequestException(String message, String queryString) {
super( message, queryString );
+ if ( queryString == null ) {
+ throw new IllegalArgumentException( "Illegal to pass null as queryString argument" );
+ }
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/ErrorCounter.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/ErrorCounter.java
index bee855397e..a520c54347 100644
--- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/ErrorCounter.java
+++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/ErrorCounter.java
@@ -37,48 +37,77 @@ import org.hibernate.internal.CoreMessageLogger;
* An error handler that counts parsing errors and warnings.
*/
public class ErrorCounter implements ParseErrorHandler {
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ ErrorCounter.class.getName()
+ );
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, ErrorCounter.class.getName());
+ private final String hql;
- private List errorList = new ArrayList();
- private List warningList = new ArrayList();
- private List recognitionExceptions = new ArrayList();
+ private List errorList = new ArrayList();
+ private List recognitionExceptions = new ArrayList();
+ /**
+ * Constructs an ErrorCounter without knowledge of the HQL, meaning that generated QueryException
+ * instances *will not* contain the HQL (and will need to be wrapped at a higher level in another
+ * QueryException).
+ */
+ public ErrorCounter() {
+ this( null );
+ }
+
+ /**
+ * Constructs an ErrorCounter with knowledge of the HQL, meaning that generated QueryException
+ * instances *will* contain the HQL.
+ */
+ public ErrorCounter(String hql) {
+ this.hql = hql;
+ }
+
+ @Override
public void reportError(RecognitionException e) {
reportError( e.toString() );
recognitionExceptions.add( e );
- LOG.error(e.toString(), e);
+ LOG.error( e.toString(), e );
}
+ @Override
public void reportError(String message) {
- LOG.error(message);
+ LOG.error( message );
errorList.add( message );
}
+ @Override
public int getErrorCount() {
return errorList.size();
}
+ @Override
public void reportWarning(String message) {
- LOG.debug(message);
- warningList.add( message );
+ LOG.debug( message );
}
private String getErrorString() {
- StringBuilder buf = new StringBuilder();
- for ( Iterator iterator = errorList.iterator(); iterator.hasNext(); ) {
- buf.append( ( String ) iterator.next() );
- if ( iterator.hasNext() ) buf.append( "\n" );
+ final StringBuilder buf = new StringBuilder();
+ final Iterator iterator = errorList.iterator();
+ while ( iterator.hasNext() ) {
+ buf.append( iterator.next() );
+ if ( iterator.hasNext() ) {
+ buf.append( "\n" );
+ }
}
return buf.toString();
}
+ @Override
public void throwQueryException() throws QueryException {
if ( getErrorCount() > 0 ) {
- if (recognitionExceptions.size() > 0) throw QuerySyntaxException.convert((RecognitionException)recognitionExceptions.get(0));
- throw new QueryException(getErrorString());
- }
- LOG.debug("throwQueryException() : no errors");
+ if ( recognitionExceptions.size() > 0 ) {
+ throw QuerySyntaxException.convert( recognitionExceptions.get( 0 ), hql );
+ }
+ throw new QueryException( getErrorString(), hql );
+ }
+ LOG.debug( "throwQueryException() : no errors" );
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlParser.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlParser.java
index b9f0bbd8e5..0a886e0e13 100644
--- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlParser.java
+++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlParser.java
@@ -52,25 +52,35 @@ import org.hibernate.internal.util.StringHelper;
* @author Joshua Davis (pgmjsd@sourceforge.net)
*/
public final class HqlParser extends HqlBaseParser {
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ HqlParser.class.getName()
+ );
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, HqlParser.class.getName());
-
- private ParseErrorHandler parseErrorHandler;
- private ASTPrinter printer = getASTPrinter();
+ private final ParseErrorHandler parseErrorHandler;
+ private final ASTPrinter printer = getASTPrinter();
private static ASTPrinter getASTPrinter() {
return new ASTPrinter( org.hibernate.hql.internal.antlr.HqlTokenTypes.class );
}
+ /**
+ * Get a HqlParser instance for the given HQL string.
+ *
+ * @param hql The HQL query string
+ *
+ * @return The parser.
+ */
public static HqlParser getInstance(String hql) {
- // [jsd] The fix for HHH-558...
- HqlLexer lexer = new HqlLexer( new StringReader( hql ) );
- return new HqlParser( lexer );
+ return new HqlParser( hql );
}
- private HqlParser(TokenStream lexer) {
- super( lexer );
- initialize();
+ private HqlParser(String hql) {
+ // The fix for HHH-558...
+ super( new HqlLexer( new StringReader( hql ) ) );
+ parseErrorHandler = new ErrorCounter( hql );
+ // Create nodes that track line and column number.
+ setASTFactory( new HqlASTFactory() );
}
@@ -326,12 +336,6 @@ public final class HqlParser extends HqlBaseParser {
printer.showAst( ast, pw );
}
- private void initialize() {
- // Initialize the error handling delegate.
- parseErrorHandler = new ErrorCounter();
- setASTFactory(new HqlASTFactory()); // Create nodes that track line and column number.
- }
-
@Override
public void weakKeywords() throws TokenStreamException {
diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java
index 2c3beb7f74..8f32783230 100644
--- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java
+++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java
@@ -170,7 +170,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par
String collectionRole) {
setASTFactory( new SqlASTFactory( this ) );
// Initialize the error handling delegate.
- this.parseErrorHandler = new ErrorCounter();
+ this.parseErrorHandler = new ErrorCounter( qti.getQueryString() );
this.queryTranslatorImpl = qti;
this.sessionFactoryHelper = new SessionFactoryHelper( sfi );
this.literalProcessor = new LiteralProcessor( this );
@@ -410,7 +410,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par
AST hqlSqlWithNode = returnAST;
if (LOG.isDebugEnabled()) LOG.debugf("handleWithFragment() : %s",
getASTPrinter().showAsString(hqlSqlWithNode, "-- with clause --"));
- WithClauseVisitor visitor = new WithClauseVisitor( fromElement );
+ WithClauseVisitor visitor = new WithClauseVisitor( fromElement, queryTranslatorImpl );
NodeTraverser traverser = new NodeTraverser( visitor );
traverser.traverseDepthFirst( hqlSqlWithNode );
@@ -421,7 +421,10 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par
else {
FromElement referencedFromElement = visitor.getReferencedFromElement();
if ( referencedFromElement != fromElement ) {
- throw new InvalidWithClauseException( "with-clause expressions did not reference from-clause element to which the with-clause was associated" );
+ throw new InvalidWithClauseException(
+ "with-clause expressions did not reference from-clause element to which the with-clause was associated",
+ queryTranslatorImpl.getQueryString()
+ );
}
}
@@ -443,11 +446,14 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par
private static class WithClauseVisitor implements NodeTraverser.VisitationStrategy {
private final FromElement joinFragment;
+ private final QueryTranslatorImpl queryTranslatorImpl;
+
private FromElement referencedFromElement;
private String joinAlias;
- public WithClauseVisitor(FromElement fromElement) {
+ public WithClauseVisitor(FromElement fromElement, QueryTranslatorImpl queryTranslatorImpl) {
this.joinFragment = fromElement;
+ this.queryTranslatorImpl = queryTranslatorImpl;
}
public void visit(AST node) {
@@ -477,7 +483,10 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par
// creates and renders the join fragments for inheritance
// hierarchies...
if ( !joinAlias.equals( referencedFromElement.getTableAlias() ) ) {
- throw new InvalidWithClauseException( "with clause can only reference columns in the driving table" );
+ throw new InvalidWithClauseException(
+ "with clause can only reference columns in the driving table",
+ queryTranslatorImpl.getQueryString()
+ );
}
}
}
@@ -1059,9 +1068,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par
public int[] getNamedParameterLocations(String name) throws QueryException {
Object o = namedParameters.get( name );
if ( o == null ) {
- QueryException qe = new QueryException( QueryTranslator.ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name );
- qe.setQueryString( queryTranslatorImpl.getQueryString() );
- throw qe;
+ throw new QueryException( QueryTranslator.ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name, queryTranslatorImpl.getQueryString() );
}
if ( o instanceof Integer ) {
return new int[]{ (Integer) o };
diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/InvalidWithClauseException.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/InvalidWithClauseException.java
index aa7f97e336..1630801054 100644
--- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/InvalidWithClauseException.java
+++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/InvalidWithClauseException.java
@@ -30,11 +30,10 @@ package org.hibernate.hql.internal.ast;
* @author Steve Ebersole
*/
public class InvalidWithClauseException extends QuerySyntaxException {
- public InvalidWithClauseException(String message) {
- super( message );
- }
-
public InvalidWithClauseException(String message, String queryString) {
super( message, queryString );
+ if ( queryString == null ) {
+ throw new IllegalArgumentException( "Illegal to pass null as queryString argument" );
+ }
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java
index b4a2456896..c651ecdd15 100644
--- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java
+++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -20,7 +20,6 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
- *
*/
package org.hibernate.hql.internal.ast;
import antlr.RecognitionException;
@@ -33,20 +32,57 @@ import org.hibernate.QueryException;
* @author josh
*/
public class QuerySyntaxException extends QueryException {
-
+ /**
+ * Constructs a QuerySyntaxException
+ *
+ * @param message Message explaining the condition that led to the exception
+ */
public QuerySyntaxException(String message) {
super( message );
}
+ /**
+ * Constructs a QuerySyntaxException
+ *
+ * @param message Message explaining the condition that led to the exception
+ * @param hql The hql query that was being parsed/analyzed
+ */
public QuerySyntaxException(String message, String hql) {
- this( message );
- setQueryString( hql );
+ super( message, hql );
}
+ /**
+ * Intended for use solely from {@link #generateQueryException(String)}
+ *
+ * @param message Message explaining the condition that led to the exception
+ * @param queryString The hql query that was being parsed/analyzed
+ * @param cause The cause, generally another QuerySyntaxException
+ */
+ protected QuerySyntaxException(String message, String queryString, Exception cause) {
+ super( message, queryString, cause );
+ }
+
+ /**
+ * Converts the given ANTLR RecognitionException into a QuerySyntaxException. The RecognitionException
+ * does not become the cause because ANTLR exceptions are not serializable.
+ *
+ * @param e The ANTLR exception
+ *
+ * @return The QuerySyntaxException
+ */
public static QuerySyntaxException convert(RecognitionException e) {
return convert( e, null );
}
+ /**
+ * Converts the given ANTLR RecognitionException into a QuerySyntaxException. The RecognitionException
+ * does not become the cause because ANTLR exceptions are not serializable.
+ *
+ * @param e The ANTLR exception
+ * @param hql The query string
+ *
+ * @return The QuerySyntaxException
+ */
public static QuerySyntaxException convert(RecognitionException e, String hql) {
String positionInfo = e.getLine() > 0 && e.getColumn() > 0
? " near line " + e.getLine() + ", column " + e.getColumn()
@@ -54,4 +90,8 @@ public class QuerySyntaxException extends QueryException {
return new QuerySyntaxException( e.getMessage() + positionInfo, hql );
}
+ @Override
+ protected QueryException generateQueryException(String queryString) {
+ return new QuerySyntaxException( getOriginalMessage(), queryString, this );
+ }
}
diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java
index 915142ffc3..61c7d0c6d4 100644
--- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java
@@ -78,8 +78,10 @@ import org.hibernate.type.Type;
* @author Joshua Davis (pgmjsd@sourceforge.net)
*/
public class QueryTranslatorImpl implements FilterTranslator {
-
- private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, QueryTranslatorImpl.class.getName());
+ private static final CoreMessageLogger LOG = Logger.getMessageLogger(
+ CoreMessageLogger.class,
+ QueryTranslatorImpl.class.getName()
+ );
private SessionFactoryImplementor factory;
@@ -132,8 +134,8 @@ public class QueryTranslatorImpl implements FilterTranslator {
* @throws MappingException There was a problem querying defined mappings.
*/
public void compile(
- Map replacements,
- boolean shallow) throws QueryException, MappingException {
+ Map replacements,
+ boolean shallow) throws QueryException, MappingException {
doCompile( replacements, shallow, null );
}
@@ -148,9 +150,9 @@ public class QueryTranslatorImpl implements FilterTranslator {
* @throws MappingException There was a problem querying defined mappings.
*/
public void compile(
- String collectionRole,
- Map replacements,
- boolean shallow) throws QueryException, MappingException {
+ String collectionRole,
+ Map replacements,
+ boolean shallow) throws QueryException, MappingException {
doCompile( replacements, shallow, collectionRole );
}
@@ -178,12 +180,12 @@ public class QueryTranslatorImpl implements FilterTranslator {
try {
// PHASE 1 : Parse the HQL into an AST.
- HqlParser parser = parse( true );
+ final HqlParser parser = parse( true );
// PHASE 2 : Analyze the HQL AST, and produce an SQL AST.
- HqlSqlWalker w = analyze( parser, collectionRole );
+ final HqlSqlWalker w = analyze( parser, collectionRole );
- sqlAst = ( Statement ) w.getAST();
+ sqlAst = (Statement) w.getAST();
// at some point the generate phase needs to be moved out of here,
// because a single object-level DML might spawn multiple SQL DML
@@ -201,15 +203,19 @@ public class QueryTranslatorImpl implements FilterTranslator {
}
else {
// PHASE 3 : Generate the SQL.
- generate( ( QueryNode ) sqlAst );
+ generate( (QueryNode) sqlAst );
queryLoader = new QueryLoader( this, factory, w.getSelectClause() );
}
compiled = true;
}
catch ( QueryException qe ) {
- qe.setQueryString( hql );
- throw qe;
+ if ( qe.getQueryString() == null ) {
+ throw qe.wrapWithQueryString( hql );
+ }
+ else {
+ throw qe;
+ }
}
catch ( RecognitionException e ) {
// we do not actually propagate ANTLRExceptions as a cause, so
@@ -224,12 +230,13 @@ public class QueryTranslatorImpl implements FilterTranslator {
throw new QueryException( e.getMessage(), hql );
}
- this.enabledFilters = null; //only needed during compilation phase...
+ //only needed during compilation phase...
+ this.enabledFilters = null;
}
private void generate(AST sqlAst) throws QueryException, RecognitionException {
if ( sql == null ) {
- SqlGenerator gen = new SqlGenerator(factory);
+ final SqlGenerator gen = new SqlGenerator( factory );
gen.statement( sqlAst );
sql = gen.getSQL();
if ( LOG.isDebugEnabled() ) {
@@ -241,16 +248,17 @@ public class QueryTranslatorImpl implements FilterTranslator {
}
}
+ private static final ASTPrinter SQL_TOKEN_PRINTER = new ASTPrinter( SqlTokenTypes.class );
+
private HqlSqlWalker analyze(HqlParser parser, String collectionRole) throws QueryException, RecognitionException {
- HqlSqlWalker w = new HqlSqlWalker( this, factory, parser, tokenReplacements, collectionRole );
- AST hqlAst = parser.getAST();
+ final HqlSqlWalker w = new HqlSqlWalker( this, factory, parser, tokenReplacements, collectionRole );
+ final AST hqlAst = parser.getAST();
// Transform the tree.
w.statement( hqlAst );
if ( LOG.isDebugEnabled() ) {
- ASTPrinter printer = new ASTPrinter( SqlTokenTypes.class );
- LOG.debug( printer.showAsString( w.getAST(), "--- SQL AST ---" ) );
+ LOG.debug( SQL_TOKEN_PRINTER.showAsString( w.getAST(), "--- SQL AST ---" ) );
}
w.getParseErrorHandler().throwQueryException();
@@ -260,16 +268,15 @@ public class QueryTranslatorImpl implements FilterTranslator {
private HqlParser parse(boolean filter) throws TokenStreamException, RecognitionException {
// Parse the query string into an HQL AST.
- HqlParser parser = HqlParser.getInstance( hql );
+ final HqlParser parser = HqlParser.getInstance( hql );
parser.setFilter( filter );
LOG.debugf( "parse() - HQL: %s", hql );
parser.statement();
- AST hqlAst = parser.getAST();
+ final AST hqlAst = parser.getAST();
- JavaConstantConverter converter = new JavaConstantConverter();
- NodeTraverser walker = new NodeTraverser( converter );
+ final NodeTraverser walker = new NodeTraverser( new JavaConstantConverter() );
walker.traverseDepthFirst( hqlAst );
showHqlAst( hqlAst );
@@ -278,10 +285,11 @@ public class QueryTranslatorImpl implements FilterTranslator {
return parser;
}
+ private static final ASTPrinter HQL_TOKEN_PRINTER = new ASTPrinter( HqlTokenTypes.class );
+
void showHqlAst(AST hqlAst) {
if ( LOG.isDebugEnabled() ) {
- ASTPrinter printer = new ASTPrinter( HqlTokenTypes.class );
- LOG.debug( printer.showAsString( hqlAst, "--- HQL AST ---" ) );
+ LOG.debug( HQL_TOKEN_PRINTER.showAsString( hqlAst, "--- HQL AST ---" ) );
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/BooleanLiteralNode.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/BooleanLiteralNode.java
index 5da071d3c4..c7a712d3ce 100644
--- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/BooleanLiteralNode.java
+++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/BooleanLiteralNode.java
@@ -61,7 +61,7 @@ public class BooleanLiteralNode extends LiteralNode implements ExpectedTypeAware
try {
return typeAsLiteralType().objectToSQLString( getValue(), sessionFactory.getDialect() );
}
- catch( Throwable t ) {
+ catch( Exception t ) {
throw new QueryException( "Unable to render boolean literal value", t );
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/JavaConstantNode.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/JavaConstantNode.java
index 82fb6ba00a..4d2af46998 100644
--- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/JavaConstantNode.java
+++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/JavaConstantNode.java
@@ -84,7 +84,7 @@ public class JavaConstantNode extends Node implements ExpectedTypeAwareNode, Ses
Dialect dialect = factory.getDialect();
return literalType.objectToSQLString( constantValue, dialect );
}
- catch ( Throwable t ) {
+ catch ( Exception t ) {
throw new QueryException( QueryTranslator.ERROR_CANNOT_FORMAT_LITERAL + constantExpression, t );
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/classic/QueryTranslatorImpl.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/classic/QueryTranslatorImpl.java
index ddc8c770dc..74d9c70ab6 100644
--- a/hibernate-core/src/main/java/org/hibernate/hql/internal/classic/QueryTranslatorImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/classic/QueryTranslatorImpl.java
@@ -245,8 +245,12 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
renderSQL();
}
catch ( QueryException qe ) {
- qe.setQueryString( queryString );
- throw qe;
+ if ( qe.getQueryString() == null ) {
+ throw qe.wrapWithQueryString( queryString );
+ }
+ else {
+ throw qe;
+ }
}
catch ( MappingException me ) {
throw me;
@@ -254,9 +258,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
catch ( Exception e ) {
LOG.debug( "Unexpected query compilation problem", e );
e.printStackTrace();
- QueryException qe = new QueryException( "Incorrect query syntax", e );
- qe.setQueryString( queryString );
- throw qe;
+ throw new QueryException( "Incorrect query syntax", queryString, e );
}
postInstantiate();
@@ -548,9 +550,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
public int[] getNamedParameterLocs(String name) throws QueryException {
Object o = namedParameters.get( name );
if ( o == null ) {
- QueryException qe = new QueryException( ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name );
- qe.setQueryString( queryString );
- throw qe;
+ throw new QueryException( ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name, queryString );
}
if ( o instanceof Integer ) return new int[] { (Integer) o };
else {
diff --git a/hibernate-core/src/main/java/org/hibernate/internal/AbstractQueryImpl.java b/hibernate-core/src/main/java/org/hibernate/internal/AbstractQueryImpl.java
index a8a492f165..f8e08a4e5e 100644
--- a/hibernate-core/src/main/java/org/hibernate/internal/AbstractQueryImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/internal/AbstractQueryImpl.java
@@ -562,7 +562,7 @@ public abstract class AbstractQueryImpl implements Query {
}
public Query setCharacter(int position, char val) {
- setParameter(position, new Character(val), StandardBasicTypes.CHARACTER);
+ setParameter( position, Character.valueOf( val ), StandardBasicTypes.CHARACTER );
return this;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/internal/CacheImpl.java b/hibernate-core/src/main/java/org/hibernate/internal/CacheImpl.java
index fed89a828e..9be13fd9c8 100644
--- a/hibernate-core/src/main/java/org/hibernate/internal/CacheImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/internal/CacheImpl.java
@@ -64,7 +64,7 @@ public class CacheImpl implements CacheImplementor {
private final Settings settings;
private final boolean isQueryCacheEnabled;
private transient QueryCache queryCache;
- private transient RegionFactory regionFactory;
+ private final transient RegionFactory regionFactory;
private transient UpdateTimestampsCache updateTimestampsCache;
private transient ConcurrentMap queryCaches;
private final transient ConcurrentMap allCacheRegions = new ConcurrentHashMap();
@@ -73,7 +73,10 @@ public class CacheImpl implements CacheImplementor {
this.sessionFactory = sessionFactory;
this.settings = sessionFactory.getSettings();
this.serviceRegistry = sessionFactory.getServiceRegistry();
- this.isQueryCacheEnabled = isQueryCacheEnabled();
+ this.isQueryCacheEnabled = serviceRegistry.getService( ConfigurationService.class ).getSetting( AvailableSettings.USE_QUERY_CACHE,
+ StandardConverters.BOOLEAN, false
+ );
+ this.regionFactory = serviceRegistry.getService( RegionFactory.class );
}
@@ -226,12 +229,6 @@ public class CacheImpl implements CacheImplementor {
}
}
- private boolean isQueryCacheEnabled(){
- return serviceRegistry.getService( ConfigurationService.class ).getSetting( AvailableSettings.USE_QUERY_CACHE,
- StandardConverters.BOOLEAN, false
- );
- }
-
@Override
public void evictQueryRegion(String regionName) {
if ( regionName == null ) {
@@ -346,11 +343,6 @@ public class CacheImpl implements CacheImplementor {
return regionFactory;
}
- @InjectService
- public void injectRegionFactory(RegionFactory regionFactory){
- this.regionFactory = regionFactory;
- }
-
@Override
public void start() {
if ( isQueryCacheEnabled ) {
diff --git a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java
index 33cafba164..a3fcc8e3a4 100644
--- a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java
+++ b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java
@@ -1663,4 +1663,8 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Exception while loading a class or resource found during scanning", id = 458)
void unableToLoadScannedClassOrResource(@Cause Exception e);
+
+ @LogMessage(level = WARN)
+ @Message(value = "Exception while discovering OSGi service implementations : %s", id = 459)
+ void unableToDiscoverOsgiService(String service, @Cause Exception e);
}
diff --git a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java
index 9cdfd99886..d40db42ce0 100644
--- a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java
+++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java
@@ -24,6 +24,7 @@
package org.hibernate.internal;
import java.util.Hashtable;
+import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.naming.Context;
import javax.naming.Name;
@@ -53,15 +54,34 @@ public class SessionFactoryRegistry {
SessionFactoryRegistry.class.getName()
);
+ /**
+ * Singleton access
+ */
public static final SessionFactoryRegistry INSTANCE = new SessionFactoryRegistry();
+ /**
+ * A map for mapping the UUID of a SessionFactory to the corresponding SessionFactory instance
+ */
private final ConcurrentHashMap sessionFactoryMap = new ConcurrentHashMap();
+
+ /**
+ * A cross-reference for mapping a SessionFactory name to its UUID. Not all SessionFactories get named,
+ */
private final ConcurrentHashMap nameUuidXref = new ConcurrentHashMap();
- public SessionFactoryRegistry() {
+ private SessionFactoryRegistry() {
LOG.debugf( "Initializing SessionFactoryRegistry : %s", this );
}
+ /**
+ * Adds a SessionFactory to the registry
+ *
+ * @param uuid The uuid under which to register the SessionFactory
+ * @param name The optional name under which to register the SessionFactory
+ * @param isNameAlsoJndiName Is name, if provided, also a JNDI name?
+ * @param instance The SessionFactory instance
+ * @param jndiService The JNDI service, so we can register a listener if name is a JNDI name
+ */
public void addSessionFactory(
String uuid,
String name,
@@ -72,7 +92,7 @@ public class SessionFactoryRegistry {
throw new IllegalArgumentException( "SessionFactory UUID cannot be null" );
}
- LOG.debugf( "Registering SessionFactory: %s (%s)", uuid, name == null ? "" : name );
+ LOG.debugf( "Registering SessionFactory: %s (%s)", uuid, name == null ? "" : name );
sessionFactoryMap.put( uuid, instance );
if ( name != null ) {
nameUuidXref.put( name, uuid );
@@ -103,6 +123,14 @@ public class SessionFactoryRegistry {
}
}
+ /**
+ * Remove a previously added SessionFactory
+ *
+ * @param uuid The uuid
+ * @param name The optional name
+ * @param isNameAlsoJndiName Is name, if provided, also a JNDI name?
+ * @param jndiService The JNDI service
+ */
public void removeSessionFactory(
String uuid,
String name,
@@ -129,8 +157,15 @@ public class SessionFactoryRegistry {
sessionFactoryMap.remove( uuid );
}
+ /**
+ * Get a registered SessionFactory by name
+ *
+ * @param name The name
+ *
+ * @return The SessionFactory
+ */
public SessionFactory getNamedSessionFactory(String name) {
- LOG.debugf( "Lookup: name=%s", name );
+ LOG.debugf( "Lookup: name=%s", name );
final String uuid = nameUuidXref.get( name );
return getSessionFactory( uuid );
}
@@ -145,6 +180,27 @@ public class SessionFactoryRegistry {
return sessionFactory;
}
+ /**
+ * Does this registry currently contain registrations?
+ *
+ * @return true/false
+ */
+ public boolean hasRegistrations() {
+ return ! sessionFactoryMap.isEmpty();
+ }
+
+ public void clearRegistrations() {
+ nameUuidXref.clear();
+ for ( SessionFactory factory : sessionFactoryMap.values() ) {
+ try {
+ factory.close();
+ }
+ catch (Exception ignore) {
+ }
+ }
+ sessionFactoryMap.clear();
+ }
+
/**
* Implementation of {@literal JNDI} {@link javax.naming.event.NamespaceChangeListener} contract to listener for context events
* and react accordingly if necessary
@@ -152,7 +208,7 @@ public class SessionFactoryRegistry {
private final NamespaceChangeListener LISTENER = new NamespaceChangeListener() {
@Override
public void objectAdded(NamingEvent evt) {
- LOG.debugf("A factory was successfully bound to name: %s", evt.getNewBinding().getName());
+ LOG.debugf("A factory was successfully bound to name: %s", evt.getNewBinding().getName());
}
@Override
@@ -172,7 +228,7 @@ public class SessionFactoryRegistry {
final String oldJndiName = evt.getOldBinding().getName();
final String newJndiName = evt.getNewBinding().getName();
- LOG.factoryJndiRename( oldJndiName, newJndiName );
+ LOG.factoryJndiRename( oldJndiName, newJndiName );
final String uuid = nameUuidXref.remove( oldJndiName );
nameUuidXref.put( newJndiName, uuid );
diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/StringHelper.java b/hibernate-core/src/main/java/org/hibernate/internal/util/StringHelper.java
index ce71b8aefd..572eb443df 100644
--- a/hibernate-core/src/main/java/org/hibernate/internal/util/StringHelper.java
+++ b/hibernate-core/src/main/java/org/hibernate/internal/util/StringHelper.java
@@ -91,7 +91,7 @@ public final class StringHelper {
}
public static String[] add(String[] x, String sep, String[] y) {
- String[] result = new String[x.length];
+ final String[] result = new String[x.length];
for ( int i = 0; i < x.length; i++ ) {
result[i] = x[i] + sep + y[i];
}
diff --git a/hibernate-core/src/main/java/org/hibernate/loader/Loader.java b/hibernate-core/src/main/java/org/hibernate/loader/Loader.java
index 0b78c1bd63..784559c18d 100644
--- a/hibernate-core/src/main/java/org/hibernate/loader/Loader.java
+++ b/hibernate-core/src/main/java/org/hibernate/loader/Loader.java
@@ -1099,7 +1099,7 @@ public abstract class Loader {
if ( LOG.isTraceEnabled() )
LOG.tracev( "Total objects hydrated: {0}", hydratedObjectsSize );
for ( int i = 0; i < hydratedObjectsSize; i++ ) {
- TwoPhaseLoad.initializeEntity( hydratedObjects.get(i), readOnly, session, pre, post );
+ TwoPhaseLoad.initializeEntity( hydratedObjects.get(i), readOnly, session, pre );
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaQueryTranslator.java b/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaQueryTranslator.java
index a543cb8d2a..868c8d5483 100755
--- a/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaQueryTranslator.java
+++ b/hibernate-core/src/main/java/org/hibernate/loader/criteria/CriteriaQueryTranslator.java
@@ -498,18 +498,18 @@ public class CriteriaQueryTranslator implements CriteriaQuery {
}
}
- public String[] getIdentifierColumns(Criteria subcriteria) {
+ public String[] getIdentifierColumns(Criteria criteria) {
String[] idcols =
- ( ( Loadable ) getPropertyMapping( getEntityName( subcriteria ) ) ).getIdentifierColumnNames();
- return StringHelper.qualify( getSQLAlias( subcriteria ), idcols );
+ ( ( Loadable ) getPropertyMapping( getEntityName( criteria ) ) ).getIdentifierColumnNames();
+ return StringHelper.qualify( getSQLAlias( criteria ), idcols );
}
- public Type getIdentifierType(Criteria subcriteria) {
- return ( ( Loadable ) getPropertyMapping( getEntityName( subcriteria ) ) ).getIdentifierType();
+ public Type getIdentifierType(Criteria criteria) {
+ return ( ( Loadable ) getPropertyMapping( getEntityName( criteria ) ) ).getIdentifierType();
}
- public TypedValue getTypedIdentifierValue(Criteria subcriteria, Object value) {
- final Loadable loadable = ( Loadable ) getPropertyMapping( getEntityName( subcriteria ) );
+ public TypedValue getTypedIdentifierValue(Criteria criteria, Object value) {
+ final Loadable loadable = ( Loadable ) getPropertyMapping( getEntityName( criteria ) );
return new TypedValue(
loadable.getIdentifierType(),
value
@@ -615,17 +615,11 @@ public class CriteriaQueryTranslator implements CriteriaQuery {
else {
throw new QueryException( "Unsupported discriminator type " + type );
}
- return new TypedValue(
- type,
- value
- );
+ return new TypedValue( type, value );
}
}
// Otherwise, this is an ordinary value.
- return new TypedValue(
- getTypeUsingProjection( subcriteria, propertyName ),
- value
- );
+ return new TypedValue( getTypeUsingProjection( subcriteria, propertyName ), value );
}
private PropertyMapping getPropertyMapping(String entityName)
diff --git a/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLCustomQuery.java b/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLCustomQuery.java
index caa353fa84..fb481168c9 100755
--- a/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLCustomQuery.java
+++ b/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLCustomQuery.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -20,9 +20,9 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
- *
*/
package org.hibernate.loader.custom.sql;
+import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
@@ -51,7 +51,7 @@ import org.hibernate.persister.entity.SQLLoadable;
* @author Max Andersen
* @author Steve Ebersole
*/
-public class SQLCustomQuery implements CustomQuery {
+public class SQLCustomQuery implements CustomQuery, Serializable {
private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, SQLCustomQuery.class.getName() );
diff --git a/hibernate-core/src/main/java/org/hibernate/loader/internal/ResultSetProcessingContextImpl.java b/hibernate-core/src/main/java/org/hibernate/loader/internal/ResultSetProcessingContextImpl.java
index 49e51a4dfd..940dab925d 100644
--- a/hibernate-core/src/main/java/org/hibernate/loader/internal/ResultSetProcessingContextImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/loader/internal/ResultSetProcessingContextImpl.java
@@ -664,7 +664,7 @@ public class ResultSetProcessingContextImpl implements ResultSetProcessingContex
}
// now finish loading the entities (2-phase load)
- performTwoPhaseLoad( preLoadEvent, postLoadEvent );
+ performTwoPhaseLoad( preLoadEvent );
// now we can finalize loading collections
finishLoadingCollections();
@@ -699,7 +699,7 @@ public class ResultSetProcessingContextImpl implements ResultSetProcessingContex
);
}
- private void performTwoPhaseLoad(PreLoadEvent preLoadEvent, PostLoadEvent postLoadEvent) {
+ private void performTwoPhaseLoad(PreLoadEvent preLoadEvent) {
final int numberOfHydratedObjects = hydratedEntityRegistrationList == null
? 0
: hydratedEntityRegistrationList.size();
@@ -710,7 +710,7 @@ public class ResultSetProcessingContextImpl implements ResultSetProcessingContex
}
for ( HydratedEntityRegistration registration : hydratedEntityRegistrationList ) {
- TwoPhaseLoad.initializeEntity( registration.instance, readOnly, session, preLoadEvent, postLoadEvent );
+ TwoPhaseLoad.initializeEntity( registration.instance, readOnly, session, preLoadEvent );
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java b/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java
index e8a299dd48..41f1bb2346 100644
--- a/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java
+++ b/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java
@@ -33,6 +33,8 @@ import java.util.StringTokenizer;
import org.hibernate.EntityMode;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.lock.OptimisticLockingStrategy;
+import org.hibernate.engine.OptimisticLockStyle;
import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.internal.FilterConfiguration;
@@ -100,9 +102,9 @@ public abstract class PersistentClass implements Serializable, Filterable, MetaA
private java.util.Map tuplizerImpls;
- protected int optimisticLockMode;
private MappedSuperclass superMappedSuperclass;
private Component declaredIdentifierMapper;
+ private OptimisticLockStyle optimisticLockStyle;
public String getClassName() {
return className;
@@ -456,10 +458,22 @@ public abstract class PersistentClass implements Serializable, Filterable, MetaA
}
}
- abstract public int getOptimisticLockMode();
+ @Deprecated
+ public int getOptimisticLockMode() {
+ return getOptimisticLockStyle().getOldCode();
+ }
+ @Deprecated
public void setOptimisticLockMode(int optimisticLockMode) {
- this.optimisticLockMode = optimisticLockMode;
+ setOptimisticLockStyle( OptimisticLockStyle.interpretOldCode( optimisticLockMode ) );
+ }
+
+ public OptimisticLockStyle getOptimisticLockStyle() {
+ return optimisticLockStyle;
+ }
+
+ public void setOptimisticLockStyle(OptimisticLockStyle optimisticLockStyle) {
+ this.optimisticLockStyle = optimisticLockStyle;
}
public void validate(Mapping mapping) throws MappingException {
diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java b/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java
index 59c5775cad..774aa95e5a 100644
--- a/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java
+++ b/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java
@@ -31,6 +31,7 @@ import java.util.Set;
import org.jboss.logging.Logger;
import org.hibernate.MappingException;
+import org.hibernate.engine.OptimisticLockStyle;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.ReflectHelper;
@@ -351,10 +352,4 @@ public class RootClass extends PersistentClass implements TableOwner {
public Object accept(PersistentClassVisitor mv) {
return mv.accept(this);
}
-
- @Override
- public int getOptimisticLockMode() {
- return optimisticLockMode;
- }
-
}
diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java b/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java
index c45d4cee16..1133d500bb 100644
--- a/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java
+++ b/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java
@@ -30,6 +30,7 @@ import java.util.Map;
import org.hibernate.AssertionFailure;
import org.hibernate.EntityMode;
+import org.hibernate.engine.OptimisticLockStyle;
import org.hibernate.internal.util.collections.JoinedIterator;
import org.hibernate.internal.util.collections.SingletonIterator;
@@ -295,9 +296,9 @@ public class Subclass extends PersistentClass {
public Component getIdentifierMapper() {
return superclass.getIdentifierMapper();
}
-
- public int getOptimisticLockMode() {
- return superclass.getOptimisticLockMode();
- }
+ @Override
+ public OptimisticLockStyle getOptimisticLockStyle() {
+ return superclass.getOptimisticLockStyle();
+ }
}
diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Table.java b/hibernate-core/src/main/java/org/hibernate/mapping/Table.java
index 95ae7644b4..39d6634bde 100644
--- a/hibernate-core/src/main/java/org/hibernate/mapping/Table.java
+++ b/hibernate-core/src/main/java/org/hibernate/mapping/Table.java
@@ -435,7 +435,7 @@ public class Table implements RelationalModel, Serializable {
StringHelper.randomFixedLengthHex("UK_"));
uk.addColumn( column );
alter.append( dialect.getUniqueDelegate()
- .applyUniqueToColumn( column ) );
+ .getColumnDefinitionUniquenessFragment( column ) );
}
if ( column.hasCheckConstraint() && dialect.supportsColumnCheck() ) {
@@ -538,7 +538,7 @@ public class Table implements RelationalModel, Serializable {
StringHelper.randomFixedLengthHex("UK_"));
uk.addColumn( col );
buf.append( dialect.getUniqueDelegate()
- .applyUniqueToColumn( col ) );
+ .getColumnDefinitionUniquenessFragment( col ) );
}
if ( col.hasCheckConstraint() && dialect.supportsColumnCheck() ) {
@@ -562,7 +562,7 @@ public class Table implements RelationalModel, Serializable {
.append( getPrimaryKey().sqlConstraintString( dialect ) );
}
- buf.append( dialect.getUniqueDelegate().applyUniquesToTable( this ) );
+ buf.append( dialect.getUniqueDelegate().getTableCreationUniqueConstraintsFragment( this ) );
if ( dialect.supportsTableCheck() ) {
Iterator chiter = checkConstraints.iterator();
diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/UniqueKey.java b/hibernate-core/src/main/java/org/hibernate/mapping/UniqueKey.java
index 5cb478bfa9..d7644a3081 100644
--- a/hibernate-core/src/main/java/org/hibernate/mapping/UniqueKey.java
+++ b/hibernate-core/src/main/java/org/hibernate/mapping/UniqueKey.java
@@ -52,15 +52,17 @@ public class UniqueKey extends Constraint {
@Override
public String sqlCreateString(Dialect dialect, Mapping p,
String defaultCatalog, String defaultSchema) {
- return dialect.getUniqueDelegate().applyUniquesOnAlter(
- this, defaultCatalog, defaultSchema );
+ return dialect.getUniqueDelegate().getAlterTableToAddUniqueKeyCommand(
+ this, defaultCatalog, defaultSchema
+ );
}
@Override
public String sqlDropString(Dialect dialect, String defaultCatalog,
String defaultSchema) {
- return dialect.getUniqueDelegate().dropUniquesOnAlter(
- this, defaultCatalog, defaultSchema );
+ return dialect.getUniqueDelegate().getAlterTableToDropUniqueKeyCommand(
+ this, defaultCatalog, defaultSchema
+ );
}
public void addColumn(Column column, String order) {
diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/spi/relational/Table.java b/hibernate-core/src/main/java/org/hibernate/metamodel/spi/relational/Table.java
index 44a3100632..fb9fb71057 100644
--- a/hibernate-core/src/main/java/org/hibernate/metamodel/spi/relational/Table.java
+++ b/hibernate-core/src/main/java/org/hibernate/metamodel/spi/relational/Table.java
@@ -283,7 +283,7 @@ public class Table extends AbstractTableSpecification implements Exportable {
alter.append( nullablePostfix );
if ( hasUniqueKey(column) ) {
- alter.append( dialect.getUniqueDelegate().applyUniqueToColumn(
+ alter.append( dialect.getUniqueDelegate().getColumnDefinitionUniquenessFragment(
column ) );
}
diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/spi/relational/UniqueKey.java b/hibernate-core/src/main/java/org/hibernate/metamodel/spi/relational/UniqueKey.java
index 7725be8ebb..141b88bd6c 100644
--- a/hibernate-core/src/main/java/org/hibernate/metamodel/spi/relational/UniqueKey.java
+++ b/hibernate-core/src/main/java/org/hibernate/metamodel/spi/relational/UniqueKey.java
@@ -51,14 +51,12 @@ public class UniqueKey extends AbstractConstraint {
@Override
public String[] sqlCreateStrings(Dialect dialect) {
- return new String[] { dialect.getUniqueDelegate().applyUniquesOnAlter(
- this ) };
+ return new String[] { dialect.getUniqueDelegate().getAlterTableToAddUniqueKeyCommand( this ) };
}
@Override
public String[] sqlDropStrings(Dialect dialect) {
- return new String[] { dialect.getUniqueDelegate().dropUniquesOnAlter(
- this ) };
+ return new String[] { dialect.getUniqueDelegate().getAlterTableToDropUniqueKeyCommand( this ) };
}
@Override
diff --git a/hibernate-core/src/main/java/org/hibernate/persister/walking/spi/MetadataDrivenModelGraphVisitor.java b/hibernate-core/src/main/java/org/hibernate/persister/walking/spi/MetadataDrivenModelGraphVisitor.java
index f22d172bec..8a9ceb77a9 100644
--- a/hibernate-core/src/main/java/org/hibernate/persister/walking/spi/MetadataDrivenModelGraphVisitor.java
+++ b/hibernate-core/src/main/java/org/hibernate/persister/walking/spi/MetadataDrivenModelGraphVisitor.java
@@ -113,7 +113,15 @@ public class MetadataDrivenModelGraphVisitor {
final PropertyPath subPath = currentPropertyPath.append( attributeDefinition.getName() );
log.debug( "Visiting attribute path : " + subPath.getFullPath() );
- final boolean continueWalk = strategy.startingAttribute( attributeDefinition );
+ final boolean continueWalk;
+ if ( attributeDefinition.getType().isAssociationType() ) {
+ continueWalk =
+ ! isDuplicateAssociation( ( (AssociationAttributeDefinition) attributeDefinition ).getAssociationKey() ) &&
+ strategy.startingAttribute( attributeDefinition );
+ }
+ else {
+ continueWalk = strategy.startingAttribute( attributeDefinition );
+ }
if ( continueWalk ) {
final PropertyPath old = currentPropertyPath;
currentPropertyPath = subPath;
@@ -135,11 +143,6 @@ public class MetadataDrivenModelGraphVisitor {
private void visitAssociation(AssociationAttributeDefinition attribute) {
// todo : do "too deep" checks; but see note about adding depth to PropertyPath
- if ( isDuplicateAssociation( attribute.getAssociationKey() ) ) {
- log.debug( "Property path deemed to be circular : " + currentPropertyPath.getFullPath() );
- return;
- }
-
if ( attribute.isCollection() ) {
visitCollectionDefinition( attribute.toCollectionDefinition() );
}
@@ -210,7 +213,14 @@ public class MetadataDrivenModelGraphVisitor {
private final Set visitedAssociationKeys = new HashSet();
protected boolean isDuplicateAssociation(AssociationKey associationKey) {
- return !visitedAssociationKeys.add( associationKey );
+ boolean isDuplicate = !visitedAssociationKeys.add( associationKey );
+ if ( isDuplicate ) {
+ log.debug( "Property path deemed to be circular : " + currentPropertyPath.getFullPath() );
+ return true;
+ }
+ else {
+ return false;
+ }
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/service/StandardServiceInitiators.java b/hibernate-core/src/main/java/org/hibernate/service/StandardServiceInitiators.java
index 03b2a2cb28..03f1b4e340 100644
--- a/hibernate-core/src/main/java/org/hibernate/service/StandardServiceInitiators.java
+++ b/hibernate-core/src/main/java/org/hibernate/service/StandardServiceInitiators.java
@@ -28,6 +28,7 @@ import java.util.Collections;
import java.util.List;
import org.hibernate.boot.registry.StandardServiceInitiator;
+import org.hibernate.cache.internal.RegionFactoryInitiator;
import org.hibernate.engine.config.internal.ConfigurationServiceInitiator;
import org.hibernate.engine.jdbc.batch.internal.BatchBuilderInitiator;
import org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator;
@@ -90,7 +91,7 @@ public class StandardServiceInitiators {
serviceInitiators.add( SessionFactoryServiceRegistryFactoryInitiator.INSTANCE );
-
+ serviceInitiators.add( RegionFactoryInitiator.INSTANCE );
return Collections.unmodifiableList( serviceInitiators );
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/service/internal/StandardSessionFactoryServiceInitiators.java b/hibernate-core/src/main/java/org/hibernate/service/internal/StandardSessionFactoryServiceInitiators.java
index eca4da5b23..700cc28856 100644
--- a/hibernate-core/src/main/java/org/hibernate/service/internal/StandardSessionFactoryServiceInitiators.java
+++ b/hibernate-core/src/main/java/org/hibernate/service/internal/StandardSessionFactoryServiceInitiators.java
@@ -48,7 +48,6 @@ public class StandardSessionFactoryServiceInitiators {
serviceInitiators.add( EventListenerServiceInitiator.INSTANCE );
serviceInitiators.add( StatisticsInitiator.INSTANCE );
serviceInitiators.add( CacheInitiator.INSTANCE );
- serviceInitiators.add( RegionFactoryInitiator.INSTANCE );
return Collections.unmodifiableList( serviceInitiators );
}
diff --git a/hibernate-core/src/main/java/org/hibernate/sql/JoinFragment.java b/hibernate-core/src/main/java/org/hibernate/sql/JoinFragment.java
index d5e1d8cd1c..83ee2327ff 100644
--- a/hibernate-core/src/main/java/org/hibernate/sql/JoinFragment.java
+++ b/hibernate-core/src/main/java/org/hibernate/sql/JoinFragment.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -20,7 +20,6 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
- *
*/
package org.hibernate.sql;
@@ -32,50 +31,128 @@ import org.hibernate.internal.util.StringHelper;
* @author Gavin King
*/
public abstract class JoinFragment {
-
- public abstract void addJoin(String tableName, String alias, String[] fkColumns, String[] pkColumns, JoinType joinType);
-
- public abstract void addJoin(String tableName, String alias, String[] fkColumns, String[] pkColumns, JoinType joinType, String on);
-
- public abstract void addCrossJoin(String tableName, String alias);
-
- public abstract void addJoins(String fromFragment, String whereFragment);
-
- public abstract String toFromFragmentString();
-
- public abstract String toWhereFragmentString();
-
- // --Commented out by Inspection (12/4/04 9:10 AM): public abstract void addCondition(String alias, String[] columns, String condition);
- public abstract void addCondition(String alias, String[] fkColumns, String[] pkColumns);
-
- public abstract boolean addCondition(String condition);
- // --Commented out by Inspection (12/4/04 9:10 AM): public abstract void addFromFragmentString(String fromFragmentString);
-
- public abstract JoinFragment copy();
-
/**
+ * Specifies an inner join.
+ *
* @deprecated use {@link JoinType#INNER_JOIN} instead.
*/
@Deprecated
- public static final int INNER_JOIN = 0;
+ public static final int INNER_JOIN = JoinType.INNER_JOIN.getJoinTypeValue();
+
/**
+ * Specifies a full join
+ *
* @deprecated use {@link JoinType#FULL_JOIN} instead.
*/
@Deprecated
- public static final int FULL_JOIN = 4;
+ @SuppressWarnings("UnusedDeclaration")
+ public static final int FULL_JOIN = JoinType.FULL_JOIN.getJoinTypeValue();
+
/**
+ * Specifies a left join.
+ *
* @deprecated use {@link JoinType#LEFT_OUTER_JOIN} instead.
*/
@Deprecated
- public static final int LEFT_OUTER_JOIN = 1;
+ public static final int LEFT_OUTER_JOIN = JoinType.LEFT_OUTER_JOIN.getJoinTypeValue();
+
/**
+ * Specifies a right join.
+ *
* @deprecated use {@link JoinType#RIGHT_OUTER_JOIN} instead.
*/
@Deprecated
- public static final int RIGHT_OUTER_JOIN = 2;
- private boolean hasFilterCondition = false;
- private boolean hasThetaJoins = false;
+ @SuppressWarnings("UnusedDeclaration")
+ public static final int RIGHT_OUTER_JOIN = JoinType.RIGHT_OUTER_JOIN.getJoinTypeValue();
+
+ private boolean hasFilterCondition;
+ private boolean hasThetaJoins;
+
+
+ /**
+ * Adds a join.
+ *
+ * @param tableName The name of the table to be joined
+ * @param alias The alias to apply to the joined table
+ * @param fkColumns The names of the columns which reference the joined table
+ * @param pkColumns The columns in the joined table being referenced
+ * @param joinType The type of join
+ */
+ public abstract void addJoin(String tableName, String alias, String[] fkColumns, String[] pkColumns, JoinType joinType);
+
+ /**
+ * Adds a join, with an additional ON clause fragment
+ *
+ * @param tableName The name of the table to be joined
+ * @param alias The alias to apply to the joined table
+ * @param fkColumns The names of the columns which reference the joined table
+ * @param pkColumns The columns in the joined table being referenced
+ * @param joinType The type of join
+ * @param on The additional ON fragment
+ */
+ public abstract void addJoin(String tableName, String alias, String[] fkColumns, String[] pkColumns, JoinType joinType, String on);
+
+ /**
+ * Adds a cross join to the specified table.
+ *
+ * @param tableName The name of the table to be joined
+ * @param alias The alias to apply to the joined table
+ */
+ public abstract void addCrossJoin(String tableName, String alias);
+
+ /**
+ * Free-form form of adding theta-style joins taking the necessary FROM and WHERE clause fragments
+ *
+ * @param fromFragment The FROM clause fragment
+ * @param whereFragment The WHERE clause fragment
+ */
+ public abstract void addJoins(String fromFragment, String whereFragment);
+
+ /**
+ * Render this fragment to its FROM clause portion
+ *
+ * @return The FROM clause portion of this fragment
+ */
+ public abstract String toFromFragmentString();
+
+ /**
+ * Render this fragment to its WHERE clause portion
+ *
+ * @return The WHERE clause portion of this fragment
+ */
+ public abstract String toWhereFragmentString();
+
+ /**
+ * Adds a condition to the join fragment.
+ *
+ * @param alias The alias of the joined table
+ * @param fkColumns The names of the columns which reference the joined table
+ * @param pkColumns The columns in the joined table being referenced
+ */
+ public abstract void addCondition(String alias, String[] fkColumns, String[] pkColumns);
+
+ /**
+ * Adds a free-form condition fragment
+ *
+ * @param condition The fragment
+ *
+ * @return {@code true} if the condition was added
+ */
+ public abstract boolean addCondition(String condition);
+
+ /**
+ * Make a copy.
+ *
+ * @return The copy.
+ */
+ public abstract JoinFragment copy();
+
+ /**
+ * Adds another join fragment to this one.
+ *
+ * @param ojf The other join fragment
+ */
public void addFragment(JoinFragment ojf) {
if ( ojf.hasThetaJoins() ) {
hasThetaJoins = true;
@@ -93,7 +170,9 @@ public abstract class JoinFragment {
*/
protected boolean addCondition(StringBuilder buffer, String on) {
if ( StringHelper.isNotEmpty( on ) ) {
- if ( !on.startsWith( " and" ) ) buffer.append( " and " );
+ if ( !on.startsWith( " and" ) ) {
+ buffer.append( " and " );
+ }
buffer.append( on );
return true;
}
@@ -115,6 +194,11 @@ public abstract class JoinFragment {
this.hasFilterCondition = b;
}
+ /**
+ * Determine if the join fragment contained any theta-joins.
+ *
+ * @return {@code true} if the fragment contained theta joins
+ */
public boolean hasThetaJoins() {
return hasThetaJoins;
}
diff --git a/hibernate-core/src/main/java/org/hibernate/sql/OracleJoinFragment.java b/hibernate-core/src/main/java/org/hibernate/sql/OracleJoinFragment.java
index b9885257bd..585d82e081 100644
--- a/hibernate-core/src/main/java/org/hibernate/sql/OracleJoinFragment.java
+++ b/hibernate-core/src/main/java/org/hibernate/sql/OracleJoinFragment.java
@@ -129,8 +129,8 @@ public class OracleJoinFragment extends JoinFragment {
StringBuilder buf = new StringBuilder( on );
for ( int i = 0; i < buf.length(); i++ ) {
char character = buf.charAt( i );
- boolean isInsertPoint = OPERATORS.contains( new Character( character ) ) ||
- ( character == ' ' && buf.length() > i + 3 && "is ".equals( buf.substring( i + 1, i + 4 ) ) );
+ final boolean isInsertPoint = OPERATORS.contains( Character.valueOf( character ) )
+ || ( character == ' ' && buf.length() > i + 3 && "is ".equals( buf.substring( i + 1, i + 4 ) ) );
if ( isInsertPoint ) {
buf.insert( i, "(+)" );
i += 3;
@@ -142,8 +142,8 @@ public class OracleJoinFragment extends JoinFragment {
private static final Set OPERATORS = new HashSet();
static {
- OPERATORS.add( new Character( '=' ) );
- OPERATORS.add( new Character( '<' ) );
- OPERATORS.add( new Character( '>' ) );
+ OPERATORS.add( Character.valueOf( '=' ) );
+ OPERATORS.add( Character.valueOf( '<' ) );
+ OPERATORS.add( Character.valueOf( '>' ) );
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/DatabaseMetadata.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/DatabaseMetadata.java
index d12b1dca03..aa1b1c2f01 100644
--- a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/DatabaseMetadata.java
+++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/DatabaseMetadata.java
@@ -49,8 +49,6 @@ import org.jboss.logging.Logger;
/**
* JDBC database metadata
* @author Christoph Sturm, Teodor Danciu
- */
-/**
* @author Brett Meyer
*/
public class DatabaseMetadata {
diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdate.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdate.java
index d5a078e2dc..ea6fe2effb 100644
--- a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdate.java
+++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdate.java
@@ -209,9 +209,9 @@ public class SchemaUpdate {
outputFileWriter = new FileWriter( outputFile );
}
- String[] sqlStrings = configuration.generateSchemaUpdateScript( dialect, meta );
- for ( String sql : sqlStrings ) {
- String formatted = formatter.format( sql );
+ List scripts = configuration.generateSchemaUpdateScriptList( dialect, meta );
+ for ( SchemaUpdateScript script : scripts ) {
+ String formatted = formatter.format( script.getScript() );
try {
if ( delimiter != null ) {
formatted += delimiter;
@@ -223,17 +223,19 @@ public class SchemaUpdate {
outputFileWriter.write( formatted + "\n" );
}
if ( target.doExport() ) {
- LOG.debug( sql );
+ LOG.debug( script.getScript() );
stmt.executeUpdate( formatted );
}
}
catch ( SQLException e ) {
- if ( haltOnError ) {
- throw new JDBCException( "Error during DDL export", e );
+ if (!script.isQuiet()) {
+ if ( haltOnError ) {
+ throw new JDBCException( "Error during DDL export", e );
+ }
+ exceptions.add( e );
+ LOG.unsuccessful(script.getScript());
+ LOG.error(e.getMessage());
}
- exceptions.add( e );
- LOG.unsuccessful(sql);
- LOG.error(e.getMessage());
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdateScript.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdateScript.java
new file mode 100644
index 0000000000..20e0d3d985
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdateScript.java
@@ -0,0 +1,66 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * JBoss, Home of Professional Open Source
+ * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors
+ * as indicated by the @authors tag. All rights reserved.
+ * See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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.
+ */
+package org.hibernate.tool.hbm2ddl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Pairs a SchemaUpdate SQL script with the boolean 'quiet'. If true, it allows
+ * the script to be run, ignoring all exceptions.
+ *
+ * @author Brett Meyer
+ */
+public class SchemaUpdateScript {
+
+ private final String script;
+
+ private final boolean quiet;
+
+ public SchemaUpdateScript(String script, boolean quiet) {
+ this.script = script;
+ this.quiet = quiet;
+ }
+
+ public String getScript() {
+ return script;
+ }
+
+ public boolean isQuiet() {
+ return quiet;
+ }
+
+ public static String[] toStringArray(List scripts) {
+ String[] scriptsArray = new String[scripts.size()];
+ for (int i = 0; i < scripts.size(); i++) {
+ scriptsArray[i] = scripts.get( i ).getScript();
+ }
+ return scriptsArray;
+ }
+
+ public static List fromStringArray(String[] scriptsArray, boolean quiet) {
+ List scripts = new ArrayList();
+ for (String script : scriptsArray) {
+ scripts.add( new SchemaUpdateScript( script, quiet ) );
+ }
+ return scripts;
+ }
+}
diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/UniqueConstraintSchemaUpdateStrategy.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/UniqueConstraintSchemaUpdateStrategy.java
new file mode 100644
index 0000000000..24b5c451a6
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/UniqueConstraintSchemaUpdateStrategy.java
@@ -0,0 +1,93 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * JBoss, Home of Professional Open Source
+ * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors
+ * as indicated by the @authors tag. All rights reserved.
+ * See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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.
+ */
+package org.hibernate.tool.hbm2ddl;
+
+import org.jboss.logging.Logger;
+
+/**
+ * Unique columns and unique keys both use unique constraints in most dialects.
+ * SchemaUpdate needs to create these constraints, but DB's
+ * support for finding existing constraints is extremely inconsistent. Further,
+ * non-explicitly-named unique constraints use randomly generated characters.
+ *
+ * Therefore, allow users to select from these strategies.
+ * {@link #RECREATE_QUIETLY} (DEFAULT): attempt to (re-)create all unique constraints,
+ * ignoring exceptions throw if the constraint already existed
+ * {@link #SKIP}: do not attempt to create unique constraints on a schema update
+ *
+ * @author Brett Meyer
+ */
+public enum UniqueConstraintSchemaUpdateStrategy {
+
+ /**
+ * Attempt to drop, then (re-)create each unique constraint.
+ * Ignore any exceptions thrown. Note
+ * that this will require unique keys/constraints to be explicitly named.
+ * If Hibernate generates the names (randomly), the drop will not work.
+ *
+ * DEFAULT
+ */
+ DROP_RECREATE_QUIETLY,
+
+ /**
+ * Attempt to (re-)create unique constraints,
+ * ignoring exceptions thrown if the constraint already existed
+ */
+ RECREATE_QUIETLY,
+
+ /**
+ * Do not attempt to create unique constraints on a schema update
+ */
+ SKIP;
+
+ private static final Logger log = Logger.getLogger( UniqueConstraintSchemaUpdateStrategy.class );
+
+ public static UniqueConstraintSchemaUpdateStrategy byName(String name) {
+ return valueOf( name.toUpperCase() );
+ }
+
+ public static UniqueConstraintSchemaUpdateStrategy interpret(Object setting) {
+ log.tracef( "Interpreting UniqueConstraintSchemaUpdateStrategy from setting : %s", setting );
+
+ if ( setting == null ) {
+ // default
+ return DROP_RECREATE_QUIETLY;
+ }
+
+ if ( UniqueConstraintSchemaUpdateStrategy.class.isInstance( setting ) ) {
+ return (UniqueConstraintSchemaUpdateStrategy) setting;
+ }
+
+ try {
+ final UniqueConstraintSchemaUpdateStrategy byName = byName( setting.toString() );
+ if ( byName != null ) {
+ return byName;
+ }
+ }
+ catch ( Exception ignore ) {
+ }
+
+ log.debugf( "Unable to interpret given setting [%s] as UniqueConstraintSchemaUpdateStrategy", setting );
+
+ // default
+ return DROP_RECREATE_QUIETLY;
+ }
+}
diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaCreatorImpl.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaCreatorImpl.java
index b47f16a704..5a3cf12dd7 100644
--- a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaCreatorImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaCreatorImpl.java
@@ -108,7 +108,7 @@ public class SchemaCreatorImpl implements SchemaCreator {
for ( UniqueKey uniqueKey : table.getUniqueKeys() ) {
checkExportIdentifier( uniqueKey, exportIdentifiers );
applySqlStrings( targets, dialect.getUniqueDelegate()
- .applyUniquesOnAlter( uniqueKey ) );
+ .getAlterTableToAddUniqueKeyCommand( uniqueKey ) );
}
}
diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaDropperImpl.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaDropperImpl.java
index 342f05ef71..068aad842c 100644
--- a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaDropperImpl.java
+++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/SchemaDropperImpl.java
@@ -108,7 +108,7 @@ public class SchemaDropperImpl implements SchemaDropper {
for ( UniqueKey uniqueKey : table.getUniqueKeys() ) {
checkExportIdentifier( uniqueKey, exportIdentifiers );
applySqlStrings( targets, dialect.getUniqueDelegate()
- .dropUniquesOnAlter( uniqueKey ) );
+ .getAlterTableToDropUniqueKeyCommand( uniqueKey ) );
}
for ( Index index : table.getIndexes() ) {
diff --git a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/StandardTableExporter.java b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/StandardTableExporter.java
index 5f356f5251..13b1f85f10 100644
--- a/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/StandardTableExporter.java
+++ b/hibernate-core/src/main/java/org/hibernate/tool/schema/internal/StandardTableExporter.java
@@ -104,8 +104,7 @@ public class StandardTableExporter implements Exporter
{
}
//only create unique constraint for non-pk column
if ( table.hasUniqueKey( col ) && !colName.equals( pkColName )) {
- buf.append( dialect.getUniqueDelegate().applyUniqueToColumn(
- col ) );
+ buf.append( dialect.getUniqueDelegate().getColumnDefinitionUniquenessFragment( col ) );
}
if ( col.getCheckCondition() != null && dialect.supportsColumnCheck() ) {
@@ -124,7 +123,7 @@ public class StandardTableExporter implements Exporter
{
.append( table.getPrimaryKey().sqlConstraintStringInCreateTable( dialect ) );
}
- buf.append( dialect.getUniqueDelegate().applyUniquesToTable( table ) );
+ buf.append( dialect.getUniqueDelegate().getTableCreationUniqueConstraintsFragment( table ) );
applyTableCheck( table, buf );
diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityBasedAssociationAttribute.java b/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityBasedAssociationAttribute.java
index f746405ff1..5e1d31ed40 100644
--- a/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityBasedAssociationAttribute.java
+++ b/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityBasedAssociationAttribute.java
@@ -93,7 +93,7 @@ public class EntityBasedAssociationAttribute
lhsColumnNames = collectionPersister.getElementColumnNames();
}
else {
- final OuterJoinLoadable entityPersister = (OuterJoinLoadable) joinable;
+ final OuterJoinLoadable entityPersister = (OuterJoinLoadable) source();
lhsTableName = getLHSTableName( type, attributeNumber(), entityPersister );
lhsColumnNames = getLHSColumnNames( type, attributeNumber(), entityPersister, sessionFactory() );
}
diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java b/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java
index a59f789b3d..0799a41de2 100644
--- a/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java
+++ b/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java
@@ -326,7 +326,7 @@ public class EntityMetamodel implements Serializable {
null;
hasSubclasses = persistentClass.hasSubclasses();
- optimisticLockStyle = interpretOptLockMode( persistentClass.getOptimisticLockMode() );
+ optimisticLockStyle = persistentClass.getOptimisticLockStyle();
final boolean isAllOrDirty =
optimisticLockStyle == OptimisticLockStyle.ALL
|| optimisticLockStyle == OptimisticLockStyle.DIRTY;
@@ -366,23 +366,6 @@ public class EntityMetamodel implements Serializable {
}
}
- private OptimisticLockStyle interpretOptLockMode(int optimisticLockMode) {
- switch ( optimisticLockMode ) {
- case Versioning.OPTIMISTIC_LOCK_NONE: {
- return OptimisticLockStyle.NONE;
- }
- case Versioning.OPTIMISTIC_LOCK_DIRTY: {
- return OptimisticLockStyle.DIRTY;
- }
- case Versioning.OPTIMISTIC_LOCK_ALL: {
- return OptimisticLockStyle.ALL;
- }
- default: {
- return OptimisticLockStyle.VERSION;
- }
- }
- }
-
public EntityMetamodel(
EntityBinding entityBinding,
AbstractEntityPersister persister,
diff --git a/hibernate-core/src/main/java/org/hibernate/type/ForeignKeyDirection.java b/hibernate-core/src/main/java/org/hibernate/type/ForeignKeyDirection.java
index 3eb8712030..c00aedd109 100644
--- a/hibernate-core/src/main/java/org/hibernate/type/ForeignKeyDirection.java
+++ b/hibernate-core/src/main/java/org/hibernate/type/ForeignKeyDirection.java
@@ -24,6 +24,7 @@
package org.hibernate.type;
import org.hibernate.engine.internal.Cascade;
+import org.hibernate.engine.internal.CascadePoint;
/**
* Represents directionality of the foreign key constraint
@@ -36,8 +37,8 @@ public enum ForeignKeyDirection {
*/
TO_PARENT {
@Override
- public boolean cascadeNow(int cascadePoint) {
- return cascadePoint != Cascade.BEFORE_INSERT_AFTER_DELETE;
+ public boolean cascadeNow(CascadePoint cascadePoint) {
+ return cascadePoint != CascadePoint.BEFORE_INSERT_AFTER_DELETE;
}
},
@@ -46,16 +47,21 @@ public enum ForeignKeyDirection {
*/
FROM_PARENT {
@Override
- public boolean cascadeNow(int cascadePoint) {
- return cascadePoint != Cascade.AFTER_INSERT_BEFORE_DELETE;
+ public boolean cascadeNow(CascadePoint cascadePoint) {
+ return cascadePoint != CascadePoint.AFTER_INSERT_BEFORE_DELETE;
}
};
/**
* Should we cascade at this cascade point?
*
+ * @param cascadePoint The point at which the cascade is being initiated.
+ *
+ * @return {@code true} if cascading should be performed now.
+ *
* @see org.hibernate.engine.internal.Cascade
*/
- public abstract boolean cascadeNow(int cascadePoint);
+ public abstract boolean cascadeNow(CascadePoint cascadePoint);
+
+}
-}
\ No newline at end of file
diff --git a/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java b/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java
index 646662ac00..72bfe2ddc7 100644
--- a/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java
+++ b/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java
@@ -59,10 +59,15 @@ public class LocaleTypeDescriptor extends AbstractTypeDescriptor {
}
public Locale fromString(String string) {
- StringTokenizer tokens = new StringTokenizer( string, "_" );
- String language = tokens.hasMoreTokens() ? tokens.nextToken() : "";
- String country = tokens.hasMoreTokens() ? tokens.nextToken() : "";
- // Need to account for allowable '_' within the variant
+ // TODO : Ultimately switch to Locale.Builder for this. However, Locale.Builder is Java 7
+
+ final StringTokenizer tokens = new StringTokenizer( string, "_" );
+ final String language = tokens.hasMoreTokens() && string.charAt(0) != '_' ? tokens.nextToken() : "";
+ final String country = tokens.hasMoreTokens() && string.charAt(string.indexOf(language) + language.length() + 1) != '_' ? tokens.nextToken() : "";
+
+ // Need to account for allowable '_' within the variant. The underscore within the variant delimits "subtags".
+ // Technically the reference spec (IETF BCP 47) also allows dash ("-") as a variant subtag delimiter.
+ // Note that this code block supports both approaches...
String variant = "";
String sep = "";
while ( tokens.hasMoreTokens() ) {
diff --git a/hibernate-core/src/test/java/org/hibernate/dialect/Mocks.java b/hibernate-core/src/test/java/org/hibernate/dialect/Mocks.java
index 4f79f00497..8f5f371af3 100644
--- a/hibernate-core/src/test/java/org/hibernate/dialect/Mocks.java
+++ b/hibernate-core/src/test/java/org/hibernate/dialect/Mocks.java
@@ -135,7 +135,7 @@ public class Mocks {
}
if ( "hashCode".equals( methodName ) ) {
- return new Integer( this.hashCode() );
+ return Integer.valueOf( this.hashCode() );
}
if ( canThrowSQLException( method ) ) {
diff --git a/hibernate-core/src/test/java/org/hibernate/event/internal/EventCacheTest.java b/hibernate-core/src/test/java/org/hibernate/event/internal/EventCacheTest.java
index ff3576e59e..e98b9b46ea 100644
--- a/hibernate-core/src/test/java/org/hibernate/event/internal/EventCacheTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/event/internal/EventCacheTest.java
@@ -127,10 +127,10 @@ public class EventCacheTest extends BaseCoreFunctionalTestCase {
Map input = new HashMap();
Object entity1 = new Simple( 1 );
//
- Object copy1 = new Integer( 2 );
+ Object copy1 = Integer.valueOf( 1 );
input.put(entity1, copy1);
Object entity2 = new Simple( 3 );
- Object copy2 = new Integer( 2 );
+ Object copy2 = Integer.valueOf( 2 );
input.put(entity2, copy2);
cache.putAll(input);
diff --git a/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorNoIncrementTest.java b/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorNoIncrementTest.java
index 155c1c04a6..9c0a457fcf 100644
--- a/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorNoIncrementTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorNoIncrementTest.java
@@ -34,7 +34,7 @@ import org.junit.Before;
import org.junit.Test;
import org.hibernate.Session;
-import org.hibernate.TestingDatabaseInfo;
+import org.hibernate.testing.env.TestingDatabaseInfo;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.NamingStrategy;
@@ -89,7 +89,7 @@ public class SequenceHiLoGeneratorNoIncrementTest extends BaseUnitTestCase {
}
);
- Dialect dialect = new H2Dialect();
+ Dialect dialect = TestingDatabaseInfo.DIALECT;
generator = new SequenceHiLoGenerator();
generator.configure( StandardBasicTypes.LONG, properties, dialect );
diff --git a/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java b/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java
index 3365474064..197ca64fb0 100644
--- a/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java
@@ -34,7 +34,7 @@ import org.junit.Before;
import org.junit.Test;
import org.hibernate.Session;
-import org.hibernate.TestingDatabaseInfo;
+import org.hibernate.testing.env.TestingDatabaseInfo;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.cfg.NamingStrategy;
@@ -85,7 +85,7 @@ public class SequenceHiLoGeneratorTest extends BaseUnitTestCase {
}
} );
- Dialect dialect = new H2Dialect();
+ Dialect dialect = TestingDatabaseInfo.DIALECT;
generator = new SequenceHiLoGenerator();
generator.configure( StandardBasicTypes.LONG, properties, dialect );
diff --git a/hibernate-core/src/test/java/org/hibernate/loader/EntityAssociationResultSetProcessorTest.java b/hibernate-core/src/test/java/org/hibernate/loader/EntityAssociationResultSetProcessorTest.java
index 24a3519853..33c32e0504 100644
--- a/hibernate-core/src/test/java/org/hibernate/loader/EntityAssociationResultSetProcessorTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/loader/EntityAssociationResultSetProcessorTest.java
@@ -55,7 +55,6 @@ import org.hibernate.loader.spi.LoadQueryAliasResolutionContext;
import org.hibernate.loader.spi.NamedParameterContext;
import org.hibernate.loader.spi.NoOpLoadPlanAdvisor;
import org.hibernate.persister.entity.EntityPersister;
-import org.hibernate.testing.FailureExpectedWithNewMetamodel;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.junit4.ExtraAssertions;
@@ -67,7 +66,6 @@ import static org.junit.Assert.assertTrue;
/**
* @author Gail Badner
*/
-@FailureExpectedWithNewMetamodel
public class EntityAssociationResultSetProcessorTest extends BaseCoreFunctionalTestCase {
@Override
diff --git a/hibernate-core/src/test/java/org/hibernate/loader/EntityWithOneToManyResultSetProcessorTest.java b/hibernate-core/src/test/java/org/hibernate/loader/EntityWithOneToManyResultSetProcessorTest.java
new file mode 100644
index 0000000000..a6351cfad0
--- /dev/null
+++ b/hibernate-core/src/test/java/org/hibernate/loader/EntityWithOneToManyResultSetProcessorTest.java
@@ -0,0 +1,236 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2013, Red Hat Inc. 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 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.loader;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.OneToMany;
+
+import org.junit.Test;
+
+import org.hibernate.Hibernate;
+import org.hibernate.Session;
+import org.hibernate.engine.spi.LoadQueryInfluencers;
+import org.hibernate.engine.spi.QueryParameters;
+import org.hibernate.engine.spi.SessionImplementor;
+import org.hibernate.jdbc.Work;
+import org.hibernate.loader.internal.EntityLoadQueryBuilderImpl;
+import org.hibernate.loader.internal.LoadQueryAliasResolutionContextImpl;
+import org.hibernate.loader.internal.ResultSetProcessorImpl;
+import org.hibernate.loader.plan.internal.SingleRootReturnLoadPlanBuilderStrategy;
+import org.hibernate.loader.plan.spi.LoadPlan;
+import org.hibernate.loader.plan.spi.build.LoadPlanBuilder;
+import org.hibernate.loader.spi.LoadQueryAliasResolutionContext;
+import org.hibernate.loader.spi.NamedParameterContext;
+import org.hibernate.loader.spi.NoOpLoadPlanAdvisor;
+import org.hibernate.persister.entity.EntityPersister;
+import org.hibernate.testing.FailureExpectedWithNewMetamodel;
+import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
+import org.hibernate.testing.junit4.ExtraAssertions;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+/**
+ * @author Gail Badner
+ */
+@FailureExpectedWithNewMetamodel
+public class EntityWithOneToManyResultSetProcessorTest extends BaseCoreFunctionalTestCase {
+
+ @Override
+ protected Class>[] getAnnotatedClasses() {
+ return new Class[] { Poster.class, Message.class };
+ }
+
+ @Test
+ public void testEntityWithSet() throws Exception {
+ final EntityPersister entityPersister = sessionFactory().getEntityPersister( Poster.class.getName() );
+
+ // create some test data
+ Session session = openSession();
+ session.beginTransaction();
+ Poster poster = new Poster();
+ poster.pid = 0;
+ poster.name = "John Doe";
+ Message message1 = new Message();
+ message1.mid = 1;
+ message1.msgTxt = "Howdy!";
+ message1.poster = poster;
+ poster.messages.add( message1 );
+ Message message2 = new Message();
+ message2.mid = 2;
+ message2.msgTxt = "Bye!";
+ message2.poster = poster;
+ poster.messages.add( message2 );
+ session.save( poster );
+ session.getTransaction().commit();
+ session.close();
+
+ session = openSession();
+ session.beginTransaction();
+ Poster posterGotten = (Poster) session.get( Poster.class, poster.pid );
+ assertEquals( 0, posterGotten.pid.intValue() );
+ assertEquals( poster.name, posterGotten.name );
+ assertTrue( Hibernate.isInitialized( posterGotten.messages ) );
+ assertEquals( 2, posterGotten.messages.size() );
+ for ( Message message : posterGotten.messages ) {
+ if ( message.mid == 1 ) {
+ assertEquals( message1.msgTxt, message.msgTxt );
+ }
+ else if ( message.mid == 2 ) {
+ assertEquals( message2.msgTxt, message.msgTxt );
+ }
+ else {
+ fail( "unexpected message id." );
+ }
+ assertSame( posterGotten, message.poster );
+ }
+ session.getTransaction().commit();
+ session.close();
+
+ {
+ final SingleRootReturnLoadPlanBuilderStrategy strategy = new SingleRootReturnLoadPlanBuilderStrategy(
+ sessionFactory(),
+ LoadQueryInfluencers.NONE
+ );
+ final LoadPlan plan = LoadPlanBuilder.buildRootEntityLoadPlan( strategy, entityPersister );
+ final LoadQueryAliasResolutionContext aliasResolutionContext =
+ new LoadQueryAliasResolutionContextImpl(
+ sessionFactory(),
+ 0,
+ Collections.singletonMap( plan.getReturns().get( 0 ), new String[] { "abc" } )
+ );
+ final EntityLoadQueryBuilderImpl queryBuilder = new EntityLoadQueryBuilderImpl(
+ LoadQueryInfluencers.NONE,
+ plan
+ );
+ final String sql = queryBuilder.generateSql( 1, sessionFactory(), aliasResolutionContext );
+
+ final ResultSetProcessorImpl resultSetProcessor = new ResultSetProcessorImpl( plan );
+ final List results = new ArrayList();
+
+ final Session workSession = openSession();
+ workSession.beginTransaction();
+ workSession.doWork(
+ new Work() {
+ @Override
+ public void execute(Connection connection) throws SQLException {
+ PreparedStatement ps = connection.prepareStatement( sql );
+ ps.setInt( 1, 0 );
+ ResultSet resultSet = ps.executeQuery();
+ results.addAll(
+ resultSetProcessor.extractResults(
+ NoOpLoadPlanAdvisor.INSTANCE,
+ resultSet,
+ (SessionImplementor) workSession,
+ new QueryParameters(),
+ new NamedParameterContext() {
+ @Override
+ public int[] getNamedParameterLocations(String name) {
+ return new int[0];
+ }
+ },
+ aliasResolutionContext,
+ true,
+ false,
+ null,
+ null
+ )
+ );
+ resultSet.close();
+ ps.close();
+ }
+ }
+ );
+ assertEquals( 2, results.size() );
+ Object result1 = results.get( 0 );
+ assertNotNull( result1 );
+ assertSame( result1, results.get( 1 ) );
+
+ Poster workPoster = ExtraAssertions.assertTyping( Poster.class, result1 );
+ assertEquals( 0, workPoster.pid.intValue() );
+ assertEquals( poster.name, workPoster.name );
+ assertTrue( Hibernate.isInitialized( workPoster.messages ) );
+ assertEquals( 2, workPoster.messages.size() );
+ assertTrue( Hibernate.isInitialized( posterGotten.messages ) );
+ assertEquals( 2, workPoster.messages.size() );
+ for ( Message message : workPoster.messages ) {
+ if ( message.mid == 1 ) {
+ assertEquals( message1.msgTxt, message.msgTxt );
+ }
+ else if ( message.mid == 2 ) {
+ assertEquals( message2.msgTxt, message.msgTxt );
+ }
+ else {
+ fail( "unexpected message id." );
+ }
+ assertSame( workPoster, message.poster );
+ }
+ workSession.getTransaction().commit();
+ workSession.close();
+ }
+
+ // clean up test data
+ session = openSession();
+ session.beginTransaction();
+ session.delete( poster );
+ session.getTransaction().commit();
+ session.close();
+ }
+
+ @Entity( name = "Message" )
+ public static class Message {
+ @Id
+ private Integer mid;
+ private String msgTxt;
+ @ManyToOne
+ @JoinColumn
+ private Poster poster;
+ }
+
+ @Entity( name = "Poster" )
+ public static class Poster {
+ @Id
+ private Integer pid;
+ private String name;
+ @OneToMany(mappedBy = "poster", fetch = FetchType.EAGER, cascade = CascadeType.ALL )
+ private Set messages = new HashSet();
+ }
+}
diff --git a/hibernate-core/src/test/java/org/hibernate/loader/plan/spi/LoadPlanBuilderTest.java b/hibernate-core/src/test/java/org/hibernate/loader/plan/spi/LoadPlanBuilderTest.java
index 7e926ff368..a5f6f84b2e 100644
--- a/hibernate-core/src/test/java/org/hibernate/loader/plan/spi/LoadPlanBuilderTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/loader/plan/spi/LoadPlanBuilderTest.java
@@ -41,7 +41,6 @@ import org.hibernate.persister.entity.EntityPersister;
import org.junit.Test;
-import org.hibernate.testing.FailureExpectedWithNewMetamodel;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.hibernate.testing.junit4.ExtraAssertions;
@@ -52,7 +51,6 @@ import static org.junit.Assert.assertNotNull;
/**
* @author Steve Ebersole
*/
-@FailureExpectedWithNewMetamodel
public class LoadPlanBuilderTest extends BaseCoreFunctionalTestCase {
@Override
protected Class>[] getAnnotatedClasses() {
diff --git a/hibernate-core/src/test/java/org/hibernate/persister/walking/BasicWalkingTest.java b/hibernate-core/src/test/java/org/hibernate/persister/walking/BasicWalkingTest.java
index 84fbf12140..da8bc7f961 100644
--- a/hibernate-core/src/test/java/org/hibernate/persister/walking/BasicWalkingTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/persister/walking/BasicWalkingTest.java
@@ -44,13 +44,11 @@ import org.hibernate.persister.walking.spi.MetadataDrivenModelGraphVisitor;
import org.junit.Test;
-import org.hibernate.testing.FailureExpectedWithNewMetamodel;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
/**
* @author Steve Ebersole
*/
-@FailureExpectedWithNewMetamodel
public class BasicWalkingTest extends BaseCoreFunctionalTestCase {
@Override
protected Class>[] getAnnotatedClasses() {
diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/EntityTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/EntityTest.java
index 32d7c6d06d..3cc641b10d 100644
--- a/hibernate-core/src/test/java/org/hibernate/test/annotations/EntityTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/EntityTest.java
@@ -63,7 +63,7 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
Session s = openSession();
Transaction tx = s.beginTransaction();
Flight firstOne = new Flight();
- firstOne.setId( new Long( 1 ) );
+ firstOne.setId( Long.valueOf( 1 ) );
firstOne.setName( "AF3202" );
firstOne.setDuration( new Long( 1000000 ) );
firstOne.setDurationInSec( 2000 );
@@ -75,11 +75,11 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
//read it
s = openSession();
tx = s.beginTransaction();
- firstOne = (Flight) s.get( Flight.class, new Long( 1 ) );
+ firstOne = (Flight) s.get( Flight.class, Long.valueOf( 1 ) );
assertNotNull( firstOne );
- assertEquals( new Long( 1 ), firstOne.getId() );
+ assertEquals( Long.valueOf( 1 ), firstOne.getId() );
assertEquals( "AF3202", firstOne.getName() );
- assertEquals( new Long( 1000000 ), firstOne.getDuration() );
+ assertEquals( Long.valueOf( 1000000 ), firstOne.getDuration() );
assertFalse( "Transient is not working", 2000l == firstOne.getDurationInSec() );
tx.commit();
s.close();
@@ -91,9 +91,9 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
Session s = openSession();
Transaction tx = s.beginTransaction();
Flight firstOne = new Flight();
- firstOne.setId( new Long( 1 ) );
+ firstOne.setId( Long.valueOf( 1 ) );
firstOne.setName( "AF3202" );
- firstOne.setDuration( new Long( 1000000 ) );
+ firstOne.setDuration( Long.valueOf( 1000000 ) );
firstOne.setDurationInSec( 2000 );
s.save( firstOne );
s.flush();
@@ -104,7 +104,7 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
s = openSession();
tx = s.beginTransaction();
firstOne = new Flight();
- firstOne.setId( new Long( 1 ) );
+ firstOne.setId( Long.valueOf( 1 ) );
firstOne.setName( null );
try {
@@ -123,7 +123,7 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
s = openSession();
tx = s.beginTransaction();
firstOne = new Flight();
- firstOne.setId( new Long( 1 ) );
+ firstOne.setId( Long.valueOf( 1 ) );
firstOne.setName( "AF3202" );
firstOne.setTriggeredData( "should not be insertable" );
tx.commit();
@@ -131,9 +131,9 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
s = openSession();
tx = s.beginTransaction();
- firstOne = (Flight) s.get( Flight.class, new Long( 1 ) );
+ firstOne = (Flight) s.get( Flight.class, Long.valueOf( 1 ) );
assertNotNull( firstOne );
- assertEquals( new Long( 1 ), firstOne.getId() );
+ assertEquals( Long.valueOf( 1 ), firstOne.getId() );
assertEquals( "AF3202", firstOne.getName() );
assertFalse( "should not be insertable".equals( firstOne.getTriggeredData() ) );
firstOne.setName( "BA1234" );
@@ -143,9 +143,9 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
s = openSession();
tx = s.beginTransaction();
- firstOne = (Flight) s.get( Flight.class, new Long( 1 ) );
+ firstOne = (Flight) s.get( Flight.class, Long.valueOf( 1 ) );
assertNotNull( firstOne );
- assertEquals( new Long( 1 ), firstOne.getId() );
+ assertEquals( Long.valueOf( 1 ), firstOne.getId() );
assertEquals( "AF3202", firstOne.getName() );
assertFalse( "should not be updatable".equals( firstOne.getTriggeredData() ) );
tx.commit();
@@ -159,13 +159,13 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
s = openSession();
tx = s.beginTransaction();
Sky sky = new Sky();
- sky.id = new Long( 2 );
+ sky.id = Long.valueOf( 2 );
sky.color = "blue";
sky.day = "monday";
sky.month = "January";
Sky sameSky = new Sky();
- sameSky.id = new Long( 3 );
+ sameSky.id = Long.valueOf( 3 );
sameSky.color = "blue";
sky.day = "tuesday";
sky.month = "January";
@@ -194,19 +194,19 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
s = openSession();
tx = s.beginTransaction();
Sky sky = new Sky();
- sky.id = new Long( id++ );
+ sky.id = Long.valueOf( id++ );
sky.color = "green";
sky.day = "monday";
sky.month = "March";
Sky otherSky = new Sky();
- otherSky.id = new Long( id++ );
+ otherSky.id = Long.valueOf( id++ );
otherSky.color = "red";
otherSky.day = "friday";
otherSky.month = "March";
Sky sameSky = new Sky();
- sameSky.id = new Long( id++ );
+ sameSky.id = Long.valueOf( id++ );
sameSky.color = "green";
sameSky.day = "monday";
sameSky.month = "March";
@@ -240,9 +240,9 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
Session s = openSession();
Transaction tx = s.beginTransaction();
Flight firstOne = new Flight();
- firstOne.setId( new Long( 2 ) );
+ firstOne.setId( Long.valueOf( 2 ) );
firstOne.setName( "AF3202" );
- firstOne.setDuration( new Long( 500 ) );
+ firstOne.setDuration( Long.valueOf( 500 ) );
s.save( firstOne );
s.flush();
tx.commit();
@@ -251,15 +251,15 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
//read it
s = openSession();
tx = s.beginTransaction();
- firstOne = (Flight) s.get( Flight.class, new Long( 2 ) );
+ firstOne = (Flight) s.get( Flight.class, Long.valueOf( 2 ) );
tx.commit();
s.close();
//read it again
s = openSession();
tx = s.beginTransaction();
- Flight concurrentOne = (Flight) s.get( Flight.class, new Long( 2 ) );
- concurrentOne.setDuration( new Long( 1000 ) );
+ Flight concurrentOne = (Flight) s.get( Flight.class, Long.valueOf( 2 ) );
+ concurrentOne.setDuration( Long.valueOf( 1000 ) );
s.update( concurrentOne );
tx.commit();
s.close();
@@ -291,22 +291,22 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
s = openSession();
tx = s.beginTransaction();
Sky sky = new Sky();
- sky.id = new Long( 1 );
+ sky.id = Long.valueOf( 1 );
sky.color = "black";
- Sky.area = "Paris";
+ sky.area = "Paris";
sky.day = "23";
sky.month = "1";
s.save( sky );
tx.commit();
s.close();
- Sky.area = "London";
+ sky.area = "London";
s = openSession();
tx = s.beginTransaction();
sky = (Sky) s.get( Sky.class, sky.id );
assertNotNull( sky );
assertEquals( "black", sky.color );
- assertFalse( "Paris".equals( Sky.area ) );
+ assertFalse( "Paris".equals( sky.area ) );
tx.commit();
s.close();
}
@@ -339,9 +339,9 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
Session s = openSession();
Transaction tx = s.beginTransaction();
Flight airFrance = new Flight();
- airFrance.setId( new Long( 747 ) );
+ airFrance.setId( Long.valueOf( 747 ) );
airFrance.setName( "Paris-Amsterdam" );
- airFrance.setDuration( new Long( 10 ) );
+ airFrance.setDuration( Long.valueOf( 10 ) );
airFrance.setFactor( 25 );
s.persist( airFrance );
tx.commit();
@@ -351,7 +351,7 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
tx = s.beginTransaction();
airFrance = (Flight) s.get( Flight.class, airFrance.getId() );
assertNotNull( airFrance );
- assertEquals( new Long( 10 ), airFrance.getDuration() );
+ assertEquals( Long.valueOf( 10 ), airFrance.getDuration() );
assertFalse( 25 == airFrance.getFactor( false ) );
s.delete( airFrance );
tx.commit();
@@ -363,9 +363,9 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
Session s = openSession();
Transaction tx = s.beginTransaction();
Flight airFrance = new Flight();
- airFrance.setId( new Long( 747 ) );
+ airFrance.setId( Long.valueOf( 747 ) );
airFrance.setName( "Paris-Amsterdam" );
- airFrance.setDuration( new Long( 10 ) );
+ airFrance.setDuration( Long.valueOf( 10 ) );
airFrance.setDepartureDate( new Date( 05, 06, 21, 10, 0, 0 ) );
airFrance.setAlternativeDepartureDate( new GregorianCalendar( 2006, 02, 03, 10, 00 ) );
airFrance.getAlternativeDepartureDate().setTimeZone( TimeZone.getTimeZone( "GMT" ) );
@@ -397,7 +397,7 @@ public class EntityTest extends BaseCoreFunctionalTestCase {
Session s = openSession();
Transaction tx = s.beginTransaction();
Flight airFrance = new Flight();
- airFrance.setId( new Long( 747 ) );
+ airFrance.setId( Long.valueOf( 747 ) );
airFrance.setName( "Paris-Amsterdam" );
airFrance.setDuration( null );
try {
diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/Sky.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/Sky.java
index 86edc4e2ba..4bb6175598 100644
--- a/hibernate-core/src/test/java/org/hibernate/test/annotations/Sky.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/Sky.java
@@ -5,6 +5,7 @@ import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
+import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
/**
@@ -23,5 +24,6 @@ public class Sky implements Serializable {
protected String day;
@Column(name = "MONTH", nullable = false)
protected String month;
- static protected String area;
+ @Transient
+ protected String area;
}
diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java
index a3eb378aee..d048ea4591 100644
--- a/hibernate-core/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java
@@ -59,6 +59,12 @@ public class BackquoteTest extends BaseUnitTestCase {
log.debug(writer.toString());
fail(e.getMessage());
}
+ finally {
+ if ( sessionFactory != null ) {
+ sessionFactory.close();
+ sessionFactory = null;
+ }
+ }
}
/**
@@ -87,6 +93,11 @@ public class BackquoteTest extends BaseUnitTestCase {
e.printStackTrace(new PrintWriter(writer));
log.debug(writer.toString());
fail(e.getMessage());
- }
+ } finally {
+ if(sessionFactory!=null){
+ sessionFactory.close();
+ sessionFactory = null;
+ }
+ }
}
}
diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/CollectionElementTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/CollectionElementTest.java
index 1f931af8c6..d9a87fff00 100644
--- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/CollectionElementTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/CollectionElementTest.java
@@ -64,8 +64,8 @@ public class CollectionElementTest extends BaseCoreFunctionalTestCase {
boy.setLastName( "Doe" );
boy.getNickNames().add( "Johnny" );
boy.getNickNames().add( "Thing" );
- boy.getScorePerNickName().put( "Johnny", new Integer( 3 ) );
- boy.getScorePerNickName().put( "Thing", new Integer( 5 ) );
+ boy.getScorePerNickName().put( "Johnny", Integer.valueOf( 3 ) );
+ boy.getScorePerNickName().put( "Thing", Integer.valueOf( 5 ) );
int[] favNbrs = new int[4];
for (int index = 0; index < favNbrs.length - 1; index++) {
favNbrs[index] = index * 3;
@@ -88,7 +88,7 @@ public class CollectionElementTest extends BaseCoreFunctionalTestCase {
assertTrue( boy.getNickNames().contains( "Thing" ) );
assertNotNull( boy.getScorePerNickName() );
assertTrue( boy.getScorePerNickName().containsKey( "Thing" ) );
- assertEquals( new Integer( 5 ), boy.getScorePerNickName().get( "Thing" ) );
+ assertEquals( Integer.valueOf( 5 ), boy.getScorePerNickName().get( "Thing" ) );
assertNotNull( boy.getFavoriteNumbers() );
assertEquals( 3, boy.getFavoriteNumbers()[1] );
assertTrue( boy.getCharacters().contains( Character.CRAFTY ) );
diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/join/JoinOrderingTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/JoinOrderingTest.java
new file mode 100644
index 0000000000..548bcb9eb7
--- /dev/null
+++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/JoinOrderingTest.java
@@ -0,0 +1,47 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * JBoss, Home of Professional Open Source
+ * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors
+ * as indicated by the @authors tag. All rights reserved.
+ * See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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.
+ */
+package org.hibernate.test.annotations.join;
+
+import org.hibernate.testing.TestForIssue;
+import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
+import org.junit.Test;
+
+/**
+ * @author Brett Meyer
+ */
+@TestForIssue( jiraKey = "HHH-2872" )
+public class JoinOrderingTest extends BaseCoreFunctionalTestCase {
+
+ @Override
+ protected Class>[] getAnnotatedClasses() {
+ // This is the important piece. ProductDetails must be first to
+ // reproduce the issue.
+// return new Class>[] { ProductDetails.class, Product.class, ProductVersion.class };
+ // TODO: commented out -- @FailureExpected wasn't working on builds
+ // if it's a MappingException.
+ return new Class>[] { };
+ }
+
+ @Test
+ public void testEntityOrderingWithJoins() {
+ // nothing to do
+ }
+}
diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/join/Product.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/Product.java
new file mode 100644
index 0000000000..0b01963dc1
--- /dev/null
+++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/Product.java
@@ -0,0 +1,53 @@
+package org.hibernate.test.annotations.join;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+import javax.persistence.UniqueConstraint;
+
+@Entity
+@Table(name = "product", uniqueConstraints = @UniqueConstraint(columnNames = "code"))
+public class Product {
+
+ @Id
+ @GeneratedValue
+ @Column(name = "id_product")
+ private Integer id;
+
+ @ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.ALL})
+ @JoinColumn(name = "id_product_version", nullable = false)
+ private ProductVersion productVersion;
+
+ @Column(name = "code", unique = true, nullable = false, precision = 4, scale = 0)
+ private Long code;
+
+ public Integer getId() {
+ return this.id;
+ }
+
+ public void setId(final Integer id) {
+ this.id = id;
+ }
+
+ public ProductVersion getProductVersion() {
+ return this.productVersion;
+ }
+
+ public void setProductVersion(final ProductVersion productVersion) {
+ this.productVersion = productVersion;
+ }
+
+ public Long getCode() {
+ return this.code;
+ }
+
+ public void setCode(final Long code) {
+ this.code = code;
+ }
+}
diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/join/ProductDetails.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/ProductDetails.java
new file mode 100644
index 0000000000..acb7e73228
--- /dev/null
+++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/ProductDetails.java
@@ -0,0 +1,43 @@
+package org.hibernate.test.annotations.join;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "product_details")
+public class ProductDetails {
+ @Id
+ @GeneratedValue
+ @Column(name = "id_product_details")
+ private Integer id;
+
+ @ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.ALL})
+ @JoinColumns({ @JoinColumn(name = "id_product", referencedColumnName = "id_product", nullable = false),
+ @JoinColumn(name = "id_product_version", referencedColumnName = "id_product_version", nullable = false) })
+ private Product product;
+
+ public Integer getId() {
+ return this.id;
+ }
+
+ public void setId(final Integer id) {
+ this.id = id;
+ }
+
+ public Product getProduct() {
+ return this.product;
+ }
+
+ public void setProduct(final Product product) {
+ this.product = product;
+ }
+
+}
diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/join/ProductVersion.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/ProductVersion.java
new file mode 100644
index 0000000000..01b5b4d7dd
--- /dev/null
+++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/ProductVersion.java
@@ -0,0 +1,45 @@
+package org.hibernate.test.annotations.join;
+
+import static javax.persistence.GenerationType.IDENTITY;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "product_version")
+public class ProductVersion {
+
+ @Id
+ @GeneratedValue(strategy = IDENTITY)
+ @Column(name = "id_product_version", unique = true, nullable = false)
+ private Integer id;
+
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "productVersion", cascade = {CascadeType.ALL})
+ private List products = new ArrayList(0);
+
+ public Integer getId() {
+ return this.id;
+ }
+
+ public void setId(final Integer id) {
+ this.id = id;
+ }
+
+ public List getProducts() {
+ return this.products;
+ }
+
+ public void setProducts(final ArrayList products) {
+ this.products = products;
+ }
+
+}
diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java
index e647ec1948..3e66f47016 100644
--- a/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java
@@ -81,6 +81,7 @@ public class NullablePrimaryKeyTest extends BaseUnitTestCase {
if ( serviceRegistry != null ) {
ServiceRegistryBuilder.destroy( serviceRegistry );
}
+
}
}
}
diff --git a/hibernate-core/src/test/java/org/hibernate/test/instrument/cases/AbstractExecutable.java b/hibernate-core/src/test/java/org/hibernate/test/instrument/cases/AbstractExecutable.java
index 0c3d0f7e35..4bb9df9a91 100644
--- a/hibernate-core/src/test/java/org/hibernate/test/instrument/cases/AbstractExecutable.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/instrument/cases/AbstractExecutable.java
@@ -30,8 +30,10 @@ public abstract class AbstractExecutable implements Executable {
}
finally {
factory.close();
+ factory = null;
if ( serviceRegistry != null ) {
ServiceRegistryBuilder.destroy( serviceRegistry );
+ serviceRegistry = null;
}
}
}
diff --git a/hibernate-core/src/test/java/org/hibernate/test/legacy/CustomPersister.java b/hibernate-core/src/test/java/org/hibernate/test/legacy/CustomPersister.java
index c7c1732c23..c17b42a7d8 100644
--- a/hibernate-core/src/test/java/org/hibernate/test/legacy/CustomPersister.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/legacy/CustomPersister.java
@@ -321,7 +321,7 @@ public class CustomPersister implements EntityPersister {
LockMode.NONE,
false,
session
- );
+ );
TwoPhaseLoad.postHydrate(
this, id,
new String[] { obj.getName() },
@@ -330,14 +330,14 @@ public class CustomPersister implements EntityPersister {
LockMode.NONE,
false,
session
- );
+ );
TwoPhaseLoad.initializeEntity(
clone,
false,
session,
- new PreLoadEvent( (EventSource) session ),
- new PostLoadEvent( (EventSource) session )
- );
+ new PreLoadEvent( (EventSource) session )
+ );
+ TwoPhaseLoad.postLoad( clone, session, new PostLoadEvent( (EventSource) session ) );
}
return clone;
}
diff --git a/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/3_Version.hbm.xml b/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/3_Version.hbm.xml
new file mode 100644
index 0000000000..1fdcd9afa1
--- /dev/null
+++ b/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/3_Version.hbm.xml
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
+
+ uid_table
+ next_hi_value_column
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/MigrationTest.java b/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/MigrationTest.java
index 204c74d1e7..e7be208575 100644
--- a/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/MigrationTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/MigrationTest.java
@@ -23,23 +23,26 @@
*/
package org.hibernate.test.schemaupdate;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.testing.ServiceRegistryBuilder;
+import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
+import org.hibernate.tool.hbm2ddl.UniqueConstraintSchemaUpdateStrategy;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
-
-import static org.junit.Assert.assertEquals;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
/**
* @author Max Rydahl Andersen
+ * @author Brett Meyer
*/
public class MigrationTest extends BaseUnitTestCase {
private ServiceRegistry serviceRegistry;
@@ -83,6 +86,49 @@ public class MigrationTest extends BaseUnitTestCase {
new SchemaExport( serviceRegistry, v2cfg ).drop( false, true );
}
+
+ /**
+ * 3_Version.hbm.xml contains a named unique constraint and an un-named
+ * unique constraint (will receive a randomly-generated name). Create
+ * the original schema with 2_Version.hbm.xml. Then, run SchemaUpdate
+ * TWICE using 3_Version.hbm.xml. Neither RECREATE_QUIETLY nor SKIP should
+ * generate any exceptions.
+ */
+ @Test
+ @TestForIssue( jiraKey = "HHH-8162" )
+ public void testConstraintUpdate() {
+ doConstraintUpdate(UniqueConstraintSchemaUpdateStrategy.DROP_RECREATE_QUIETLY);
+ doConstraintUpdate(UniqueConstraintSchemaUpdateStrategy.RECREATE_QUIETLY);
+ doConstraintUpdate(UniqueConstraintSchemaUpdateStrategy.SKIP);
+ }
+
+ private void doConstraintUpdate(UniqueConstraintSchemaUpdateStrategy strategy) {
+ // original
+ String resource1 = "org/hibernate/test/schemaupdate/2_Version.hbm.xml";
+ // adds unique constraint
+ String resource2 = "org/hibernate/test/schemaupdate/3_Version.hbm.xml";
+
+ Configuration v1cfg = new Configuration();
+ v1cfg.addResource( resource1 );
+ new SchemaExport( v1cfg ).execute( false, true, true, false );
+
+ // adds unique constraint
+ Configuration v2cfg = new Configuration();
+ v2cfg.getProperties().put( AvailableSettings.UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY, strategy );
+ v2cfg.addResource( resource2 );
+ SchemaUpdate v2schemaUpdate = new SchemaUpdate( serviceRegistry, v2cfg );
+ v2schemaUpdate.execute( true, true );
+ assertEquals( 0, v2schemaUpdate.getExceptions().size() );
+
+ Configuration v3cfg = new Configuration();
+ v3cfg.getProperties().put( AvailableSettings.UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY, strategy );
+ v3cfg.addResource( resource2 );
+ SchemaUpdate v3schemaUpdate = new SchemaUpdate( serviceRegistry, v3cfg );
+ v3schemaUpdate.execute( true, true );
+ assertEquals( 0, v3schemaUpdate.getExceptions().size() );
+
+ new SchemaExport( serviceRegistry, v3cfg ).drop( false, true );
+ }
}
diff --git a/hibernate-core/src/test/java/org/hibernate/type/AttributeConverterTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/AttributeConverterTest.java
similarity index 95%
rename from hibernate-core/src/test/java/org/hibernate/type/AttributeConverterTest.java
rename to hibernate-core/src/test/java/org/hibernate/test/type/AttributeConverterTest.java
index 568ab94856..6316fccebe 100644
--- a/hibernate-core/src/test/java/org/hibernate/type/AttributeConverterTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/type/AttributeConverterTest.java
@@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.type;
+package org.hibernate.test.type;
import java.sql.Clob;
import java.sql.Types;
@@ -39,16 +39,18 @@ import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.SimpleValue;
-import org.hibernate.testing.junit4.BaseUnitTestCase;
+import org.hibernate.type.AbstractStandardBasicType;
+import org.hibernate.type.BasicType;
+import org.hibernate.type.Type;
import org.hibernate.type.descriptor.java.StringTypeDescriptor;
-
+import org.hibernate.testing.junit4.BaseUnitTestCase;
import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
/**
- * Tests the principle of adding "AttributeConverter" to the mix of {@link Type} resolution
+ * Tests the principle of adding "AttributeConverter" to the mix of {@link org.hibernate.type.Type} resolution
*
* @author Steve Ebersole
*/
diff --git a/hibernate-core/src/test/java/org/hibernate/type/BasicTypeRegistryTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/BasicTypeRegistryTest.java
similarity index 94%
rename from hibernate-core/src/test/java/org/hibernate/type/BasicTypeRegistryTest.java
rename to hibernate-core/src/test/java/org/hibernate/test/type/BasicTypeRegistryTest.java
index a898e7a17d..ed9b7cc6b3 100644
--- a/hibernate-core/src/test/java/org/hibernate/type/BasicTypeRegistryTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/type/BasicTypeRegistryTest.java
@@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.type;
+package org.hibernate.test.type;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@@ -33,6 +33,15 @@ import org.junit.Test;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.testing.junit4.BaseUnitTestCase;
+
+import org.hibernate.type.AbstractSingleColumnStandardBasicType;
+import org.hibernate.type.BasicType;
+import org.hibernate.type.BasicTypeRegistry;
+import org.hibernate.type.CompositeCustomType;
+import org.hibernate.type.CustomType;
+import org.hibernate.type.Type;
+import org.hibernate.type.UUIDBinaryType;
+import org.hibernate.type.UUIDCharType;
import org.hibernate.type.descriptor.java.StringTypeDescriptor;
import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor;
import org.hibernate.usertype.CompositeUserType;
diff --git a/hibernate-core/src/test/java/org/hibernate/type/TypeTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/TypeTest.java
similarity index 90%
rename from hibernate-core/src/test/java/org/hibernate/type/TypeTest.java
rename to hibernate-core/src/test/java/org/hibernate/test/type/TypeTest.java
index 541725b034..3f6a6de910 100644
--- a/hibernate-core/src/test/java/org/hibernate/type/TypeTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/type/TypeTest.java
@@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.type;
+package org.hibernate.test.type;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
@@ -45,6 +45,39 @@ import org.hibernate.Session;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.internal.util.SerializationHelper;
import org.hibernate.internal.util.collections.ArrayHelper;
+import org.hibernate.type.AbstractSingleColumnStandardBasicType;
+import org.hibernate.type.BigDecimalType;
+import org.hibernate.type.BigIntegerType;
+import org.hibernate.type.BinaryType;
+import org.hibernate.type.BooleanType;
+import org.hibernate.type.ByteType;
+import org.hibernate.type.CalendarDateType;
+import org.hibernate.type.CalendarType;
+import org.hibernate.type.CharArrayType;
+import org.hibernate.type.CharacterArrayType;
+import org.hibernate.type.CharacterType;
+import org.hibernate.type.ClassType;
+import org.hibernate.type.CurrencyType;
+import org.hibernate.type.DateType;
+import org.hibernate.type.DoubleType;
+import org.hibernate.type.FloatType;
+import org.hibernate.type.ImageType;
+import org.hibernate.type.IntegerType;
+import org.hibernate.type.LocaleType;
+import org.hibernate.type.LongType;
+import org.hibernate.type.MaterializedBlobType;
+import org.hibernate.type.MaterializedClobType;
+import org.hibernate.type.NumericBooleanType;
+import org.hibernate.type.SerializableType;
+import org.hibernate.type.ShortType;
+import org.hibernate.type.StringType;
+import org.hibernate.type.TextType;
+import org.hibernate.type.TimeType;
+import org.hibernate.type.TimeZoneType;
+import org.hibernate.type.TimestampType;
+import org.hibernate.type.TrueFalseType;
+import org.hibernate.type.YesNoType;
+
import org.hibernate.testing.junit4.BaseUnitTestCase;
import static org.junit.Assert.assertFalse;
diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/AbstractDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/AbstractDescriptorTest.java
similarity index 97%
rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/java/AbstractDescriptorTest.java
rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/AbstractDescriptorTest.java
index 312aeaaa14..ba8a2a1c40 100644
--- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/AbstractDescriptorTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/AbstractDescriptorTest.java
@@ -21,11 +21,13 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.type.descriptor.java;
+package org.hibernate.test.type.descriptor.java;
import java.io.Serializable;
import java.sql.Blob;
import java.sql.Clob;
+import org.hibernate.type.descriptor.java.JavaTypeDescriptor;
+
import org.junit.Before;
import org.junit.Test;
diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BigDecimalDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BigDecimalDescriptorTest.java
similarity index 93%
rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BigDecimalDescriptorTest.java
rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BigDecimalDescriptorTest.java
index c3924ffadd..0643102cdc 100644
--- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BigDecimalDescriptorTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BigDecimalDescriptorTest.java
@@ -21,9 +21,11 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.type.descriptor.java;
+package org.hibernate.test.type.descriptor.java;
import java.math.BigDecimal;
+import org.hibernate.type.descriptor.java.BigDecimalTypeDescriptor;
+
/**
* @author Steve Ebersole
*/
diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BigIntegerDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BigIntegerDescriptorTest.java
similarity index 93%
rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BigIntegerDescriptorTest.java
rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BigIntegerDescriptorTest.java
index fceb752037..76ec3e94bb 100644
--- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BigIntegerDescriptorTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BigIntegerDescriptorTest.java
@@ -21,9 +21,11 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.type.descriptor.java;
+package org.hibernate.test.type.descriptor.java;
import java.math.BigInteger;
+import org.hibernate.type.descriptor.java.BigIntegerTypeDescriptor;
+
/**
* @author Steve Ebersole
*/
diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BlobDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BlobDescriptorTest.java
similarity index 92%
rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BlobDescriptorTest.java
rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BlobDescriptorTest.java
index 8cdc89ab4e..b5f1cd2935 100644
--- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BlobDescriptorTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BlobDescriptorTest.java
@@ -21,13 +21,16 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.type.descriptor.java;
+package org.hibernate.test.type.descriptor.java;
import java.sql.Blob;
import java.sql.SQLException;
import org.junit.Test;
import org.hibernate.engine.jdbc.BlobProxy;
+import org.hibernate.type.descriptor.java.BlobTypeDescriptor;
+import org.hibernate.type.descriptor.java.DataHelper;
+import org.hibernate.type.descriptor.java.PrimitiveByteArrayTypeDescriptor;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BooleanDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BooleanDescriptorTest.java
similarity index 93%
rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BooleanDescriptorTest.java
rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BooleanDescriptorTest.java
index 15cb04dd24..a045f548c6 100644
--- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BooleanDescriptorTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BooleanDescriptorTest.java
@@ -21,9 +21,11 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.type.descriptor.java;
+package org.hibernate.test.type.descriptor.java;
+import org.hibernate.type.descriptor.java.BooleanTypeDescriptor;
+
/**
* @author Steve Ebersole
*/
diff --git a/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/LocaleTypeDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/LocaleTypeDescriptorTest.java
new file mode 100644
index 0000000000..0c1da5b205
--- /dev/null
+++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/LocaleTypeDescriptorTest.java
@@ -0,0 +1,70 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2013, Red Hat Inc. 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 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.type.descriptor.java;
+
+import java.util.Locale;
+import java.util.StringTokenizer;
+
+import org.hibernate.internal.util.StringHelper;
+import org.hibernate.type.descriptor.java.LocaleTypeDescriptor;
+
+import org.junit.Test;
+
+import org.hibernate.testing.junit4.BaseUnitTestCase;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Tests of the {@link LocaleTypeDescriptor} class.
+ *
+ * @author Christian Beikov
+ * @author Steve Ebersole
+ */
+public class LocaleTypeDescriptorTest extends BaseUnitTestCase {
+
+ @Test
+ public void testConversionFromString() {
+ assertEquals( toLocale( "de", null, null ), LocaleTypeDescriptor.INSTANCE.fromString( "de" ) );
+ assertEquals( toLocale( "de", "DE", null ), LocaleTypeDescriptor.INSTANCE.fromString( "de_DE" ) );
+ assertEquals( toLocale( null, "DE", null ), LocaleTypeDescriptor.INSTANCE.fromString( "_DE" ) );
+ assertEquals( toLocale( null, null, "ch123" ), LocaleTypeDescriptor.INSTANCE.fromString( "__ch123" ) );
+ assertEquals( toLocale( null, "DE", "ch123" ), LocaleTypeDescriptor.INSTANCE.fromString( "_DE_ch123" ) );
+ assertEquals( toLocale( "de", null, "ch123" ), LocaleTypeDescriptor.INSTANCE.fromString( "de__ch123" ) );
+ assertEquals( toLocale( "de", "DE", "ch123" ), LocaleTypeDescriptor.INSTANCE.fromString( "de_DE_ch123" ) );
+ }
+
+ public Locale toLocale(String lang, String region, String variant) {
+ final Locale.Builder builder = new Locale.Builder();
+ if ( StringHelper.isNotEmpty( lang ) ) {
+ builder.setLanguage( lang );
+ }
+ if ( StringHelper.isNotEmpty( region ) ) {
+ builder.setRegion( region );
+ }
+ if ( StringHelper.isNotEmpty( variant ) ) {
+ builder.setVariant( variant );
+ }
+ return builder.build();
+ }
+}
diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/StringDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/StringDescriptorTest.java
similarity index 93%
rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/java/StringDescriptorTest.java
rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/StringDescriptorTest.java
index 496358865c..df48304864 100644
--- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/StringDescriptorTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/StringDescriptorTest.java
@@ -21,9 +21,11 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.type.descriptor.java;
+package org.hibernate.test.type.descriptor.java;
+import org.hibernate.type.descriptor.java.StringTypeDescriptor;
+
/**
* @author Steve Ebersole
*/
diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/PreparedStatementProxy.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/PreparedStatementProxy.java
similarity index 98%
rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/PreparedStatementProxy.java
rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/PreparedStatementProxy.java
index 521f1cd749..2429ed9c2f 100644
--- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/PreparedStatementProxy.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/PreparedStatementProxy.java
@@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.type.descriptor.sql;
+package org.hibernate.test.type.descriptor.sql;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/ResultSetProxy.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/ResultSetProxy.java
similarity index 98%
rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/ResultSetProxy.java
rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/ResultSetProxy.java
index 5406a25a75..a8932c1d39 100644
--- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/ResultSetProxy.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/ResultSetProxy.java
@@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.type.descriptor.sql;
+package org.hibernate.test.type.descriptor.sql;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/StringClobImpl.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/StringClobImpl.java
similarity index 98%
rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/StringClobImpl.java
rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/StringClobImpl.java
index e7e362c459..3a0246e492 100644
--- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/StringClobImpl.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/StringClobImpl.java
@@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.type.descriptor.sql;
+package org.hibernate.test.type.descriptor.sql;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/StringValueMappingTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/StringValueMappingTest.java
similarity index 95%
rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/StringValueMappingTest.java
rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/StringValueMappingTest.java
index 2803819df3..992cb643e1 100644
--- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/StringValueMappingTest.java
+++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/StringValueMappingTest.java
@@ -21,7 +21,7 @@
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
-package org.hibernate.type.descriptor.sql;
+package org.hibernate.test.type.descriptor.sql;
import java.sql.Clob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@@ -36,6 +36,9 @@ import org.hibernate.type.descriptor.ValueBinder;
import org.hibernate.type.descriptor.ValueExtractor;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.StringTypeDescriptor;
+import org.hibernate.type.descriptor.sql.ClobTypeDescriptor;
+import org.hibernate.type.descriptor.sql.SqlTypeDescriptor;
+import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java
index fff05b346d..beb9e86272 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java
@@ -23,14 +23,17 @@
*/
package org.hibernate.cache.ehcache;
+import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.util.ClassLoaderUtil;
+
import org.jboss.logging.Logger;
+import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.nonstop.NonstopAccessStrategyFactory;
import org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion;
@@ -40,7 +43,7 @@ import org.hibernate.cache.ehcache.internal.regions.EhcacheQueryResultsRegion;
import org.hibernate.cache.ehcache.internal.regions.EhcacheTimestampsRegion;
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory;
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactoryImpl;
-import org.hibernate.cache.ehcache.internal.util.HibernateUtil;
+import org.hibernate.cache.ehcache.internal.util.HibernateEhcacheUtils;
import org.hibernate.cache.ehcache.management.impl.ProviderMBeanRegistrationHelper;
import org.hibernate.cache.spi.AbstractRegionFactory;
import org.hibernate.cache.spi.CacheDataDescription;
@@ -50,8 +53,7 @@ import org.hibernate.cache.spi.NaturalIdRegion;
import org.hibernate.cache.spi.QueryResultsRegion;
import org.hibernate.cache.spi.TimestampsRegion;
import org.hibernate.cache.spi.access.AccessType;
-import org.hibernate.cfg.Settings;
-import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
+import org.hibernate.service.spi.InjectService;
/**
* Abstract implementation of an Ehcache specific RegionFactory.
@@ -88,11 +90,6 @@ abstract class AbstractEhcacheRegionFactory extends AbstractRegionFactory {
*/
protected volatile CacheManager manager;
- /**
- * Settings object for the Hibernate persistence unit.
- */
- protected Settings settings;
-
/**
* {@link EhcacheAccessStrategyFactory} for creating various access strategies
*/
@@ -116,99 +113,64 @@ abstract class AbstractEhcacheRegionFactory extends AbstractRegionFactory {
return true;
}
- /**
- * {@inheritDoc}
- */
- public long nextTimestamp() {
- return net.sf.ehcache.util.Timestamper.next();
- }
- /**
- * {@inheritDoc}
- */
- public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata)
- throws CacheException {
- return new EhcacheEntityRegion( accessStrategyFactory, getCache( regionName ), isMinimalPutsEnabled(), metadata, properties );
- }
-
- @Override
- public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata)
- throws CacheException {
- return new EhcacheNaturalIdRegion( accessStrategyFactory, getCache( regionName ), isMinimalPutsEnabled(), metadata, properties );
- }
- /**
- * {@inheritDoc}
- */
- public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata)
- throws CacheException {
- return new EhcacheCollectionRegion(
- accessStrategyFactory,
- getCache( regionName ),
- isMinimalPutsEnabled(),
- metadata,
- properties
- );
- }
+ private Ehcache getCache(String name) throws CacheException {
+ try {
+ Ehcache cache = manager.getEhcache( name );
+ if ( cache == null ) {
+ LOG.unableToFindEhCacheConfiguration( name );
+ manager.addCache( name );
+ cache = manager.getEhcache( name );
+ LOG.debug( "started EHCache region: " + name );
+ }
+ HibernateEhcacheUtils.validateEhcache( cache );
+ return cache;
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ throw new CacheException( e );
+ }
- /**
- * {@inheritDoc}
- */
- public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException {
- return new EhcacheQueryResultsRegion( accessStrategyFactory, getCache( regionName ), properties );
- }
- /**
- * {@inheritDoc}
- */
- public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException {
- return new EhcacheTimestampsRegion( accessStrategyFactory, getCache( regionName ), properties );
- }
+ }
- private Ehcache getCache(String name) throws CacheException {
- try {
- Ehcache cache = manager.getEhcache( name );
- if ( cache == null ) {
- LOG.unableToFindEhCacheConfiguration( name );
- manager.addCache( name );
- cache = manager.getEhcache( name );
- LOG.debug( "started EHCache region: " + name );
- }
- HibernateUtil.validateEhcache( cache );
- return cache;
- }
- catch ( net.sf.ehcache.CacheException e ) {
- throw new CacheException( e );
- }
+ /**
+ * Load a resource from the classpath.
+ */
+ protected URL loadResource(String configurationResourceName) {
+ URL url = null;
+ if ( classLoaderService != null ) {
+ url = classLoaderService.locateResource( configurationResourceName );
+ }
+ if ( url == null ) {
+ final ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();
+ if ( standardClassloader != null ) {
+ url = standardClassloader.getResource( configurationResourceName );
+ }
+ if ( url == null ) {
+ url = AbstractEhcacheRegionFactory.class.getResource( configurationResourceName );
+ }
+ if ( url == null ) {
+ try {
+ url = new URL( configurationResourceName );
+ }
+ catch ( MalformedURLException e ) {
+ // ignore
+ }
+ }
+ }
+ if ( LOG.isDebugEnabled() ) {
+ LOG.debugf(
+ "Creating EhCacheRegionFactory from a specified resource: %s. Resolved to URL: %s",
+ configurationResourceName,
+ url
+ );
+ }
+ if ( url == null ) {
- }
-
- /**
- * Load a resource from the classpath.
- */
- protected URL loadResource(String configurationResourceName) {
- URL url = getServiceRegistry().getService( ClassLoaderService.class ).locateResource( configurationResourceName );
- if ( url == null ) {
- ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();
- if ( standardClassloader != null ) {
- url = standardClassloader.getResource( configurationResourceName );
- }
- if ( url == null ) {
- url = AbstractEhcacheRegionFactory.class.getResource( configurationResourceName );
- }
- }
- if ( LOG.isDebugEnabled() ) {
- LOG.debugf(
- "Creating EhCacheRegionFactory from a specified resource: %s. Resolved to URL: %s",
- configurationResourceName,
- url
- );
- }
- if ( url == null ) {
-
- LOG.unableToLoadConfiguration( configurationResourceName );
- }
- return url;
- }
+ LOG.unableToLoadConfiguration( configurationResourceName );
+ }
+ return url;
+ }
/**
* Default access-type used when the configured using JPA 2.0 config. JPA 2.0 allows @Cacheable(true) to be attached to an
@@ -221,4 +183,66 @@ abstract class AbstractEhcacheRegionFactory extends AbstractRegionFactory {
public AccessType getDefaultAccessType() {
return AccessType.READ_WRITE;
}
+
+
+ @Override
+ public long nextTimestamp() {
+ return net.sf.ehcache.util.Timestamper.next();
+ }
+
+ @Override
+ public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata)
+ throws CacheException {
+ return new EhcacheEntityRegion( accessStrategyFactory, getCache( regionName ),isMinimalPutsEnabled(), metadata, properties );
+ }
+
+ @Override
+ public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata)
+ throws CacheException {
+ return new EhcacheNaturalIdRegion(
+ accessStrategyFactory,
+ getCache( regionName ),
+ isMinimalPutsEnabled(),
+ metadata,
+ properties
+ );
+ }
+
+ @Override
+ public CollectionRegion buildCollectionRegion(
+ String regionName,
+ Properties properties,
+ CacheDataDescription metadata)
+ throws CacheException {
+ return new EhcacheCollectionRegion(
+ accessStrategyFactory,
+ getCache( regionName ),
+ isMinimalPutsEnabled(),
+ metadata,
+ properties
+ );
+ }
+
+ @Override
+ public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException {
+ return new EhcacheQueryResultsRegion( accessStrategyFactory, getCache( regionName ), properties );
+ }
+
+ @InjectService
+ @SuppressWarnings("UnusedDeclaration")
+ public void setClassLoaderService(ClassLoaderService classLoaderService) {
+ this.classLoaderService = classLoaderService;
+ }
+
+ private ClassLoaderService classLoaderService;
+
+ @Override
+ public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException {
+ return new EhcacheTimestampsRegion( accessStrategyFactory, getCache( regionName ), properties );
+ }
+
+
+
+
+
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheMessageLogger.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheMessageLogger.java
index c7fdc74ea2..dcceea5bfd 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheMessageLogger.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheMessageLogger.java
@@ -37,45 +37,99 @@ import static org.jboss.logging.Logger.Level.WARN;
*
* New messages must be added after the last message defined to ensure message codes are unique.
*/
-@MessageLogger( projectCode = "HHH" )
+@MessageLogger(projectCode = "HHH")
public interface EhCacheMessageLogger extends CoreMessageLogger {
- @LogMessage( level = WARN )
- @Message( value = "Attempt to restart an already started EhCacheProvider. Use sessionFactory.close() between repeated calls to "
- + "buildSessionFactory. Using previously created EhCacheProvider. If this behaviour is required, consider "
- + "using net.sf.ehcache.hibernate.SingletonEhCacheProvider.", id = 20001 )
- void attemptToRestartAlreadyStartedEhCacheProvider();
+ /**
+ * Log a message (WARN) about attempt to start an already started Ehcache region factory
+ */
+ @LogMessage(level = WARN)
+ @Message(
+ value = "Attempt to restart an already started EhCacheRegionFactory. Use sessionFactory.close() between " +
+ "repeated calls to buildSessionFactory. Using previously created EhCacheRegionFactory. If this " +
+ "behaviour is required, consider using org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory.",
+ id = 20001
+ )
+ void attemptToRestartAlreadyStartedEhCacheProvider();
- @LogMessage( level = WARN )
- @Message( value = "Could not find configuration [%s]; using defaults.", id = 20002 )
- void unableToFindConfiguration( String name );
+ /**
+ * Log a message (WARN) about inability to find configuration file
+ *
+ * @param name The name of the configuration file
+ */
+ @LogMessage(level = WARN)
+ @Message(value = "Could not find configuration [%s]; using defaults.", id = 20002)
+ void unableToFindConfiguration(String name);
- @LogMessage( level = WARN )
- @Message( value = "Could not find a specific ehcache configuration for cache named [%s]; using defaults.", id = 20003 )
- void unableToFindEhCacheConfiguration( String name );
+ /**
+ * Log a message (WARN) about inability to find named cache configuration
+ *
+ * @param name The name of the cache configuration
+ */
+ @LogMessage(level = WARN)
+ @Message(value = "Could not find a specific ehcache configuration for cache named [%s]; using defaults.", id = 20003)
+ void unableToFindEhCacheConfiguration(String name);
- @LogMessage( level = WARN )
- @Message( value = "A configurationResourceName was set to %s but the resource could not be loaded from the classpath. Ehcache will configure itself using defaults.", id = 20004 )
- void unableToLoadConfiguration( String configurationResourceName );
+ /**
+ * Logs a message about not being able to resolve the configuration by resource name.
+ *
+ * @param configurationResourceName The resource name we attempted to resolve
+ */
+ @LogMessage(level = WARN)
+ @Message(
+ value = "A configurationResourceName was set to %s but the resource could not be loaded from the classpath. " +
+ "Ehcache will configure itself using defaults.",
+ id = 20004
+ )
+ void unableToLoadConfiguration(String configurationResourceName);
- @LogMessage( level = WARN )
- @Message( value = "The default cache value mode for this Ehcache configuration is \"identity\". This is incompatible with clustered "
- + "Hibernate caching - the value mode has therefore been switched to \"serialization\"", id = 20005 )
- void incompatibleCacheValueMode( );
+ /**
+ * Logs a message (WARN) about attempt to use an incompatible
+ * {@link net.sf.ehcache.config.TerracottaConfiguration.ValueMode}.
+ */
+ @LogMessage(level = WARN)
+ @Message(
+ value = "The default cache value mode for this Ehcache configuration is \"identity\". " +
+ "This is incompatible with clustered Hibernate caching - the value mode has therefore been " +
+ "switched to \"serialization\"",
+ id = 20005
+ )
+ void incompatibleCacheValueMode();
- @LogMessage( level = WARN )
- @Message( value = "The value mode for the cache[%s] is \"identity\". This is incompatible with clustered Hibernate caching - "
- + "the value mode has therefore been switched to \"serialization\"", id = 20006 )
- void incompatibleCacheValueModePerCache( String cacheName );
- @LogMessage( level = WARN )
- @Message( value = "read-only cache configured for mutable entity [%s]", id = 20007 )
- void readOnlyCacheConfiguredForMutableEntity( String entityName );
+ /**
+ * Logs a message (WARN) about attempt to use an incompatible
+ * {@link net.sf.ehcache.config.TerracottaConfiguration.ValueMode}.
+ *
+ * @param cacheName The name of the cache whose config attempted to specify value mode.
+ */
+ @LogMessage(level = WARN)
+ @Message(value = "The value mode for the cache[%s] is \"identity\". This is incompatible with clustered Hibernate caching - "
+ + "the value mode has therefore been switched to \"serialization\"", id = 20006)
+ void incompatibleCacheValueModePerCache(String cacheName);
- @LogMessage( level = WARN )
- @Message( value = "Cache[%s] Key[%s] Lockable[%s]\n"
- + "A soft-locked cache entry was expired by the underlying Ehcache. "
- + "If this happens regularly you should consider increasing the cache timeouts and/or capacity limits", id = 20008 )
- void softLockedCacheExpired( String regionName, Object key, String lock);
+ /**
+ * Log a message (WARN) about an attempt to specify read-only caching for a mutable entity
+ *
+ * @param entityName The name of the entity
+ */
+ @LogMessage(level = WARN)
+ @Message(value = "read-only cache configured for mutable entity [%s]", id = 20007)
+ void readOnlyCacheConfiguredForMutableEntity(String entityName);
+ /**
+ * Log a message (WARN) about expiry of soft-locked region.
+ *
+ * @param regionName The region name
+ * @param key The cache key
+ * @param lock The lock
+ */
+ @LogMessage(level = WARN)
+ @Message(
+ value = "Cache[%s] Key[%s] Lockable[%s]\n" +
+ "A soft-locked cache entry was expired by the underlying Ehcache. If this happens regularly you " +
+ "should consider increasing the cache timeouts and/or capacity limits",
+ id = 20008
+ )
+ void softLockedCacheExpired(String regionName, Object key, String lock);
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java
index 3d90de81e2..c8f42474b9 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java
@@ -30,12 +30,13 @@ import java.util.Properties;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.Configuration;
import net.sf.ehcache.config.ConfigurationFactory;
+
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
-import org.hibernate.cache.ehcache.internal.util.HibernateUtil;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.config.spi.StandardConverters;
+import org.hibernate.cache.ehcache.internal.util.HibernateEhcacheUtils;
/**
* A non-singleton EhCacheRegionFactory implementation.
@@ -47,11 +48,28 @@ import org.hibernate.engine.config.spi.StandardConverters;
* @author Alex Snaps
*/
public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory {
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ EhCacheRegionFactory.class.getName()
+ );
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- EhCacheRegionFactory.class.getName()
- );
+
+ /**
+ * Creates a non-singleton EhCacheRegionFactory
+ */
+ @SuppressWarnings("UnusedDeclaration")
+ public EhCacheRegionFactory() {
+ }
+
+ /**
+ * Creates a non-singleton EhCacheRegionFactory
+ *
+ * @param prop Not used
+ */
+ @SuppressWarnings("UnusedDeclaration")
+ public EhCacheRegionFactory(Properties prop) {
+ super();
+ }
@Override
public void start() {
@@ -62,7 +80,8 @@ public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory {
try {
ConfigurationService configurationService = getServiceRegistry().getService( ConfigurationService.class );
- String configurationResourceName = configurationService.getSetting( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME,
+ String configurationResourceName = configurationService.getSetting(
+ NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME,
StandardConverters.STRING, null
);
if ( configurationResourceName == null || configurationResourceName.length() == 0 ) {
@@ -77,10 +96,10 @@ public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory {
catch ( MalformedURLException e ) {
url = loadResource( configurationResourceName );
}
- Configuration configuration = HibernateUtil.loadAndCorrectConfiguration( url );
+ Configuration configuration = HibernateEhcacheUtils.loadAndCorrectConfiguration( url );
manager = new CacheManager( configuration );
}
- Properties properties = new Properties( );
+ Properties properties = new Properties();
properties.putAll( configurationService.getSettings() );
mbeanRegistrationHelper.registerMBean( manager, properties );
}
@@ -101,20 +120,18 @@ public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory {
}
}
- /**
- * {@inheritDoc}
- */
- public void stop() {
- try {
- if ( manager != null ) {
- mbeanRegistrationHelper.unregisterMBean();
- manager.shutdown();
- manager = null;
- }
- }
- catch ( net.sf.ehcache.CacheException e ) {
- throw new CacheException( e );
- }
- }
+ @Override
+ public void stop() {
+ try {
+ if ( manager != null ) {
+ mbeanRegistrationHelper.unregisterMBean();
+ manager.shutdown();
+ manager = null;
+ }
+ }
+ catch ( net.sf.ehcache.CacheException e ) {
+ throw new CacheException( e );
+ }
+ }
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/SingletonEhCacheRegionFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/SingletonEhCacheRegionFactory.java
index b32810f4f8..af5d4b950d 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/SingletonEhCacheRegionFactory.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/SingletonEhCacheRegionFactory.java
@@ -30,10 +30,11 @@ import java.util.concurrent.atomic.AtomicInteger;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.Configuration;
+
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
-import org.hibernate.cache.ehcache.internal.util.HibernateUtil;
+import org.hibernate.cache.ehcache.internal.util.HibernateEhcacheUtils;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.config.spi.StandardConverters;
@@ -46,12 +47,12 @@ import org.hibernate.engine.config.spi.StandardConverters;
* @author Alex Snaps
*/
public class SingletonEhCacheRegionFactory extends AbstractEhcacheRegionFactory {
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ SingletonEhCacheRegionFactory.class.getName()
+ );
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- SingletonEhCacheRegionFactory.class.getName()
- );
- private static final AtomicInteger REFERENCE_COUNT = new AtomicInteger();
+ private static final AtomicInteger REFERENCE_COUNT = new AtomicInteger();
@Override
public void start() {
@@ -79,7 +80,7 @@ public class SingletonEhCacheRegionFactory extends AbstractEhcacheRegionFactory
}
url = loadResource( configurationResourceName );
}
- Configuration configuration = HibernateUtil.loadAndCorrectConfiguration( url );
+ Configuration configuration = HibernateEhcacheUtils.loadAndCorrectConfiguration( url );
manager = CacheManager.create( configuration );
REFERENCE_COUNT.incrementAndGet();
}
@@ -109,5 +110,22 @@ public class SingletonEhCacheRegionFactory extends AbstractEhcacheRegionFactory
throw new CacheException( e );
}
}
+ /**
+ * Constructs a SingletonEhCacheRegionFactory
+ */
+ @SuppressWarnings("UnusedDeclaration")
+ public SingletonEhCacheRegionFactory() {
+ }
+
+ /**
+ * Constructs a SingletonEhCacheRegionFactory
+ *
+ * @param prop Not used
+ */
+ @SuppressWarnings("UnusedDeclaration")
+ public SingletonEhCacheRegionFactory(Properties prop) {
+ super();
+ }
+
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AvailabilityAnnouncerImpl.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/StrategyRegistrationProviderImpl.java
similarity index 65%
rename from hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AvailabilityAnnouncerImpl.java
rename to hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/StrategyRegistrationProviderImpl.java
index 9efe6fa462..2c68ca1df8 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AvailabilityAnnouncerImpl.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/StrategyRegistrationProviderImpl.java
@@ -26,9 +26,9 @@ package org.hibernate.cache.ehcache;
import java.util.ArrayList;
import java.util.List;
-import org.hibernate.boot.registry.selector.Availability;
-import org.hibernate.boot.registry.selector.AvailabilityAnnouncer;
-import org.hibernate.boot.registry.selector.SimpleAvailabilityImpl;
+import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl;
+import org.hibernate.boot.registry.selector.StrategyRegistration;
+import org.hibernate.boot.registry.selector.StrategyRegistrationProvider;
import org.hibernate.cache.spi.RegionFactory;
/**
@@ -37,32 +37,36 @@ import org.hibernate.cache.spi.RegionFactory;
*
* @author Steve Ebersole
*/
-public class AvailabilityAnnouncerImpl implements AvailabilityAnnouncer {
+public class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider {
@Override
@SuppressWarnings("unchecked")
- public Iterable getAvailabilities() {
- final List availabilities = new ArrayList();
+ public Iterable getStrategyRegistrations() {
+ final List strategyRegistrations = new ArrayList();
- availabilities.add(
- new SimpleAvailabilityImpl(
+ strategyRegistrations.add(
+ new SimpleStrategyRegistrationImpl(
RegionFactory.class,
EhCacheRegionFactory.class,
"ehcache",
+ EhCacheRegionFactory.class.getName(),
EhCacheRegionFactory.class.getSimpleName(),
- "org.hibernate.cache.EhCacheRegionFactory" // legacy impl class name
+ // legacy impl class name
+ "org.hibernate.cache.EhCacheRegionFactory"
)
);
- availabilities.add(
- new SimpleAvailabilityImpl(
+ strategyRegistrations.add(
+ new SimpleStrategyRegistrationImpl(
RegionFactory.class,
SingletonEhCacheRegionFactory.class,
"ehcache-singleton",
+ SingletonEhCacheRegionFactory.class.getName(),
SingletonEhCacheRegionFactory.class.getSimpleName(),
- "org.hibernate.cache.SingletonEhCacheRegionFactory" // legacy impl class name
+ // legacy impl class name
+ "org.hibernate.cache.SingletonEhCacheRegionFactory"
)
);
- return availabilities;
+ return strategyRegistrations;
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/HibernateNonstopCacheExceptionHandler.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/HibernateNonstopCacheExceptionHandler.java
index af5b77a2e5..ebdf6da9de 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/HibernateNonstopCacheExceptionHandler.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/HibernateNonstopCacheExceptionHandler.java
@@ -24,6 +24,7 @@
package org.hibernate.cache.ehcache.internal.nonstop;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
+
import org.jboss.logging.Logger;
import org.hibernate.cache.ehcache.EhCacheMessageLogger;
@@ -35,61 +36,61 @@ import org.hibernate.cache.ehcache.EhCacheMessageLogger;
* @author Alex Snaps
*/
public final class HibernateNonstopCacheExceptionHandler {
- /**
- * Property name which set as "true" will throw exceptions on timeout with hibernate
- */
- public static final String HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY = "ehcache.hibernate.propagateNonStopCacheException";
+ /**
+ * Property name which set as "true" will throw exceptions on timeout with hibernate
+ */
+ public static final String HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY = "ehcache.hibernate.propagateNonStopCacheException";
- /**
- * Property name for logging the stack trace of the nonstop cache exception too. False by default
- */
- public static final String HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY = "ehcache.hibernate.logNonStopCacheExceptionStackTrace";
+ /**
+ * Property name for logging the stack trace of the nonstop cache exception too. False by default
+ */
+ public static final String HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY = "ehcache.hibernate.logNonStopCacheExceptionStackTrace";
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- HibernateNonstopCacheExceptionHandler.class.getName()
- );
- private static final HibernateNonstopCacheExceptionHandler INSTANCE = new HibernateNonstopCacheExceptionHandler();
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ HibernateNonstopCacheExceptionHandler.class.getName()
+ );
+ private static final HibernateNonstopCacheExceptionHandler INSTANCE = new HibernateNonstopCacheExceptionHandler();
- /**
- * private constructor
- */
- private HibernateNonstopCacheExceptionHandler() {
- // private
- }
+ /**
+ * private constructor
+ */
+ private HibernateNonstopCacheExceptionHandler() {
+ // private
+ }
- /**
- * Returns the singleton instance
- *
- * @return the singleton instance
- */
- public static HibernateNonstopCacheExceptionHandler getInstance() {
- return INSTANCE;
- }
+ /**
+ * Returns the singleton instance
+ *
+ * @return the singleton instance
+ */
+ public static HibernateNonstopCacheExceptionHandler getInstance() {
+ return INSTANCE;
+ }
- /**
- * Handle {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}.
- * If {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY} system property is set to true,
- * rethrows the {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}, otherwise logs the exception. While logging, if
- * {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY} is set to true, logs the exception stack
- * trace too, otherwise logs the exception message only
- *
- * @param nonStopCacheException
- */
- public void handleNonstopCacheException(NonStopCacheException nonStopCacheException) {
- if ( Boolean.getBoolean( HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY ) ) {
- throw nonStopCacheException;
- }
- else {
- if ( Boolean.getBoolean( HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY ) ) {
- LOG.debug(
- "Ignoring NonstopCacheException - " + nonStopCacheException.getMessage(),
- nonStopCacheException
- );
- }
- else {
- LOG.debug( "Ignoring NonstopCacheException - " + nonStopCacheException.getMessage() );
- }
- }
- }
+ /**
+ * Handle {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}.
+ * If {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY} system property is set to true,
+ * rethrows the {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}, otherwise logs the exception. While logging, if
+ * {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY} is set to true, logs the exception stack
+ * trace too, otherwise logs the exception message only
+ *
+ * @param nonStopCacheException The exception to handle
+ */
+ public void handleNonstopCacheException(NonStopCacheException nonStopCacheException) {
+ if ( Boolean.getBoolean( HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY ) ) {
+ throw nonStopCacheException;
+ }
+ else {
+ if ( Boolean.getBoolean( HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY ) ) {
+ LOG.debug(
+ "Ignoring NonstopCacheException - " + nonStopCacheException.getMessage(),
+ nonStopCacheException
+ );
+ }
+ else {
+ LOG.debug( "Ignoring NonstopCacheException - " + nonStopCacheException.getMessage() );
+ }
+ }
+ }
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAccessStrategyFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAccessStrategyFactory.java
index 93ab9c897c..b379584285 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAccessStrategyFactory.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAccessStrategyFactory.java
@@ -41,49 +41,49 @@ import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy;
*/
public class NonstopAccessStrategyFactory implements EhcacheAccessStrategyFactory {
- private final EhcacheAccessStrategyFactory actualFactory;
-
- /**
- * Constructor accepting the actual factory
- *
- * @param actualFactory
- */
- public NonstopAccessStrategyFactory(EhcacheAccessStrategyFactory actualFactory) {
- this.actualFactory = actualFactory;
- }
-
- /**
- * {@inheritDoc}
- */
- public EntityRegionAccessStrategy createEntityRegionAccessStrategy(EhcacheEntityRegion entityRegion, AccessType accessType) {
- return new NonstopAwareEntityRegionAccessStrategy(
- actualFactory.createEntityRegionAccessStrategy( entityRegion, accessType ),
- HibernateNonstopCacheExceptionHandler.getInstance()
- );
- }
-
- @Override
- public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion naturalIdRegion,
- AccessType accessType) {
- return new NonstopAwareNaturalIdRegionAccessStrategy(
- actualFactory.createNaturalIdRegionAccessStrategy(
- naturalIdRegion,
- accessType
- ), HibernateNonstopCacheExceptionHandler.getInstance()
- );
- }
+ private final EhcacheAccessStrategyFactory actualFactory;
/**
- * {@inheritDoc}
- */
- public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(EhcacheCollectionRegion collectionRegion,
- AccessType accessType) {
- return new NonstopAwareCollectionRegionAccessStrategy(
- actualFactory.createCollectionRegionAccessStrategy(
- collectionRegion,
- accessType
- ), HibernateNonstopCacheExceptionHandler.getInstance()
- );
- }
+ * Constructor accepting the actual factory
+ *
+ * @param actualFactory The wrapped RegionAccessStrategy factory
+ */
+ public NonstopAccessStrategyFactory(EhcacheAccessStrategyFactory actualFactory) {
+ this.actualFactory = actualFactory;
+ }
+
+ @Override
+ public EntityRegionAccessStrategy createEntityRegionAccessStrategy(
+ EhcacheEntityRegion entityRegion,
+ AccessType accessType) {
+ return new NonstopAwareEntityRegionAccessStrategy(
+ actualFactory.createEntityRegionAccessStrategy( entityRegion, accessType ),
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ );
+ }
+
+ @Override
+ public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(
+ EhcacheNaturalIdRegion naturalIdRegion,
+ AccessType accessType) {
+ return new NonstopAwareNaturalIdRegionAccessStrategy(
+ actualFactory.createNaturalIdRegionAccessStrategy(
+ naturalIdRegion,
+ accessType
+ ), HibernateNonstopCacheExceptionHandler.getInstance()
+ );
+ }
+
+ @Override
+ public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(
+ EhcacheCollectionRegion collectionRegion,
+ AccessType accessType) {
+ return new NonstopAwareCollectionRegionAccessStrategy(
+ actualFactory.createCollectionRegionAccessStrategy(
+ collectionRegion,
+ accessType
+ ), HibernateNonstopCacheExceptionHandler.getInstance()
+ );
+ }
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareCollectionRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareCollectionRegionAccessStrategy.java
index 3f1f2cc1db..fdd82bd9cf 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareCollectionRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareCollectionRegionAccessStrategy.java
@@ -38,188 +38,139 @@ import org.hibernate.cache.spi.access.SoftLock;
* @author Alex Snaps
*/
public class NonstopAwareCollectionRegionAccessStrategy implements CollectionRegionAccessStrategy {
-
private final CollectionRegionAccessStrategy actualStrategy;
private final HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler;
/**
* Constructor accepting the actual {@link CollectionRegionAccessStrategy} and the {@link HibernateNonstopCacheExceptionHandler}
*
- * @param actualStrategy
- * @param hibernateNonstopExceptionHandler
+ * @param actualStrategy The wrapped strategy
+ * @param hibernateNonstopExceptionHandler The exception handler
*/
- public NonstopAwareCollectionRegionAccessStrategy(CollectionRegionAccessStrategy actualStrategy,
- HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
+ public NonstopAwareCollectionRegionAccessStrategy(
+ CollectionRegionAccessStrategy actualStrategy,
+ HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
this.actualStrategy = actualStrategy;
this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler;
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#getRegion()
- */
+ @Override
public CollectionRegion getRegion() {
return actualStrategy.getRegion();
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evict(java.lang.Object)
- */
+ @Override
public void evict(Object key) throws CacheException {
try {
actualStrategy.evict( key );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll()
- */
+ @Override
public void evictAll() throws CacheException {
try {
actualStrategy.evictAll();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long)
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
return actualStrategy.get( key, txTimestamp );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
- */
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
try {
return actualStrategy.lockItem( key, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion()
- */
+ @Override
public SoftLock lockRegion() throws CacheException {
try {
return actualStrategy.lockRegion();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object,
- * boolean)
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version, minimalPutOverride );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#remove(java.lang.Object)
- */
+ @Override
public void remove(Object key) throws CacheException {
try {
actualStrategy.remove( key );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll()
- */
+ @Override
public void removeAll() throws CacheException {
try {
actualStrategy.removeAll();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
- */
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
try {
actualStrategy.unlockItem( key, lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockRegion(org.hibernate.cache.spi.access.SoftLock)
- */
+ @Override
public void unlockRegion(SoftLock lock) throws CacheException {
try {
actualStrategy.unlockRegion( lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareEntityRegionAccessStrategy.java
index 45f26270d0..e755bd0f28 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareEntityRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareEntityRegionAccessStrategy.java
@@ -38,253 +38,186 @@ import org.hibernate.cache.spi.access.SoftLock;
* @author Alex Snaps
*/
public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAccessStrategy {
-
private final EntityRegionAccessStrategy actualStrategy;
private final HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler;
/**
* Constructor accepting the actual {@link EntityRegionAccessStrategy} and the {@link HibernateNonstopCacheExceptionHandler}
*
- * @param actualStrategy
- * @param hibernateNonstopExceptionHandler
+ * @param actualStrategy The wrapped EntityRegionAccessStrategy
+ * @param hibernateNonstopExceptionHandler The exception handler
*/
- public NonstopAwareEntityRegionAccessStrategy(EntityRegionAccessStrategy actualStrategy,
- HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
+ public NonstopAwareEntityRegionAccessStrategy(
+ EntityRegionAccessStrategy actualStrategy,
+ HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
this.actualStrategy = actualStrategy;
this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler;
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#getRegion()
- */
+ @Override
public EntityRegion getRegion() {
return actualStrategy.getRegion();
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#afterInsert(java.lang.Object, java.lang.Object, java.lang.Object)
- */
+ @Override
public boolean afterInsert(Object key, Object value, Object version) throws CacheException {
try {
return actualStrategy.afterInsert( key, value, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#afterUpdate(java.lang.Object, java.lang.Object, java.lang.Object,
- * java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
- */
+ @Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock)
throws CacheException {
try {
return actualStrategy.afterUpdate( key, value, currentVersion, previousVersion, lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evict(java.lang.Object)
- */
+ @Override
public void evict(Object key) throws CacheException {
try {
actualStrategy.evict( key );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll()
- */
+ @Override
public void evictAll() throws CacheException {
try {
actualStrategy.evictAll();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long)
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
return actualStrategy.get( key, txTimestamp );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#insert(java.lang.Object, java.lang.Object, java.lang.Object)
- */
+ @Override
public boolean insert(Object key, Object value, Object version) throws CacheException {
try {
return actualStrategy.insert( key, value, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
- */
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
try {
return actualStrategy.lockItem( key, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion()
- */
+ @Override
public SoftLock lockRegion() throws CacheException {
try {
return actualStrategy.lockRegion();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object,
- * boolean)
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version, minimalPutOverride );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#remove(java.lang.Object)
- */
+ @Override
public void remove(Object key) throws CacheException {
try {
actualStrategy.remove( key );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll()
- */
+ @Override
public void removeAll() throws CacheException {
try {
actualStrategy.removeAll();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
- */
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
try {
actualStrategy.unlockItem( key, lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockRegion(org.hibernate.cache.spi.access.SoftLock)
- */
+ @Override
public void unlockRegion(SoftLock lock) throws CacheException {
try {
actualStrategy.unlockRegion( lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#update(java.lang.Object, java.lang.Object, java.lang.Object,
- * java.lang.Object)
- */
+ @Override
public boolean update(Object key, Object value, Object currentVersion, Object previousVersion)
throws CacheException {
try {
return actualStrategy.update( key, value, currentVersion, previousVersion );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareNaturalIdRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareNaturalIdRegionAccessStrategy.java
index 45e8498d5b..b50d6b1e20 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareNaturalIdRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareNaturalIdRegionAccessStrategy.java
@@ -38,28 +38,28 @@ import org.hibernate.cache.spi.access.SoftLock;
* @author Alex Snaps
*/
public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegionAccessStrategy {
-
private final NaturalIdRegionAccessStrategy actualStrategy;
private final HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler;
/**
* Constructor accepting the actual {@link NaturalIdRegionAccessStrategy} and the {@link HibernateNonstopCacheExceptionHandler}
*
- * @param actualStrategy
- * @param hibernateNonstopExceptionHandler
+ * @param actualStrategy The wrapped NaturalIdRegionAccessStrategy
+ * @param hibernateNonstopExceptionHandler The exception handler
*/
- public NonstopAwareNaturalIdRegionAccessStrategy(NaturalIdRegionAccessStrategy actualStrategy,
- HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
+ public NonstopAwareNaturalIdRegionAccessStrategy(
+ NaturalIdRegionAccessStrategy actualStrategy,
+ HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) {
this.actualStrategy = actualStrategy;
this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler;
}
-
+
@Override
public boolean insert(Object key, Object value) throws CacheException {
try {
return actualStrategy.insert( key, value );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
@@ -70,7 +70,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
try {
return actualStrategy.afterInsert( key, value );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
@@ -81,7 +81,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
try {
return actualStrategy.update( key, value );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
@@ -92,178 +92,129 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio
try {
return actualStrategy.afterUpdate( key, value, lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#getRegion()
- */
+ @Override
public NaturalIdRegion getRegion() {
return actualStrategy.getRegion();
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evict(java.lang.Object)
- */
+ @Override
public void evict(Object key) throws CacheException {
try {
actualStrategy.evict( key );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll()
- */
+ @Override
public void evictAll() throws CacheException {
try {
actualStrategy.evictAll();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long)
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
return actualStrategy.get( key, txTimestamp );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object)
- */
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
try {
return actualStrategy.lockItem( key, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion()
- */
+ @Override
public SoftLock lockRegion() throws CacheException {
try {
return actualStrategy.lockRegion();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return null;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object,
- * boolean)
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version, minimalPutOverride );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object)
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException {
try {
return actualStrategy.putFromLoad( key, value, txTimestamp, version );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
return false;
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#remove(java.lang.Object)
- */
+ @Override
public void remove(Object key) throws CacheException {
try {
actualStrategy.remove( key );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll()
- */
+ @Override
public void removeAll() throws CacheException {
try {
actualStrategy.removeAll();
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock)
- */
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
try {
actualStrategy.unlockItem( key, lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
- /**
- * {@inheritDoc}
- *
- * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockRegion(org.hibernate.cache.spi.access.SoftLock)
- */
+ @Override
public void unlockRegion(SoftLock lock) throws CacheException {
try {
actualStrategy.unlockRegion( lock );
}
- catch ( NonStopCacheException nonStopCacheException ) {
+ catch (NonStopCacheException nonStopCacheException) {
hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/package-info.java
new file mode 100644
index 0000000000..1115173682
--- /dev/null
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/package-info.java
@@ -0,0 +1,5 @@
+/**
+ * Support for handling non-stop caches. Really no idea. The Ehcache guys added this and tbh I really do not
+ * understand the intent
+ */
+package org.hibernate.cache.ehcache.internal.nonstop;
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheCollectionRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheCollectionRegion.java
index 0444534f36..cc545f6464 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheCollectionRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheCollectionRegion.java
@@ -47,13 +47,14 @@ import org.hibernate.cfg.Settings;
* @author Alex Snaps
*/
public class EhcacheCollectionRegion extends EhcacheTransactionalDataRegion implements CollectionRegion {
-
-
- /**
- * Constructs an EhcacheCollectionRegion around the given underlying cache.
- *
- * @param accessStrategyFactory
- */
+ /**
+ * Constructs an EhcacheCollectionRegion around the given underlying cache.
+ *
+ * @param accessStrategyFactory The factory for building needed CollectionRegionAccessStrategy instance
+ * @param underlyingCache The ehcache cache instance
+ * @param metadata Metadata about the data to be cached in this region
+ * @param properties Any additional[ properties
+ */
public EhcacheCollectionRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, boolean isMinimalPutsEnabled,
CacheDataDescription metadata, Properties properties) {
super( accessStrategyFactory, underlyingCache, isMinimalPutsEnabled, metadata, properties );
@@ -63,6 +64,7 @@ public class EhcacheCollectionRegion extends EhcacheTransactionalDataRegion impl
* {@inheritDoc}
*/
public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
- return accessStrategyFactory.createCollectionRegionAccessStrategy( this, accessType );
+ return getAccessStrategyFactory().createCollectionRegionAccessStrategy( this, accessType );
}
-}
\ No newline at end of file
+}
+
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheDataRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheDataRegion.java
index dfab454bf9..6f86f13ce7 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheDataRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheDataRegion.java
@@ -32,6 +32,7 @@ import java.util.Properties;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
import net.sf.ehcache.util.Timestamper;
+
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
@@ -52,174 +53,163 @@ import org.hibernate.cache.spi.Region;
* @author Alex Snaps
*/
public abstract class EhcacheDataRegion implements Region {
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ EhcacheDataRegion.class.getName()
+ );
+ private static final String CACHE_LOCK_TIMEOUT_PROPERTY = "net.sf.ehcache.hibernate.cache_lock_timeout";
+ private static final int DEFAULT_CACHE_LOCK_TIMEOUT = 60000;
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- EhcacheDataRegion.class.getName()
- );
- private static final String CACHE_LOCK_TIMEOUT_PROPERTY = "net.sf.ehcache.hibernate.cache_lock_timeout";
- private static final int DEFAULT_CACHE_LOCK_TIMEOUT = 60000;
-
- /**
- * Ehcache instance backing this Hibernate data region.
- */
- protected final Ehcache cache;
-
- /**
- * The {@link EhcacheAccessStrategyFactory} used for creating various access strategies
- */
- protected final EhcacheAccessStrategyFactory accessStrategyFactory;
-
- private final int cacheLockTimeout;
+ private final Ehcache cache;
+ private final EhcacheAccessStrategyFactory accessStrategyFactory;
+ private final int cacheLockTimeout;
- /**
- * Create a Hibernate data region backed by the given Ehcache instance.
- */
- EhcacheDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Properties properties) {
- this.accessStrategyFactory = accessStrategyFactory;
- this.cache = cache;
- String timeout = properties.getProperty(
- CACHE_LOCK_TIMEOUT_PROPERTY,
- Integer.toString( DEFAULT_CACHE_LOCK_TIMEOUT )
- );
- this.cacheLockTimeout = Timestamper.ONE_MS * Integer.decode( timeout );
- }
+ /**
+ * Create a Hibernate data region backed by the given Ehcache instance.
+ */
+ EhcacheDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Properties properties) {
+ this.accessStrategyFactory = accessStrategyFactory;
+ this.cache = cache;
+ final String timeout = properties.getProperty(
+ CACHE_LOCK_TIMEOUT_PROPERTY,
+ Integer.toString( DEFAULT_CACHE_LOCK_TIMEOUT )
+ );
+ this.cacheLockTimeout = Timestamper.ONE_MS * Integer.decode( timeout );
+ }
- /**
- * {@inheritDoc}
- */
- public String getName() {
- return cache.getName();
- }
+ /**
+ * Ehcache instance backing this Hibernate data region.
+ */
+ protected Ehcache getCache() {
+ return cache;
+ }
- /**
- * {@inheritDoc}
- */
- public void destroy() throws CacheException {
- try {
- cache.getCacheManager().removeCache( cache.getName() );
- }
- catch ( IllegalStateException e ) {
- //When Spring and Hibernate are both involved this will happen in normal shutdown operation.
- //Do not throw an exception, simply log this one.
- LOG.debug( "This can happen if multiple frameworks both try to shutdown ehcache", e );
- }
- catch ( net.sf.ehcache.CacheException e ) {
- if ( e instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) e );
- }
- else {
- throw new CacheException( e );
- }
- }
- }
+ /**
+ * The {@link org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory} used for creating
+ * various access strategies
+ */
+ protected EhcacheAccessStrategyFactory getAccessStrategyFactory() {
+ return accessStrategyFactory;
+ }
- /**
- * {@inheritDoc}
- */
- public long getSizeInMemory() {
- try {
- return cache.calculateInMemorySize();
- }
- catch ( Throwable t ) {
- if ( t instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) t );
- }
- return -1;
- }
- }
+ /**
+ * Return the Ehcache instance backing this Hibernate data region.
+ *
+ * @return The underlying ehcache cache
+ */
+ public Ehcache getEhcache() {
+ return getCache();
+ }
- /**
- * {@inheritDoc}
- */
- public long getElementCountInMemory() {
- try {
- return cache.getMemoryStoreSize();
- }
- catch ( net.sf.ehcache.CacheException ce ) {
- if ( ce instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) ce );
- return -1;
- }
- else {
- throw new CacheException( ce );
- }
- }
- }
+ @Override
+ public String getName() {
+ return getCache().getName();
+ }
- /**
- * {@inheritDoc}
- */
- public long getElementCountOnDisk() {
- try {
- return cache.getDiskStoreSize();
- }
- catch ( net.sf.ehcache.CacheException ce ) {
- if ( ce instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) ce );
- return -1;
- }
- else {
- throw new CacheException( ce );
- }
- }
- }
+ @Override
+ public void destroy() throws CacheException {
+ try {
+ getCache().getCacheManager().removeCache( getCache().getName() );
+ }
+ catch (IllegalStateException e) {
+ //When Spring and Hibernate are both involved this will happen in normal shutdown operation.
+ //Do not throw an exception, simply log this one.
+ LOG.debug( "This can happen if multiple frameworks both try to shutdown ehcache", e );
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ if ( e instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) e );
+ }
+ else {
+ throw new CacheException( e );
+ }
+ }
+ }
- /**
- * {@inheritDoc}
- */
- public Map toMap() {
- try {
- Map result = new HashMap();
- for ( Object key : cache.getKeys() ) {
- result.put( key, cache.get( key ).getObjectValue() );
- }
- return result;
- }
- catch ( Exception e ) {
- if ( e instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) e );
- return Collections.emptyMap();
- }
- else {
- throw new CacheException( e );
- }
- }
- }
+ @Override
+ public long getSizeInMemory() {
+ try {
+ return getCache().calculateInMemorySize();
+ }
+ catch (Throwable t) {
+ if ( t instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) t );
+ }
+ return -1;
+ }
+ }
- /**
- * {@inheritDoc}
- */
- public long nextTimestamp() {
- return Timestamper.next();
- }
+ @Override
+ public long getElementCountInMemory() {
+ try {
+ return getCache().getMemoryStoreSize();
+ }
+ catch (net.sf.ehcache.CacheException ce) {
+ if ( ce instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) ce );
+ return -1;
+ }
+ else {
+ throw new CacheException( ce );
+ }
+ }
+ }
- /**
- * {@inheritDoc}
- */
- public int getTimeout() {
- return cacheLockTimeout;
- }
+ @Override
+ public long getElementCountOnDisk() {
+ try {
+ return getCache().getDiskStoreSize();
+ }
+ catch (net.sf.ehcache.CacheException ce) {
+ if ( ce instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) ce );
+ return -1;
+ }
+ else {
+ throw new CacheException( ce );
+ }
+ }
+ }
- /**
- * Return the Ehcache instance backing this Hibernate data region.
- */
- public Ehcache getEhcache() {
- return cache;
- }
+ @Override
+ public Map toMap() {
+ try {
+ final Map result = new HashMap();
+ for ( Object key : getCache().getKeys() ) {
+ result.put( key, getCache().get( key ).getObjectValue() );
+ }
+ return result;
+ }
+ catch (Exception e) {
+ if ( e instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) e );
+ return Collections.emptyMap();
+ }
+ else {
+ throw new CacheException( e );
+ }
+ }
+ }
+
+ @Override
+ public long nextTimestamp() {
+ return Timestamper.next();
+ }
+
+ @Override
+ public int getTimeout() {
+ return cacheLockTimeout;
+ }
+
+ @Override
+ public boolean contains(Object key) {
+ return getCache().isKeyInCache( key );
+ }
- /**
- * Returns true if this region contains data for the given key.
- *
- * This is a Hibernate 3.5 method.
- */
- public boolean contains(Object key) {
- return cache.isKeyInCache( key );
- }
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheEntityRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheEntityRegion.java
index 6686c39315..db99905b5c 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheEntityRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheEntityRegion.java
@@ -33,7 +33,6 @@ import org.hibernate.cache.spi.CacheDataDescription;
import org.hibernate.cache.spi.EntityRegion;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cache.spi.access.EntityRegionAccessStrategy;
-import org.hibernate.cfg.Settings;
/**
* An entity region specific wrapper around an Ehcache instance.
@@ -46,12 +45,11 @@ import org.hibernate.cfg.Settings;
* @author Alex Snaps
*/
public class EhcacheEntityRegion extends EhcacheTransactionalDataRegion implements EntityRegion {
-
-
/**
* Constructs an EhcacheEntityRegion around the given underlying cache.
*
- * @param accessStrategyFactory
+ * @param accessStrategyFactory The factory for building needed EntityRegionAccessStrategy instance
+ * @param underlyingCache The ehcache cache instance
*/
public EhcacheEntityRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, boolean isMinimalPutsEnabled,
CacheDataDescription metadata, Properties properties) {
@@ -62,6 +60,7 @@ public class EhcacheEntityRegion extends EhcacheTransactionalDataRegion implemen
* {@inheritDoc}
*/
public EntityRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
- return accessStrategyFactory.createEntityRegionAccessStrategy( this, accessType );
+ return getAccessStrategyFactory().createEntityRegionAccessStrategy( this, accessType );
}
-}
\ No newline at end of file
+}
+
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheGeneralDataRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheGeneralDataRegion.java
index 8af54afb93..79bbbdeaa4 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheGeneralDataRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheGeneralDataRegion.java
@@ -28,6 +28,7 @@ import java.util.Properties;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
+
import org.jboss.logging.Logger;
import org.hibernate.cache.CacheException;
@@ -48,119 +49,117 @@ import org.hibernate.cache.spi.GeneralDataRegion;
* @author Alex Snaps
*/
abstract class EhcacheGeneralDataRegion extends EhcacheDataRegion implements GeneralDataRegion {
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ EhcacheGeneralDataRegion.class.getName()
+ );
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- EhcacheGeneralDataRegion.class.getName()
- );
+ /**
+ * Constructs an EhcacheGeneralDataRegion around the given underlying cache.
+ *
+ * @param accessStrategyFactory The factory for building needed RegionAccessStrategy instance
+ * @param underlyingCache The ehcache cache instance
+ * @param properties Any additional[ properties
+ */
+ public EhcacheGeneralDataRegion(
+ EhcacheAccessStrategyFactory accessStrategyFactory,
+ Ehcache underlyingCache,
+ Properties properties) {
+ super( accessStrategyFactory, underlyingCache, properties );
+ }
- /**
- * Creates an EhcacheGeneralDataRegion using the given Ehcache instance as a backing.
- */
- public EhcacheGeneralDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Properties properties) {
- super( accessStrategyFactory, cache, properties );
- }
+ @Override
+ public Object get(Object key) throws CacheException {
+ try {
+ LOG.debugf( "key: %s", key );
+ if ( key == null ) {
+ return null;
+ }
+ else {
+ final Element element = getCache().get( key );
+ if ( element == null ) {
+ LOG.debugf( "Element for key %s is null", key );
+ return null;
+ }
+ else {
+ return element.getObjectValue();
+ }
+ }
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ if ( e instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) e );
+ return null;
+ }
+ else {
+ throw new CacheException( e );
+ }
+ }
+ }
- /**
- * {@inheritDoc}
- */
- public Object get(Object key) throws CacheException {
- try {
- LOG.debugf( "key: %s", key );
- if ( key == null ) {
- return null;
- }
- else {
- Element element = cache.get( key );
- if ( element == null ) {
- LOG.debugf( "Element for key %s is null", key );
- return null;
- }
- else {
- return element.getObjectValue();
- }
- }
- }
- catch ( net.sf.ehcache.CacheException e ) {
- if ( e instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) e );
- return null;
- }
- else {
- throw new CacheException( e );
- }
- }
- }
+ @Override
+ public void put(Object key, Object value) throws CacheException {
+ LOG.debugf( "key: %s value: %s", key, value );
+ try {
+ final Element element = new Element( key, value );
+ getCache().put( element );
+ }
+ catch (IllegalArgumentException e) {
+ throw new CacheException( e );
+ }
+ catch (IllegalStateException e) {
+ throw new CacheException( e );
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ if ( e instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) e );
+ }
+ else {
+ throw new CacheException( e );
+ }
+ }
+ }
- /**
- * {@inheritDoc}
- */
- public void put(Object key, Object value) throws CacheException {
- LOG.debugf( "key: %s value: %s", key, value );
- try {
- Element element = new Element( key, value );
- cache.put( element );
- }
- catch ( IllegalArgumentException e ) {
- throw new CacheException( e );
- }
- catch ( IllegalStateException e ) {
- throw new CacheException( e );
- }
- catch ( net.sf.ehcache.CacheException e ) {
- if ( e instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) e );
- }
- else {
- throw new CacheException( e );
- }
- }
- }
+ @Override
+ public void evict(Object key) throws CacheException {
+ try {
+ getCache().remove( key );
+ }
+ catch (ClassCastException e) {
+ throw new CacheException( e );
+ }
+ catch (IllegalStateException e) {
+ throw new CacheException( e );
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ if ( e instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) e );
+ }
+ else {
+ throw new CacheException( e );
+ }
+ }
+ }
- /**
- * {@inheritDoc}
- */
- public void evict(Object key) throws CacheException {
- try {
- cache.remove( key );
- }
- catch ( ClassCastException e ) {
- throw new CacheException( e );
- }
- catch ( IllegalStateException e ) {
- throw new CacheException( e );
- }
- catch ( net.sf.ehcache.CacheException e ) {
- if ( e instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) e );
- }
- else {
- throw new CacheException( e );
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void evictAll() throws CacheException {
- try {
- cache.removeAll();
- }
- catch ( IllegalStateException e ) {
- throw new CacheException( e );
- }
- catch ( net.sf.ehcache.CacheException e ) {
- if ( e instanceof NonStopCacheException ) {
- HibernateNonstopCacheExceptionHandler.getInstance()
- .handleNonstopCacheException( (NonStopCacheException) e );
- }
- else {
- throw new CacheException( e );
- }
- }
- }
+ @Override
+ public void evictAll() throws CacheException {
+ try {
+ getCache().removeAll();
+ }
+ catch (IllegalStateException e) {
+ throw new CacheException( e );
+ }
+ catch (net.sf.ehcache.CacheException e) {
+ if ( e instanceof NonStopCacheException ) {
+ HibernateNonstopCacheExceptionHandler.getInstance()
+ .handleNonstopCacheException( (NonStopCacheException) e );
+ }
+ else {
+ throw new CacheException( e );
+ }
+ }
+ }
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheNaturalIdRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheNaturalIdRegion.java
index 75d0f20e2f..6a20ea1795 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheNaturalIdRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheNaturalIdRegion.java
@@ -34,7 +34,6 @@ import org.hibernate.cache.spi.CacheDataDescription;
import org.hibernate.cache.spi.NaturalIdRegion;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy;
-import org.hibernate.cfg.Settings;
/**
* A collection region specific wrapper around an Ehcache instance.
@@ -48,7 +47,6 @@ import org.hibernate.cfg.Settings;
*/
public class EhcacheNaturalIdRegion extends EhcacheTransactionalDataRegion implements NaturalIdRegion {
-
/**
* Constructs an EhcacheNaturalIdRegion around the given underlying cache.
*
@@ -61,6 +59,6 @@ public class EhcacheNaturalIdRegion extends EhcacheTransactionalDataRegion imple
@Override
public NaturalIdRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
- return accessStrategyFactory.createNaturalIdRegionAccessStrategy( this, accessType );
+ return getAccessStrategyFactory().createNaturalIdRegionAccessStrategy( this, accessType );
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheQueryResultsRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheQueryResultsRegion.java
index f7952f98db..5305af419a 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheQueryResultsRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheQueryResultsRegion.java
@@ -37,14 +37,18 @@ import org.hibernate.cache.spi.QueryResultsRegion;
* @author Alex Snaps
*/
public class EhcacheQueryResultsRegion extends EhcacheGeneralDataRegion implements QueryResultsRegion {
-
/**
* Constructs an EhcacheQueryResultsRegion around the given underlying cache.
*
- * @param accessStrategyFactory
+ * @param accessStrategyFactory The factory for building needed CollectionRegionAccessStrategy instance
+ * @param underlyingCache The ehcache cache instance
+ * @param properties Any additional[ properties
*/
- public EhcacheQueryResultsRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Properties properties) {
+ public EhcacheQueryResultsRegion(
+ EhcacheAccessStrategyFactory accessStrategyFactory,
+ Ehcache underlyingCache,
+ Properties properties) {
super( accessStrategyFactory, underlyingCache, properties );
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTimestampsRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTimestampsRegion.java
index bbc87dfd00..cc3316853e 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTimestampsRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTimestampsRegion.java
@@ -38,13 +38,17 @@ import org.hibernate.cache.spi.TimestampsRegion;
* @author Alex Snaps
*/
public class EhcacheTimestampsRegion extends EhcacheGeneralDataRegion implements TimestampsRegion {
-
/**
* Constructs an EhcacheTimestampsRegion around the given underlying cache.
*
- * @param accessStrategyFactory
+ * @param accessStrategyFactory The factory for building needed CollectionRegionAccessStrategy instance
+ * @param underlyingCache The ehcache cache instance
+ * @param properties Any additional[ properties
*/
- public EhcacheTimestampsRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Properties properties) {
- super(accessStrategyFactory, underlyingCache, properties);
+ public EhcacheTimestampsRegion(
+ EhcacheAccessStrategyFactory accessStrategyFactory,
+ Ehcache underlyingCache,
+ Properties properties) {
+ super( accessStrategyFactory, underlyingCache, properties );
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTransactionalDataRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTransactionalDataRegion.java
index b340120777..eba56c094e 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTransactionalDataRegion.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTransactionalDataRegion.java
@@ -37,7 +37,6 @@ import org.hibernate.cache.ehcache.internal.nonstop.HibernateNonstopCacheExcepti
import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory;
import org.hibernate.cache.spi.CacheDataDescription;
import org.hibernate.cache.spi.TransactionalDataRegion;
-import org.hibernate.cfg.Settings;
/**
* An Ehcache specific TransactionalDataRegion.
@@ -51,7 +50,6 @@ import org.hibernate.cfg.Settings;
* @author Alex Snaps
*/
public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements TransactionalDataRegion {
-
private static final int LOCAL_LOCK_PROVIDER_CONCURRENCY = 128;
protected final boolean isMinimalPutsEnabled;
@@ -62,6 +60,7 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
protected final CacheDataDescription metadata;
private final CacheLockProvider lockProvider;
+ private final boolean locksAreIndependentOfCache;
/**
* Construct an transactional Hibernate cache region around the given Ehcache instance.
@@ -72,39 +71,40 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
this.isMinimalPutsEnabled = isMinimalPutsEnabled;
this.metadata = metadata;
- Object context = cache.getInternalContext();
+ final Object context = cache.getInternalContext();
if ( context instanceof CacheLockProvider ) {
this.lockProvider = (CacheLockProvider) context;
}
else {
this.lockProvider = new StripedReadWriteLockSync( LOCAL_LOCK_PROVIDER_CONCURRENCY );
}
+ this.locksAreIndependentOfCache = lockProvider instanceof StripedReadWriteLockSync;
}
public boolean isMinimalPutsEnabled(){
return isMinimalPutsEnabled;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean isTransactionAware() {
return false;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public CacheDataDescription getCacheDataDescription() {
return metadata;
}
/**
* Get the value mapped to this key, or null if no value is mapped to this key.
+ *
+ * @param key The cache key
+ *
+ * @return The cached data
*/
public final Object get(Object key) {
try {
- Element element = cache.get( key );
+ final Element element = getCache().get( key );
if ( element == null ) {
return null;
}
@@ -112,7 +112,7 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
return element.getObjectValue();
}
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -126,19 +126,24 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Map the given value to the given key, replacing any existing mapping for this key
+ *
+ * @param key The cache key
+ * @param value The data to cache
+ *
+ * @throws CacheException Indicates a problem accessing the cache
*/
public final void put(Object key, Object value) throws CacheException {
try {
- Element element = new Element( key, value );
- cache.put( element );
+ final Element element = new Element( key, value );
+ getCache().put( element );
}
- catch ( IllegalArgumentException e ) {
+ catch (IllegalArgumentException e) {
throw new CacheException( e );
}
- catch ( IllegalStateException e ) {
+ catch (IllegalStateException e) {
throw new CacheException( e );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -151,18 +156,22 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Remove the mapping for this key (if any exists).
+ *
+ * @param key The cache key
+ *
+ * @throws CacheException Indicates a problem accessing the cache
*/
public final void remove(Object key) throws CacheException {
try {
- cache.remove( key );
+ getCache().remove( key );
}
- catch ( ClassCastException e ) {
+ catch (ClassCastException e) {
throw new CacheException( e );
}
- catch ( IllegalStateException e ) {
+ catch (IllegalStateException e) {
throw new CacheException( e );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -175,15 +184,17 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Remove all mapping from this cache region.
+ *
+ * @throws CacheException Indicates a problem accessing the cache
*/
public final void clear() throws CacheException {
try {
- cache.removeAll();
+ getCache().removeAll();
}
- catch ( IllegalStateException e ) {
+ catch (IllegalStateException e) {
throw new CacheException( e );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -196,12 +207,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Attempts to write lock the mapping for the given key.
+ *
+ * @param key The cache key
+ *
+ * @throws CacheException Indicates a problem accessing the cache
*/
public final void writeLock(Object key) {
try {
lockProvider.getSyncForKey( key ).lock( LockType.WRITE );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -214,12 +229,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Attempts to write unlock the mapping for the given key.
+ *
+ * @param key The cache key
+ *
+ * @throws CacheException Indicates a problem accessing the cache
*/
public final void writeUnlock(Object key) {
try {
lockProvider.getSyncForKey( key ).unlock( LockType.WRITE );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -232,12 +251,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Attempts to read lock the mapping for the given key.
+ *
+ * @param key The cache key
+ *
+ * @throws CacheException Indicates a problem accessing the cache
*/
public final void readLock(Object key) {
try {
lockProvider.getSyncForKey( key ).lock( LockType.WRITE );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -250,12 +273,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
/**
* Attempts to read unlock the mapping for the given key.
+ *
+ * @param key The cache key
+ *
+ * @throws CacheException Indicates a problem accessing the cache
*/
public final void readUnlock(Object key) {
try {
lockProvider.getSyncForKey( key ).unlock( LockType.WRITE );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
if ( e instanceof NonStopCacheException ) {
HibernateNonstopCacheExceptionHandler.getInstance()
.handleNonstopCacheException( (NonStopCacheException) e );
@@ -271,8 +298,10 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements
*
* Independent locks are not locked by the cache when the cache is accessed directly. This means that for an independent lock
* lock holds taken through a region method will not block direct access to the cache via other means.
+ *
+ * @return true/false. See discussion above.
*/
public final boolean locksAreIndependentOfCache() {
- return lockProvider instanceof StripedReadWriteLockSync;
+ return locksAreIndependentOfCache;
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/package-info.java
new file mode 100644
index 0000000000..ff6247faea
--- /dev/null
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines {@link org.hibernate.cache.spi.RegionFactory} support for the Ehcache integration
+ */
+package org.hibernate.cache.ehcache.internal.regions;
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/AbstractEhcacheAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/AbstractEhcacheAccessStrategy.java
index cbc67bcdec..9df3dbbb36 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/AbstractEhcacheAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/AbstractEhcacheAccessStrategy.java
@@ -26,7 +26,6 @@ package org.hibernate.cache.ehcache.internal.strategy;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.ehcache.internal.regions.EhcacheTransactionalDataRegion;
import org.hibernate.cache.spi.access.SoftLock;
-import org.hibernate.cfg.Settings;
/**
* Ultimate superclass for all Ehcache specific Hibernate AccessStrategy implementations.
@@ -38,13 +37,17 @@ import org.hibernate.cfg.Settings;
*/
abstract class AbstractEhcacheAccessStrategy {
- /**
- * The wrapped Hibernate cache region.
- */
protected final T region;
/**
- * Create an access strategy wrapping the given region.
+ * The wrapped Hibernate cache region.
+ */
+ protected T region() {
+ return region;
+ }
+
+ /**
+ * The settings for this persistence unit.
*/
AbstractEhcacheAccessStrategy(T region) {
this.region = region;
@@ -79,6 +82,7 @@ abstract class AbstractEhcacheAccessStrategy timestamp;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) {
return version != null && versionComparator.compare( version, newVersion ) < 0;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Object getValue() {
return value;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean isUnlockable(SoftLock lock) {
return false;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Lock lock(long timeout, UUID uuid, long lockId) {
return new Lock( timeout, uuid, lockId, version );
}
@@ -320,16 +310,12 @@ abstract class AbstractReadWriteEhcacheAccessStrategy timeout ) {
// if timedout then allow write
@@ -345,23 +331,16 @@ abstract class AbstractReadWriteEhcacheAccessStrategy
* Since this is a non-strict read/write strategy item locking is not used.
*/
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
/**
+ * {@inheritDoc}
+ *
* Since this is a non-strict read/write strategy item locking is not used.
*/
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
- region.remove( key );
+ region().remove( key );
}
- /**
- * {@inheritDoc}
- */
@Override
public void remove(Object key) throws CacheException {
- region.remove( key );
+ region().remove( key );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheEntityRegionAccessStrategy.java
index f6b6b5626e..3853886604 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheEntityRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheEntityRegionAccessStrategy.java
@@ -42,90 +42,97 @@ public class NonStrictReadWriteEhcacheEntityRegionAccessStrategy
/**
* Create a non-strict read/write access strategy accessing the given collection region.
+ *
+ * @param region The wrapped region
+ * @param settings The Hibernate settings
*/
public NonStrictReadWriteEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region) {
super( region );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public EntityRegion getRegion() {
- return region;
+ return super.region();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
- return region.get( key );
+ return region().get( key );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
- if ( minimalPutOverride && region.contains( key ) ) {
+ if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
- region.put( key, value );
+ region().put( key, value );
return true;
}
}
/**
+ * {@inheritDoc}
+ *
* Since this is a non-strict read/write strategy item locking is not used.
*/
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
/**
+ * {@inheritDoc}
+ *
* Since this is a non-strict read/write strategy item locking is not used.
*/
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
- region.remove( key );
+ region().remove( key );
}
/**
+ * {@inheritDoc}
+ *
* Returns false since this is an asynchronous cache access strategy.
*/
+ @Override
public boolean insert(Object key, Object value, Object version) throws CacheException {
return false;
}
/**
+ * {@inheritDoc}
+ *
* Returns false since this is a non-strict read/write cache access strategy
*/
+ @Override
public boolean afterInsert(Object key, Object value, Object version) throws CacheException {
return false;
}
/**
+ * {@inheritDoc}
+ *
* Removes the entry since this is a non-strict read/write cache strategy.
*/
+ @Override
public boolean update(Object key, Object value, Object currentVersion, Object previousVersion)
throws CacheException {
remove( key );
return false;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock)
throws CacheException {
unlockItem( key, lock );
return false;
}
- /**
- * {@inheritDoc}
- */
@Override
public void remove(Object key) throws CacheException {
- region.remove( key );
+ region().remove( key );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy.java
index 28469366bc..5f1ae0b273 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy.java
@@ -42,88 +42,95 @@ public class NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy
/**
* Create a non-strict read/write access strategy accessing the given NaturalId region.
+ *
+ * @param region The wrapped region
+ * @param settings The Hibernate settings
*/
public NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region) {
super( region );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public NaturalIdRegion getRegion() {
- return region;
+ return region();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
- return region.get( key );
+ return region().get( key );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
- if ( minimalPutOverride && region.contains( key ) ) {
+ if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
- region.put( key, value );
+ region().put( key, value );
return true;
}
}
/**
+ * {@inheritDoc}
+ *
* Since this is a non-strict read/write strategy item locking is not used.
*/
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
/**
+ * {@inheritDoc}
+ *
* Since this is a non-strict read/write strategy item locking is not used.
*/
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
- region.remove( key );
+ region().remove( key );
}
/**
+ * {@inheritDoc}
+ *
* Returns false since this is an asynchronous cache access strategy.
*/
- public boolean insert(Object key, Object value ) throws CacheException {
- return false;
- }
-
- /**
- * Returns false since this is a non-strict read/write cache access strategy
- */
- public boolean afterInsert(Object key, Object value ) throws CacheException {
- return false;
- }
-
- /**
- * Removes the entry since this is a non-strict read/write cache strategy.
- */
- public boolean update(Object key, Object value ) throws CacheException {
- remove( key );
+ @Override
+ public boolean insert(Object key, Object value) throws CacheException {
return false;
}
/**
* {@inheritDoc}
+ *
+ * Returns false since this is a non-strict read/write cache access strategy
*/
+ @Override
+ public boolean afterInsert(Object key, Object value) throws CacheException {
+ return false;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * Removes the entry since this is a non-strict read/write cache strategy.
+ */
+ @Override
+ public boolean update(Object key, Object value) throws CacheException {
+ remove( key );
+ return false;
+ }
+
+ @Override
public boolean afterUpdate(Object key, Object value, SoftLock lock) throws CacheException {
unlockItem( key, lock );
return false;
}
- /**
- * {@inheritDoc}
- */
@Override
public void remove(Object key) throws CacheException {
- region.remove( key );
+ region().remove( key );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheCollectionRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheCollectionRegionAccessStrategy.java
index a92e8e6149..4a3c94c6c5 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheCollectionRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheCollectionRegionAccessStrategy.java
@@ -42,46 +42,47 @@ public class ReadOnlyEhcacheCollectionRegionAccessStrategy
/**
* Create a read-only access strategy accessing the given collection region.
+ *
+ * @param region The wrapped region
+ * @param settings The Hibernate settings
*/
public ReadOnlyEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region) {
super( region );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public CollectionRegion getRegion() {
- return region;
+ return region();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
- return region.get( key );
+ return region().get( key );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
- if ( minimalPutOverride && region.contains( key ) ) {
+ if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
- region.put( key, value );
+ region().put( key, value );
return true;
}
}
+ @Override
public SoftLock lockItem(Object key, Object version) throws UnsupportedOperationException {
return null;
}
/**
+ * {@inheritDoc}
+ *
* A no-op since this cache is read-only
*/
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java
index 6f8dc3b2fe..b3dd3e8770 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java
@@ -30,10 +30,6 @@ import org.hibernate.cache.spi.access.EntityRegionAccessStrategy;
import org.hibernate.cache.spi.access.SoftLock;
import org.hibernate.cfg.Settings;
-/**
- * @author Alex Snaps
- */
-
/**
* Ehcache specific read-only entity region access strategy
*
@@ -45,82 +41,90 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc
/**
* Create a read-only access strategy accessing the given entity region.
+ *
+ * @param region The wrapped region
+ * @param settings The Hibernate settings
*/
public ReadOnlyEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region) {
super( region );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public EntityRegion getRegion() {
- return region;
+ return region();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
- return region.get( key );
+ return region().get( key );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
- if ( minimalPutOverride && region.contains( key ) ) {
+ if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
- region.put( key, value );
+ region().put( key, value );
return true;
}
}
+ @Override
public SoftLock lockItem(Object key, Object version) throws UnsupportedOperationException {
return null;
}
/**
+ * {@inheritDoc}
+ *
* A no-op since this cache is read-only
*/
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
evict( key );
}
/**
+ * {@inheritDoc}
+ *
* This cache is asynchronous hence a no-op
*/
+ @Override
public boolean insert(Object key, Object value, Object version) throws CacheException {
return false;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean afterInsert(Object key, Object value, Object version) throws CacheException {
- region.put( key, value );
+ region().put( key, value );
return true;
}
/**
+ * {@inheritDoc}
+ *
* Throws UnsupportedOperationException since this cache is read-only
*
* @throws UnsupportedOperationException always
*/
+ @Override
public boolean update(Object key, Object value, Object currentVersion, Object previousVersion)
throws UnsupportedOperationException {
throw new UnsupportedOperationException( "Can't write to a readonly object" );
}
/**
+ * {@inheritDoc}
+ *
* Throws UnsupportedOperationException since this cache is read-only
*
* @throws UnsupportedOperationException always
*/
+ @Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock)
throws UnsupportedOperationException {
throw new UnsupportedOperationException( "Can't write to a readonly object" );
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheNaturalIdRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheNaturalIdRegionAccessStrategy.java
index 1af1a15d42..16d44ab7e4 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheNaturalIdRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheNaturalIdRegionAccessStrategy.java
@@ -42,79 +42,87 @@ public class ReadOnlyEhcacheNaturalIdRegionAccessStrategy
/**
* Create a read-only access strategy accessing the given NaturalId region.
+ *
+ * @param region THe wrapped region
+ * @param settings The Hibermate settings
*/
public ReadOnlyEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region) {
super( region );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public NaturalIdRegion getRegion() {
- return region;
+ return region();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
- return region.get( key );
+ return region().get( key );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
- if ( minimalPutOverride && region.contains( key ) ) {
+ if ( minimalPutOverride && region().contains( key ) ) {
return false;
}
else {
- region.put( key, value );
+ region().put( key, value );
return true;
}
}
+ @Override
public SoftLock lockItem(Object key, Object version) throws UnsupportedOperationException {
return null;
}
/**
+ * {@inheritDoc}
+ *
* A no-op since this cache is read-only
*/
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
- region.remove( key );
- }
-
- /**
- * This cache is asynchronous hence a no-op
- */
- public boolean insert(Object key, Object value ) throws CacheException {
- return false;
+ region().remove( key );
}
/**
* {@inheritDoc}
+ *
+ * This cache is asynchronous hence a no-op
*/
- public boolean afterInsert(Object key, Object value ) throws CacheException {
- region.put( key, value );
+ @Override
+ public boolean insert(Object key, Object value) throws CacheException {
+ return false;
+ }
+
+ @Override
+ public boolean afterInsert(Object key, Object value) throws CacheException {
+ region().put( key, value );
return true;
}
/**
+ * {@inheritDoc}
+ *
* Throws UnsupportedOperationException since this cache is read-only
*
* @throws UnsupportedOperationException always
*/
- public boolean update(Object key, Object value ) throws UnsupportedOperationException {
+ @Override
+ public boolean update(Object key, Object value) throws UnsupportedOperationException {
throw new UnsupportedOperationException( "Can't write to a readonly object" );
}
/**
+ * {@inheritDoc}
+ *
* Throws UnsupportedOperationException since this cache is read-only
*
* @throws UnsupportedOperationException always
*/
+ @Override
public boolean afterUpdate(Object key, Object value, SoftLock lock) throws UnsupportedOperationException {
throw new UnsupportedOperationException( "Can't write to a readonly object" );
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheCollectionRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheCollectionRegionAccessStrategy.java
index 70a943d230..b57005b7d7 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheCollectionRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheCollectionRegionAccessStrategy.java
@@ -40,15 +40,16 @@ public class ReadWriteEhcacheCollectionRegionAccessStrategy
/**
* Create a read/write access strategy accessing the given collection region.
+ *
+ * @param region The wrapped region
+ * @param settings The Hibernate settings
*/
public ReadWriteEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region) {
super( region );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public CollectionRegion getRegion() {
- return region;
+ return region();
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java
index 4fd96f2df9..8873b8b514 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java
@@ -42,21 +42,25 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
/**
* Create a read/write access strategy accessing the given entity region.
+ *
+ * @param region The wrapped region
+ * @param settings The Hibernate settings
*/
public ReadWriteEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region) {
super( region );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public EntityRegion getRegion() {
- return region;
+ return region();
}
/**
+ * {@inheritDoc}
+ *
* A no-op since this is an asynchronous cache access strategy.
*/
+ @Override
public boolean insert(Object key, Object value, Object version) throws CacheException {
return false;
}
@@ -66,12 +70,13 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
*
* Inserts will only succeed if there is no existing value mapped to this key.
*/
+ @Override
public boolean afterInsert(Object key, Object value, Object version) throws CacheException {
- region.writeLock( key );
+ region().writeLock( key );
try {
- Lockable item = (Lockable) region.get( key );
+ final Lockable item = (Lockable) region().get( key );
if ( item == null ) {
- region.put( key, new Item( value, version, region.nextTimestamp() ) );
+ region().put( key, new Item( value, version, region().nextTimestamp() ) );
return true;
}
else {
@@ -79,13 +84,16 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
}
}
finally {
- region.writeUnlock( key );
+ region().writeUnlock( key );
}
}
/**
+ * {@inheritDoc}
+ *
* A no-op since this is an asynchronous cache access strategy.
*/
+ @Override
public boolean update(Object key, Object value, Object currentVersion, Object previousVersion)
throws CacheException {
return false;
@@ -98,21 +106,22 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
* duration of this transaction. It is important to also note that updates will fail if the soft-lock expired during
* the course of this transaction.
*/
+ @Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock)
throws CacheException {
//what should we do with previousVersion here?
- region.writeLock( key );
+ region().writeLock( key );
try {
- Lockable item = (Lockable) region.get( key );
+ final Lockable item = (Lockable) region().get( key );
if ( item != null && item.isUnlockable( lock ) ) {
- Lock lockItem = (Lock) item;
+ final Lock lockItem = (Lock) item;
if ( lockItem.wasLockedConcurrently() ) {
decrementLock( key, lockItem );
return false;
}
else {
- region.put( key, new Item( value, currentVersion, region.nextTimestamp() ) );
+ region().put( key, new Item( value, currentVersion, region().nextTimestamp() ) );
return true;
}
}
@@ -122,7 +131,7 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy
}
}
finally {
- region.writeUnlock( key );
+ region().writeUnlock( key );
}
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheNaturalIdRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheNaturalIdRegionAccessStrategy.java
index d32f8ec540..e81522a1f0 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheNaturalIdRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheNaturalIdRegionAccessStrategy.java
@@ -42,22 +42,26 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
/**
* Create a read/write access strategy accessing the given NaturalId region.
+ *
+ * @param region The wrapped region
+ * @param settings The Hibernate settings
*/
public ReadWriteEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region) {
super( region );
}
- /**
- * {@inheritDoc}
- */
+ @Override
public NaturalIdRegion getRegion() {
- return region;
+ return region();
}
/**
+ * {@inheritDoc}
+ *
* A no-op since this is an asynchronous cache access strategy.
*/
- public boolean insert(Object key, Object value ) throws CacheException {
+ @Override
+ public boolean insert(Object key, Object value) throws CacheException {
return false;
}
@@ -66,12 +70,13 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
*
* Inserts will only succeed if there is no existing value mapped to this key.
*/
- public boolean afterInsert(Object key, Object value ) throws CacheException {
- region.writeLock( key );
+ @Override
+ public boolean afterInsert(Object key, Object value) throws CacheException {
+ region().writeLock( key );
try {
- Lockable item = (Lockable) region.get( key );
+ final Lockable item = (Lockable) region().get( key );
if ( item == null ) {
- region.put( key, new Item( value, null, region.nextTimestamp() ) );
+ region().put( key, new Item( value, null, region().nextTimestamp() ) );
return true;
}
else {
@@ -79,15 +84,17 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
}
}
finally {
- region.writeUnlock( key );
+ region().writeUnlock( key );
}
}
/**
+ * {@inheritDoc}
+ *
* A no-op since this is an asynchronous cache access strategy.
*/
- public boolean update(Object key, Object value )
- throws CacheException {
+ @Override
+ public boolean update(Object key, Object value) throws CacheException {
return false;
}
@@ -98,20 +105,21 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
* duration of this transaction. It is important to also note that updates will fail if the soft-lock expired during
* the course of this transaction.
*/
+ @Override
public boolean afterUpdate(Object key, Object value, SoftLock lock) throws CacheException {
//what should we do with previousVersion here?
- region.writeLock( key );
+ region().writeLock( key );
try {
- Lockable item = (Lockable) region.get( key );
+ final Lockable item = (Lockable) region().get( key );
if ( item != null && item.isUnlockable( lock ) ) {
- Lock lockItem = (Lock) item;
+ final Lock lockItem = (Lock) item;
if ( lockItem.wasLockedConcurrently() ) {
decrementLock( key, lockItem );
return false;
}
else {
- region.put( key, new Item( value, null, region.nextTimestamp() ) );
+ region().put( key, new Item( value, null, region().nextTimestamp() ) );
return true;
}
}
@@ -121,7 +129,7 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy
}
}
finally {
- region.writeUnlock( key );
+ region().writeUnlock( key );
}
}
-}
\ No newline at end of file
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheCollectionRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheCollectionRegionAccessStrategy.java
index 34a3a5b508..c922c20cac 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheCollectionRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheCollectionRegionAccessStrategy.java
@@ -31,7 +31,6 @@ import org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion;
import org.hibernate.cache.spi.CollectionRegion;
import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy;
import org.hibernate.cache.spi.access.SoftLock;
-import org.hibernate.cfg.Settings;
/**
* JTA CollectionRegionAccessStrategy.
@@ -57,39 +56,34 @@ public class TransactionalEhcacheCollectionRegionAccessStrategy
this.ehcache = ehcache;
}
-
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
- Element element = ehcache.get( key );
+ final Element element = ehcache.get( key );
return element == null ? null : element.getObjectValue();
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public CollectionRegion getRegion() {
- return region;
+ return region();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
- /**
- * {@inheritDoc}
- */
- public boolean putFromLoad(Object key, Object value, long txTimestamp,
- Object version, boolean minimalPutOverride) throws CacheException {
+ @Override
+ public boolean putFromLoad(
+ Object key,
+ Object value,
+ long txTimestamp,
+ Object version,
+ boolean minimalPutOverride) throws CacheException {
try {
if ( minimalPutOverride && ehcache.get( key ) != null ) {
return false;
@@ -98,27 +92,22 @@ public class TransactionalEhcacheCollectionRegionAccessStrategy
ehcache.put( new Element( key, value ) );
return true;
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
@Override
public void remove(Object key) throws CacheException {
try {
ehcache.remove( key );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
// no-op
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheEntityRegionAccessStrategy.java
index 72b375608c..8c4f3378ca 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheEntityRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheEntityRegionAccessStrategy.java
@@ -31,7 +31,6 @@ import org.hibernate.cache.ehcache.internal.regions.EhcacheEntityRegion;
import org.hibernate.cache.spi.EntityRegion;
import org.hibernate.cache.spi.access.EntityRegionAccessStrategy;
import org.hibernate.cache.spi.access.SoftLock;
-import org.hibernate.cfg.Settings;
/**
* JTA EntityRegionAccessStrategy.
@@ -56,43 +55,33 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca
this.ehcache = ehcache;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean afterInsert(Object key, Object value, Object version) {
return false;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) {
return false;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
- Element element = ehcache.get( key );
+ final Element element = ehcache.get( key );
return element == null ? null : element.getObjectValue();
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public EntityRegion getRegion() {
- return region;
+ return region();
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean insert(Object key, Object value, Object version)
throws CacheException {
//OptimisticCache? versioning?
@@ -100,23 +89,23 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca
ehcache.put( new Element( key, value ) );
return true;
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
- /**
- * {@inheritDoc}
- */
- public boolean putFromLoad(Object key, Object value, long txTimestamp,
- Object version, boolean minimalPutOverride) throws CacheException {
+ @Override
+ public boolean putFromLoad(
+ Object key,
+ Object value,
+ long txTimestamp,
+ Object version,
+ boolean minimalPutOverride) throws CacheException {
try {
if ( minimalPutOverride && ehcache.get( key ) != null ) {
return false;
@@ -125,41 +114,37 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca
ehcache.put( new Element( key, value ) );
return true;
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
@Override
public void remove(Object key) throws CacheException {
try {
ehcache.remove( key );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
// no-op
}
- /**
- * {@inheritDoc}
- */
- public boolean update(Object key, Object value, Object currentVersion,
- Object previousVersion) throws CacheException {
+ @Override
+ public boolean update(
+ Object key,
+ Object value,
+ Object currentVersion,
+ Object previousVersion) throws CacheException {
try {
ehcache.put( new Element( key, value ) );
return true;
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheNaturalIdRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheNaturalIdRegionAccessStrategy.java
index c1f29c2afd..b8e998a377 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheNaturalIdRegionAccessStrategy.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheNaturalIdRegionAccessStrategy.java
@@ -31,7 +31,6 @@ import org.hibernate.cache.ehcache.internal.regions.EhcacheNaturalIdRegion;
import org.hibernate.cache.spi.NaturalIdRegion;
import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy;
import org.hibernate.cache.spi.access.SoftLock;
-import org.hibernate.cfg.Settings;
/**
* JTA NaturalIdRegionAccessStrategy.
@@ -57,67 +56,56 @@ public class TransactionalEhcacheNaturalIdRegionAccessStrategy
this.ehcache = ehcache;
}
- /**
- * {@inheritDoc}
- */
- public boolean afterInsert(Object key, Object value ) {
+ @Override
+ public boolean afterInsert(Object key, Object value) {
return false;
}
- /**
- * {@inheritDoc}
- */
+ @Override
public boolean afterUpdate(Object key, Object value, SoftLock lock) {
return false;
}
-
- /**
- * {@inheritDoc}
- */
+ @Override
public Object get(Object key, long txTimestamp) throws CacheException {
try {
- Element element = ehcache.get( key );
+ final Element element = ehcache.get( key );
return element == null ? null : element.getObjectValue();
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public NaturalIdRegion getRegion() {
- return region;
+ return region();
}
- /**
- * {@inheritDoc}
- */
- public boolean insert(Object key, Object value ) throws CacheException {
+ @Override
+ public boolean insert(Object key, Object value) throws CacheException {
//OptimisticCache? versioning?
try {
ehcache.put( new Element( key, value ) );
return true;
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public SoftLock lockItem(Object key, Object version) throws CacheException {
return null;
}
- /**
- * {@inheritDoc}
- */
- public boolean putFromLoad(Object key, Object value, long txTimestamp,
- Object version, boolean minimalPutOverride) throws CacheException {
+ @Override
+ public boolean putFromLoad(
+ Object key,
+ Object value,
+ long txTimestamp,
+ Object version,
+ boolean minimalPutOverride) throws CacheException {
try {
if ( minimalPutOverride && ehcache.get( key ) != null ) {
return false;
@@ -126,40 +114,33 @@ public class TransactionalEhcacheNaturalIdRegionAccessStrategy
ehcache.put( new Element( key, value ) );
return true;
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
@Override
public void remove(Object key) throws CacheException {
try {
ehcache.remove( key );
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
- /**
- * {@inheritDoc}
- */
+ @Override
public void unlockItem(Object key, SoftLock lock) throws CacheException {
// no-op
}
- /**
- * {@inheritDoc}
- */
- public boolean update(Object key, Object value ) throws CacheException {
+ @Override
+ public boolean update(Object key, Object value) throws CacheException {
try {
ehcache.put( new Element( key, value ) );
return true;
}
- catch ( net.sf.ehcache.CacheException e ) {
+ catch (net.sf.ehcache.CacheException e) {
throw new CacheException( e );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/package-info.java
new file mode 100644
index 0000000000..f055c0e74d
--- /dev/null
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines {@link org.hibernate.cache.spi.access.RegionAccessStrategy} support for the Ehcache integration
+ */
+package org.hibernate.cache.ehcache.internal.strategy;
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateEhcacheUtils.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateEhcacheUtils.java
new file mode 100644
index 0000000000..6167af991e
--- /dev/null
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateEhcacheUtils.java
@@ -0,0 +1,129 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2011, Red Hat Inc. 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 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.cache.ehcache.internal.util;
+
+import java.net.URL;
+
+import net.sf.ehcache.Ehcache;
+import net.sf.ehcache.config.CacheConfiguration;
+import net.sf.ehcache.config.Configuration;
+import net.sf.ehcache.config.ConfigurationFactory;
+import net.sf.ehcache.config.NonstopConfiguration;
+import net.sf.ehcache.config.TerracottaConfiguration;
+import net.sf.ehcache.config.TerracottaConfiguration.ValueMode;
+import net.sf.ehcache.config.TimeoutBehaviorConfiguration.TimeoutBehaviorType;
+
+import org.jboss.logging.Logger;
+
+import org.hibernate.cache.CacheException;
+import org.hibernate.cache.ehcache.EhCacheMessageLogger;
+
+
+/**
+ * Copy of Ehcache utils into Hibernate code base
+ *
+ * @author Chris Dennis
+ * @author Abhishek Sanoujam
+ * @author Alex Snaps
+ */
+public final class HibernateEhcacheUtils {
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ HibernateEhcacheUtils.class.getName()
+ );
+
+ private HibernateEhcacheUtils() {
+ }
+
+ /**
+ * Create a cache manager configuration from the supplied url, correcting it for Hibernate compatibility.
+ *
+ * Currently "correcting" for Hibernate compatibility means simply switching any identity based value modes
+ * to serialization.
+ *
+ * @param url The url to load the config from
+ *
+ * @return The Ehcache Configuration object
+ */
+ public static Configuration loadAndCorrectConfiguration(URL url) {
+ final Configuration config = ConfigurationFactory.parseConfiguration( url );
+ if ( config.getDefaultCacheConfiguration().isTerracottaClustered() ) {
+ if ( ValueMode.IDENTITY
+ .equals( config.getDefaultCacheConfiguration().getTerracottaConfiguration().getValueMode() ) ) {
+ LOG.incompatibleCacheValueMode();
+ config.getDefaultCacheConfiguration()
+ .getTerracottaConfiguration()
+ .setValueMode( ValueMode.SERIALIZATION.name() );
+ }
+ setupHibernateTimeoutBehavior(
+ config.getDefaultCacheConfiguration()
+ .getTerracottaConfiguration()
+ .getNonstopConfiguration()
+ );
+ }
+
+ for ( CacheConfiguration cacheConfig : config.getCacheConfigurations().values() ) {
+ if ( cacheConfig.isTerracottaClustered() ) {
+ if ( ValueMode.IDENTITY.equals( cacheConfig.getTerracottaConfiguration().getValueMode() ) ) {
+ LOG.incompatibleCacheValueModePerCache( cacheConfig.getName() );
+ cacheConfig.getTerracottaConfiguration().setValueMode( ValueMode.SERIALIZATION.name() );
+ }
+ setupHibernateTimeoutBehavior( cacheConfig.getTerracottaConfiguration().getNonstopConfiguration() );
+ }
+ }
+ return config;
+ }
+
+ private static void setupHibernateTimeoutBehavior(NonstopConfiguration nonstopConfig) {
+ nonstopConfig.getTimeoutBehavior().setType( TimeoutBehaviorType.EXCEPTION.getTypeName() );
+ }
+
+ /**
+ * Validates that the supplied Ehcache instance is valid for use as a Hibernate cache.
+ *
+ * @param cache The cache instance
+ *
+ * @throws CacheException If any explicit settings on the cache are not validate
+ */
+ public static void validateEhcache(Ehcache cache) throws CacheException {
+ final CacheConfiguration cacheConfig = cache.getCacheConfiguration();
+
+ if ( cacheConfig.isTerracottaClustered() ) {
+ final TerracottaConfiguration tcConfig = cacheConfig.getTerracottaConfiguration();
+ switch ( tcConfig.getValueMode() ) {
+ case IDENTITY: {
+ throw new CacheException(
+ "The clustered Hibernate cache " + cache.getName() + " is using IDENTITY value mode.\n"
+ + "Identity value mode cannot be used with Hibernate cache regions."
+ );
+ }
+ case SERIALIZATION:
+ default: {
+ // this is the recommended valueMode
+ break;
+ }
+ }
+ }
+ }
+}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateUtil.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateUtil.java
deleted file mode 100644
index 7d66b8820d..0000000000
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateUtil.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2011, Red Hat Inc. 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 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.cache.ehcache.internal.util;
-
-import java.net.URL;
-
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.ConfigurationFactory;
-import net.sf.ehcache.config.NonstopConfiguration;
-import net.sf.ehcache.config.TerracottaConfiguration;
-import net.sf.ehcache.config.TerracottaConfiguration.ValueMode;
-import net.sf.ehcache.config.TimeoutBehaviorConfiguration.TimeoutBehaviorType;
-import org.jboss.logging.Logger;
-
-import org.hibernate.cache.CacheException;
-import org.hibernate.cache.ehcache.EhCacheMessageLogger;
-
-
-/**
- * @author Chris Dennis
- * @author Abhishek Sanoujam
- * @author Alex Snaps
- */
-public final class HibernateUtil {
-
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- HibernateUtil.class.getName()
- );
-
- private HibernateUtil() {
- }
-
- /**
- * Create a cache manager configuration from the supplied url, correcting it for Hibernate compatibility.
- *
- * Currently correcting for Hibernate compatibility means simply switching any identity based value modes to serialization.
- */
- public static Configuration loadAndCorrectConfiguration(URL url) {
- Configuration config = ConfigurationFactory.parseConfiguration( url );
- if ( config.getDefaultCacheConfiguration().isTerracottaClustered() ) {
- if ( ValueMode.IDENTITY
- .equals( config.getDefaultCacheConfiguration().getTerracottaConfiguration().getValueMode() ) ) {
- LOG.incompatibleCacheValueMode();
- config.getDefaultCacheConfiguration()
- .getTerracottaConfiguration()
- .setValueMode( ValueMode.SERIALIZATION.name() );
- }
- setupHibernateTimeoutBehavior(
- config.getDefaultCacheConfiguration()
- .getTerracottaConfiguration()
- .getNonstopConfiguration()
- );
- }
-
- for ( CacheConfiguration cacheConfig : config.getCacheConfigurations().values() ) {
- if ( cacheConfig.isTerracottaClustered() ) {
- if ( ValueMode.IDENTITY.equals( cacheConfig.getTerracottaConfiguration().getValueMode() ) ) {
- LOG.incompatibleCacheValueModePerCache( cacheConfig.getName() );
- cacheConfig.getTerracottaConfiguration().setValueMode( ValueMode.SERIALIZATION.name() );
- }
- setupHibernateTimeoutBehavior( cacheConfig.getTerracottaConfiguration().getNonstopConfiguration() );
- }
- }
- return config;
- }
-
- private static void setupHibernateTimeoutBehavior(NonstopConfiguration nonstopConfig) {
- nonstopConfig.getTimeoutBehavior().setType( TimeoutBehaviorType.EXCEPTION.getTypeName() );
- }
-
- /**
- * Validates that the supplied Ehcache instance is valid for use as a Hibernate cache.
- */
- public static void validateEhcache(Ehcache cache) throws CacheException {
- CacheConfiguration cacheConfig = cache.getCacheConfiguration();
-
- if ( cacheConfig.isTerracottaClustered() ) {
- TerracottaConfiguration tcConfig = cacheConfig.getTerracottaConfiguration();
- switch ( tcConfig.getValueMode() ) {
- case IDENTITY:
- throw new CacheException(
- "The clustered Hibernate cache " + cache.getName() + " is using IDENTITY value mode.\n"
- + "Identity value mode cannot be used with Hibernate cache regions."
- );
- case SERIALIZATION:
- default:
- // this is the recommended valueMode
- break;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/package-info.java
new file mode 100644
index 0000000000..5c6a04407f
--- /dev/null
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines utilities used by the Ehcache integration
+ */
+package org.hibernate.cache.ehcache.internal.util;
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BaseEmitterBean.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java
similarity index 69%
rename from hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BaseEmitterBean.java
rename to hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java
index 2c6a6d27f5..5d3f3abc31 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BaseEmitterBean.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java
@@ -24,9 +24,6 @@
package org.hibernate.cache.ehcache.management.impl;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.atomic.AtomicLong;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
@@ -36,64 +33,61 @@ import javax.management.NotificationEmitter;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.StandardMBean;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicLong;
/**
+ * Base MBean impl
+ *
* @author gkeim
*/
-public abstract class BaseEmitterBean extends StandardMBean implements NotificationEmitter {
- /**
- * emitter
- */
- protected final Emitter emitter = new Emitter();
-
- /**
- * sequenceNumber
- */
- protected final AtomicLong sequenceNumber = new AtomicLong();
-
+public abstract class AbstractEmitterBean extends StandardMBean implements NotificationEmitter {
+ private final Emitter emitter = new Emitter();
+ private final AtomicLong sequenceNumber = new AtomicLong();
private final List notificationListeners = new CopyOnWriteArrayList();
/**
- * BaseEmitterBean
+ * Constructs a AbstractEmitterBean
*
- * @param
- * @param mbeanInterface
+ * @param mbeanInterface The MBean contract
+ * @param Not used as far as I can see
*
- * @throws javax.management.NotCompliantMBeanException
+ * @throws javax.management.NotCompliantMBeanException thrown from JMX super ctor
*/
- protected BaseEmitterBean(Class mbeanInterface) throws NotCompliantMBeanException {
+ protected AbstractEmitterBean(Class mbeanInterface) throws NotCompliantMBeanException {
super( mbeanInterface );
}
/**
- * sendNotification
+ * Sends notification of an event
*
- * @param eventType
+ * @param eventType The type of event
*/
public void sendNotification(String eventType) {
sendNotification( eventType, null, null );
}
/**
- * sendNotification
+ * Sends notification of an event
*
- * @param eventType
- * @param data
+ * @param eventType The type of event
+ * @param data The event data
*/
public void sendNotification(String eventType, Object data) {
sendNotification( eventType, data, null );
}
/**
- * sendNotification
+ * Sends notification of an event
*
- * @param eventType
- * @param data
- * @param msg
+ * @param eventType The type of event
+ * @param data The event data
+ * @param msg A message
*/
public void sendNotification(String eventType, Object data, String msg) {
- Notification notif = new Notification(
+ final Notification notification = new Notification(
eventType,
this,
sequenceNumber.incrementAndGet(),
@@ -101,9 +95,9 @@ public abstract class BaseEmitterBean extends StandardMBean implements Notificat
msg
);
if ( data != null ) {
- notif.setUserData( data );
+ notification.setUserData( data );
}
- emitter.sendNotification( notif );
+ emitter.sendNotification( notification );
}
/**
@@ -119,61 +113,42 @@ public abstract class BaseEmitterBean extends StandardMBean implements Notificat
*/
protected abstract void doDispose();
- /**
- * @author gkeim
- */
private class Emitter extends NotificationBroadcasterSupport {
- /**
- * @see javax.management.NotificationBroadcasterSupport#getNotificationInfo()
- */
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
- return BaseEmitterBean.this.getNotificationInfo();
+ return AbstractEmitterBean.this.getNotificationInfo();
}
}
- /**
- * @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener,
- * javax.management.NotificationFilter, java.lang.Object)
- */
+ @Override
public void addNotificationListener(NotificationListener notif, NotificationFilter filter, Object callBack) {
emitter.addNotificationListener( notif, filter, callBack );
notificationListeners.add( notif );
}
- /**
- * remove all added notification listeners
- */
private void removeAllNotificationListeners() {
for ( NotificationListener listener : notificationListeners ) {
try {
emitter.removeNotificationListener( listener );
}
- catch ( ListenerNotFoundException e ) {
+ catch (ListenerNotFoundException e) {
// ignore
}
}
notificationListeners.clear();
}
- /**
- * @see javax.management.NotificationBroadcaster#getNotificationInfo()
- */
+ @Override
public abstract MBeanNotificationInfo[] getNotificationInfo();
- /**
- * @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener)
- */
+ @Override
public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
emitter.removeNotificationListener( listener );
notificationListeners.remove( listener );
}
- /**
- * @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener,
- * javax.management.NotificationFilter, java.lang.Object)
- */
+ @Override
public void removeNotificationListener(NotificationListener notif, NotificationFilter filter, Object callBack)
throws ListenerNotFoundException {
emitter.removeNotificationListener( notif, filter, callBack );
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BeanUtils.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BeanUtils.java
index 1352c0fbfc..afcd716ae7 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BeanUtils.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BeanUtils.java
@@ -36,17 +36,17 @@ public class BeanUtils {
/**
* Return the named getter method on the bean or null if not found.
*
- * @param bean
- * @param propertyName
+ * @param bean The bean
+ * @param propertyName The property to get the getter for
*
* @return the named getter method
*/
private static Method getMethod(Object bean, String propertyName) {
- StringBuilder sb = new StringBuilder( "get" ).append( Character.toUpperCase( propertyName.charAt( 0 ) ) );
+ final StringBuilder sb = new StringBuilder( "get" ).append( Character.toUpperCase( propertyName.charAt( 0 ) ) );
if ( propertyName.length() > 1 ) {
sb.append( propertyName.substring( 1 ) );
}
- String getterName = sb.toString();
+ final String getterName = sb.toString();
for ( Method m : bean.getClass().getMethods() ) {
if ( getterName.equals( m.getName() ) && m.getParameterTypes().length == 0 ) {
return m;
@@ -55,14 +55,6 @@ public class BeanUtils {
return null;
}
- /**
- * Return the named field on the bean or null if not found.
- *
- * @param bean
- * @param propertyName
- *
- * @return the named field
- */
private static Field getField(Object bean, String propertyName) {
for ( Field f : bean.getClass().getDeclaredFields() ) {
if ( propertyName.equals( f.getName() ) ) {
@@ -87,8 +79,8 @@ public class BeanUtils {
/**
* Retrieve a named bean property value.
*
- * @param bean bean
- * @param propertyName
+ * @param bean The bean instance
+ * @param propertyName The name of the property whose value to extract
*
* @return the property value
*/
@@ -96,24 +88,24 @@ public class BeanUtils {
validateArgs( bean, propertyName );
// try getters first
- Method getter = getMethod( bean, propertyName );
+ final Method getter = getMethod( bean, propertyName );
if ( getter != null ) {
try {
return getter.invoke( bean );
}
- catch ( Exception e ) {
+ catch (Exception e) {
/**/
}
}
// then try fields
- Field field = getField( bean, propertyName );
+ final Field field = getField( bean, propertyName );
if ( field != null ) {
try {
field.setAccessible( true );
return field.get( bean );
}
- catch ( Exception e ) {
+ catch (Exception e) {
/**/
}
}
@@ -124,22 +116,25 @@ public class BeanUtils {
/**
* Retrieve a Long bean property value.
*
- * @param bean bean
- * @param propertyName
+ * @param bean The bean instance
+ * @param propertyName The name of the property whose value to extract
*
* @return long value
*
- * @throws NoSuchFieldException
+ * @throws NoSuchFieldException If the value is null (wow)
*/
public static long getLongBeanProperty(final Object bean, final String propertyName) throws NoSuchFieldException {
validateArgs( bean, propertyName );
- Object o = getBeanProperty( bean, propertyName );
+ final Object o = getBeanProperty( bean, propertyName );
if ( o == null ) {
throw new NoSuchFieldException( propertyName );
}
- else if ( !( o instanceof Number ) ) {
+ else if ( !(o instanceof Number) ) {
throw new IllegalArgumentException( propertyName + " not an Number" );
}
- return ( (Number) o ).longValue();
+ return ((Number) o).longValue();
+ }
+
+ private BeanUtils() {
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionStats.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionStats.java
index 677f217d1f..9f1264a56b 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionStats.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionStats.java
@@ -23,10 +23,6 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
@@ -36,10 +32,15 @@ import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
import org.hibernate.stat.SecondLevelCacheStatistics;
/**
+ * Bean for exposing region stats
+ *
* @author gkeim
*/
public class CacheRegionStats implements Serializable {
@@ -61,7 +62,7 @@ public class CacheRegionStats implements Serializable {
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Cache-region";
private static final String TABULAR_TYPE_DESCRIPTION = "All Cache Region Statistics";
- private static final String[] INDEX_NAMES = new String[] { "region", };
+ private static final String[] INDEX_NAMES = new String[] {"region",};
private static final TabularType TABULAR_TYPE;
static {
@@ -72,7 +73,7 @@ public class CacheRegionStats implements Serializable {
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
@@ -123,7 +124,9 @@ public class CacheRegionStats implements Serializable {
protected long elementCountTotal;
/**
- * @param region
+ * Construct a CacheRegionStats
+ *
+ * @param region The region name
*/
public CacheRegionStats(String region) {
this.region = region;
@@ -131,8 +134,10 @@ public class CacheRegionStats implements Serializable {
}
/**
- * @param region
- * @param src
+ * Construct a CacheRegionStats
+ *
+ * @param region The region name
+ * @param src The SecondLevelCacheStatistics reference
*/
public CacheRegionStats(String region, SecondLevelCacheStatistics src) {
this( region );
@@ -146,15 +151,18 @@ public class CacheRegionStats implements Serializable {
this.elementCountOnDisk = BeanUtils.getLongBeanProperty( src, "elementCountOnDisk" );
this.elementCountTotal = BeanUtils.getLongBeanProperty( src, "elementCountOnDisk" );
}
- catch ( Exception e ) {
+ catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
}
/**
- * @param cData
+ * Construct a CacheRegionStats
+ *
+ * @param cData No idea
*/
+ @SuppressWarnings("UnusedAssignment")
public CacheRegionStats(final CompositeData cData) {
int i = 0;
region = (String) cData.get( ITEM_NAMES[i++] );
@@ -168,30 +176,15 @@ public class CacheRegionStats implements Serializable {
elementCountTotal = (Long) cData.get( ITEM_NAMES[i++] );
}
- private static int safeParseInt(String s) {
- try {
- return Integer.parseInt( s );
- }
- catch ( Exception e ) {
- return -1;
- }
- }
-
- /**
- * @return hit ratio
- */
protected double determineHitRatio() {
+ final long readCount = getHitCount() + getMissCount();
double result = 0;
- long readCount = getHitCount() + getMissCount();
if ( readCount > 0 ) {
- result = getHitCount() / ( (double) readCount );
+ result = getHitCount() / ((double) readCount);
}
return result;
}
- /**
- * @see java.lang.Object#toString()
- */
@Override
public String toString() {
return "region=" + getRegion() + "shortName=" + getShortName() + ", hitCount=" + getHitCount() + ", missCount="
@@ -200,70 +193,45 @@ public class CacheRegionStats implements Serializable {
+ getElementCountTotal();
}
- /**
- * @return region name
- */
public String getRegion() {
return region;
}
- /**
- * @return short name
- */
public String getShortName() {
return shortName;
}
- /**
- * @return hit count
- */
public long getHitCount() {
return hitCount;
}
- /**
- * @return miss count
- */
public long getMissCount() {
return missCount;
}
- /**
- * @return put count
- */
public long getPutCount() {
return putCount;
}
- /**
- * @return hit ratio
- */
public double getHitRatio() {
return hitRatio;
}
- /**
- * @return in-memory element count
- */
public long getElementCountInMemory() {
return elementCountInMemory;
}
- /**
- * @return on-disk element count
- */
public long getElementCountOnDisk() {
return elementCountOnDisk;
}
- /**
- * @return total element count
- */
public long getElementCountTotal() {
return elementCountTotal;
}
/**
+ * Convert our state into a JMX CompositeData
+ *
* @return composite data
*/
public CompositeData toCompositeData() {
@@ -276,12 +244,14 @@ public class CacheRegionStats implements Serializable {
}
);
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
/**
+ * Convert our state into a JMX TabularData
+ *
* @return tabular data
*/
public static TabularData newTabularDataInstance() {
@@ -289,14 +259,17 @@ public class CacheRegionStats implements Serializable {
}
/**
- * @param tabularData
+ * Re-build the CacheRegionStats from JMX tabular data
+ *
+ * @param tabularData The JMX tabular data
*
* @return array of region statistics
*/
+ @SuppressWarnings("UnusedDeclaration")
public static CacheRegionStats[] fromTabularData(final TabularData tabularData) {
- final List countList = new ArrayList( tabularData.size() );
- for ( final Iterator pos = tabularData.values().iterator(); pos.hasNext(); ) {
- countList.add( new CacheRegionStats( (CompositeData) pos.next() ) );
+ final List countList = new ArrayList( tabularData.size() );
+ for ( Object o : tabularData.values() ) {
+ countList.add( new CacheRegionStats( (CompositeData) o ) );
}
return countList.toArray( new CacheRegionStats[countList.size()] );
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionUtils.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionUtils.java
index 023876fa68..267486a6a2 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionUtils.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionUtils.java
@@ -23,13 +23,14 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.awt.*;
+import java.awt.Color;
/**
* CacheRegionUtils
*
* @author gkeim
*/
+@SuppressWarnings("UnusedDeclaration")
public abstract class CacheRegionUtils {
/**
* HIT_COLOR
@@ -49,51 +50,53 @@ public abstract class CacheRegionUtils {
/**
* HIT_FILL_COLOR
*/
- public final static Color HIT_FILL_COLOR = CacheRegionUtils.HIT_COLOR.brighter().brighter().brighter();
+ public static final Color HIT_FILL_COLOR = CacheRegionUtils.HIT_COLOR.brighter().brighter().brighter();
/**
* MISS_FILL_COLOR
*/
- public final static Color MISS_FILL_COLOR = CacheRegionUtils.MISS_COLOR.brighter().brighter().brighter();
+ public static final Color MISS_FILL_COLOR = CacheRegionUtils.MISS_COLOR.brighter().brighter().brighter();
/**
* PUT_FILL_COLOR
*/
- public final static Color PUT_FILL_COLOR = CacheRegionUtils.PUT_COLOR.brighter().brighter().brighter();
+ public static final Color PUT_FILL_COLOR = CacheRegionUtils.PUT_COLOR.brighter().brighter().brighter();
/**
* HIT_DRAW_COLOR
*/
- public final static Color HIT_DRAW_COLOR = CacheRegionUtils.HIT_COLOR.darker();
+ public static final Color HIT_DRAW_COLOR = CacheRegionUtils.HIT_COLOR.darker();
/**
* MISS_DRAW_COLOR
*/
- public final static Color MISS_DRAW_COLOR = CacheRegionUtils.MISS_COLOR.darker();
+ public static final Color MISS_DRAW_COLOR = CacheRegionUtils.MISS_COLOR.darker();
/**
* PUT_DRAW_COLOR
*/
- public final static Color PUT_DRAW_COLOR = CacheRegionUtils.PUT_COLOR.darker();
+ public static final Color PUT_DRAW_COLOR = CacheRegionUtils.PUT_COLOR.darker();
/**
- * determineShortName
+ * Determine a short name from the full name
*
- * @param fullName
+ * @param fullName The full name
+ *
+ * @return The short name
*/
public static String determineShortName(String fullName) {
String result = fullName;
if ( fullName != null ) {
- String[] comps = fullName.split( "\\." );
+ final String[] comps = fullName.split( "\\." );
if ( comps.length == 1 ) {
return fullName;
}
boolean truncate = true;
for ( int i = 0; i < comps.length; i++ ) {
String comp = comps[i];
- char c = comp.charAt( 0 );
+ final char c = comp.charAt( 0 );
if ( truncate && Character.isUpperCase( c ) ) {
truncate = false;
}
@@ -108,16 +111,18 @@ public abstract class CacheRegionUtils {
}
/**
- * join
+ * Same as Hibernate internal {@link org.hibernate.internal.util.StringHelper#join} methods
*
- * @param elements
- * @param c
+ * @param elements The things to join
+ * @param c The separator between elements
+ *
+ * @return The joined string
*/
private static String join(String[] elements, char c) {
if ( elements == null ) {
return null;
}
- StringBuilder sb = new StringBuilder();
+ final StringBuilder sb = new StringBuilder();
for ( String s : elements ) {
sb.append( s ).append( c );
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CollectionStats.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CollectionStats.java
index a6eebe5280..667a3ab8b3 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CollectionStats.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CollectionStats.java
@@ -23,10 +23,6 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
@@ -36,6 +32,9 @@ import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
import org.hibernate.stat.CollectionStatistics;
@@ -62,7 +61,7 @@ public class CollectionStats implements Serializable {
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Collection";
private static final String TABULAR_TYPE_DESCRIPTION = "All Collection Statistics";
- private static final String[] INDEX_NAMES = new String[] { "roleName", };
+ private static final String[] INDEX_NAMES = new String[] {"roleName",};
private static final TabularType TABULAR_TYPE;
static {
@@ -73,7 +72,7 @@ public class CollectionStats implements Serializable {
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
@@ -115,19 +114,23 @@ public class CollectionStats implements Serializable {
/**
- * @param roleName
+ * Constructs a CollectionsStats
+ *
+ * @param role The collection role
*/
- public CollectionStats(String roleName) {
- this.roleName = roleName;
- this.shortName = CacheRegionUtils.determineShortName( roleName );
+ public CollectionStats(String role) {
+ this.roleName = role;
+ this.shortName = CacheRegionUtils.determineShortName( role );
}
/**
- * @param name
- * @param src
+ * Constructs a CollectionsStats
+ *
+ * @param role The collection role
+ * @param src The CollectionStatistics instance
*/
- public CollectionStats(String name, CollectionStatistics src) {
- this( name );
+ public CollectionStats(String role, CollectionStatistics src) {
+ this( role );
try {
this.loadCount = BeanUtils.getLongBeanProperty( src, "loadCount" );
@@ -136,15 +139,18 @@ public class CollectionStats implements Serializable {
this.removeCount = BeanUtils.getLongBeanProperty( src, "removeCount" );
this.recreateCount = BeanUtils.getLongBeanProperty( src, "recreateCount" );
}
- catch ( Exception e ) {
+ catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
}
/**
- * @param cData
+ * Constructs a CollectionsStats from a JMX CompositeData
+ *
+ * @param cData The JMX CompositeData
*/
+ @SuppressWarnings("UnusedAssignment")
public CollectionStats(final CompositeData cData) {
int i = 0;
roleName = (String) cData.get( ITEM_NAMES[i++] );
@@ -156,17 +162,10 @@ public class CollectionStats implements Serializable {
recreateCount = (Long) cData.get( ITEM_NAMES[i++] );
}
- private static int safeParseInt(String s) {
- try {
- return Integer.parseInt( s );
- }
- catch ( Exception e ) {
- return -1;
- }
- }
-
/**
- * @param stats
+ * Update the internal stats
+ *
+ * @param stats The incoming stats
*/
public void add(CollectionStats stats) {
loadCount += stats.getLoadCount();
@@ -176,9 +175,6 @@ public class CollectionStats implements Serializable {
recreateCount += stats.getRecreateCount();
}
- /**
- * toString
- */
@Override
public String toString() {
return "roleName=" + roleName + "shortName=" + shortName + ", loadCount=" + loadCount + ", fetchCount="
@@ -186,86 +182,75 @@ public class CollectionStats implements Serializable {
+ recreateCount;
}
- /**
- * getRoleName
- */
+ @SuppressWarnings("UnusedDeclaration")
public String getRoleName() {
return roleName;
}
- /**
- * getShortName
- */
+ @SuppressWarnings("UnusedDeclaration")
public String getShortName() {
return shortName;
}
- /**
- * getLoadCount
- */
public long getLoadCount() {
return loadCount;
}
- /**
- * getFetchCount
- */
public long getFetchCount() {
return fetchCount;
}
- /**
- * getUpdateCount
- */
public long getUpdateCount() {
return updateCount;
}
- /**
- * getRemoveCount
- */
public long getRemoveCount() {
return removeCount;
}
- /**
- * getRecreateCount
- */
public long getRecreateCount() {
return recreateCount;
}
/**
- * toCompositeData
+ * Builds a JMX CompositeData view of our state
+ *
+ * @return The JMX CompositeData
*/
public CompositeData toCompositeData() {
try {
return new CompositeDataSupport(
- COMPOSITE_TYPE, ITEM_NAMES, new Object[] {
- roleName, shortName, loadCount,
- fetchCount, updateCount, removeCount, recreateCount,
- }
+ COMPOSITE_TYPE,
+ ITEM_NAMES,
+ new Object[] { roleName, shortName, loadCount, fetchCount, updateCount, removeCount, recreateCount }
);
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
/**
- * newTabularDataInstance
+ * Builds a JMX TabularData
+ *
+ * @return JMX TabularData
*/
public static TabularData newTabularDataInstance() {
return new TabularDataSupport( TABULAR_TYPE );
}
/**
- * fromTabularData
+ * Re-builds CollectionStats from JMX TabularData
+ *
+ * @param tabularData The JMX TabularData
+ *
+ * @return The CollectionsStats
*/
+ @SuppressWarnings("UnusedDeclaration")
public static CollectionStats[] fromTabularData(final TabularData tabularData) {
- final List countList = new ArrayList( tabularData.size() );
- for ( final Iterator pos = tabularData.values().iterator(); pos.hasNext(); ) {
- countList.add( new CollectionStats( (CompositeData) pos.next() ) );
+ final List countList = new ArrayList( tabularData.size() );
+ for ( Object o : tabularData.values() ) {
+ countList.add( new CollectionStats( (CompositeData) o ) );
}
return countList.toArray( new CollectionStats[countList.size()] );
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernate.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernate.java
index d63a0c8407..a978ff6140 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernate.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernate.java
@@ -23,12 +23,12 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicBoolean;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
import javax.management.openmbean.TabularData;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.hibernate.management.api.EhcacheHibernateMBean;
@@ -44,7 +44,7 @@ import org.hibernate.SessionFactory;
*
* @author Abhishek Sanoujam
*/
-public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernateMBean {
+public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibernateMBean {
private static final MBeanNotificationInfo NOTIFICATION_INFO;
private final AtomicBoolean statsEnabled = new AtomicBoolean( true );
@@ -52,7 +52,7 @@ public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernat
private volatile HibernateStats hibernateStats = NullHibernateStats.INSTANCE;
static {
- final String[] notifTypes = new String[] { };
+ final String[] notifTypes = new String[] {};
final String name = Notification.class.getName();
final String description = "Ehcache Hibernate Statistics Event";
NOTIFICATION_INFO = new MBeanNotificationInfo( notifTypes, name, description );
@@ -77,7 +77,7 @@ public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernat
try {
hibernateStats = new HibernateStatsImpl( sessionFactory );
}
- catch ( Exception e ) {
+ catch (Exception e) {
throw new RuntimeException( e );
}
}
@@ -588,10 +588,10 @@ public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernat
}
/**
- * @see BaseEmitterBean#getNotificationInfo()
+ * @see AbstractEmitterBean#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
- return new MBeanNotificationInfo[] { NOTIFICATION_INFO };
+ return new MBeanNotificationInfo[] {NOTIFICATION_INFO};
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMBeanRegistrationImpl.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMBeanRegistrationImpl.java
index 9605094fb6..738bca7e05 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMBeanRegistrationImpl.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMBeanRegistrationImpl.java
@@ -23,16 +23,17 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.lang.management.ManagementFactory;
-import java.util.Properties;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
+import java.lang.management.ManagementFactory;
+import java.util.Properties;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Status;
import net.sf.ehcache.event.CacheManagerEventListener;
+
import org.jboss.logging.Logger;
import org.hibernate.SessionFactory;
@@ -48,132 +49,132 @@ import org.hibernate.cfg.Environment;
* @author Abhishek Sanoujam
*/
public class EhcacheHibernateMBeanRegistrationImpl
- implements EhcacheHibernateMBeanRegistration, CacheManagerEventListener {
+ implements EhcacheHibernateMBeanRegistration, CacheManagerEventListener {
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- EhcacheHibernateMBeanRegistrationImpl.class.getName()
- );
- private static final int MAX_MBEAN_REGISTRATION_RETRIES = 50;
- private String cacheManagerClusterUUID;
- private String registeredCacheManagerName;
- private Status status = Status.STATUS_UNINITIALISED;
- private volatile EhcacheHibernate ehcacheHibernate;
- private volatile ObjectName cacheManagerObjectName;
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ EhcacheHibernateMBeanRegistrationImpl.class.getName()
+ );
+ private static final int MAX_MBEAN_REGISTRATION_RETRIES = 50;
+ private String cacheManagerClusterUUID;
+ private String registeredCacheManagerName;
+ private Status status = Status.STATUS_UNINITIALISED;
+ private volatile EhcacheHibernate ehcacheHibernate;
+ private volatile ObjectName cacheManagerObjectName;
- /**
- * {@inheritDoc}
- */
- public synchronized void registerMBeanForCacheManager(final CacheManager manager, final Properties properties)
- throws Exception {
- String sessionFactoryName = properties.getProperty( Environment.SESSION_FACTORY_NAME );
- String name = null;
- if ( sessionFactoryName == null ) {
- name = manager.getName();
- }
- else {
- name = "".equals( sessionFactoryName.trim() ) ? manager.getName() : sessionFactoryName;
- }
- registerBean( name, manager );
- }
+ /**
+ * {@inheritDoc}
+ */
+ public synchronized void registerMBeanForCacheManager(final CacheManager manager, final Properties properties)
+ throws Exception {
+ String sessionFactoryName = properties.getProperty( Environment.SESSION_FACTORY_NAME );
+ String name = null;
+ if ( sessionFactoryName == null ) {
+ name = manager.getName();
+ }
+ else {
+ name = "".equals( sessionFactoryName.trim() ) ? manager.getName() : sessionFactoryName;
+ }
+ registerBean( name, manager );
+ }
- private void registerBean(String name, CacheManager manager) throws Exception {
- ehcacheHibernate = new EhcacheHibernate( manager );
- int tries = 0;
- boolean success = false;
- Exception exception = null;
- cacheManagerClusterUUID = manager.getClusterUUID();
- do {
- this.registeredCacheManagerName = name;
- if ( tries != 0 ) {
- registeredCacheManagerName += "_" + tries;
- }
- try {
- // register the CacheManager MBean
- MBeanServer mBeanServer = getMBeanServer();
- cacheManagerObjectName = EhcacheHibernateMbeanNames.getCacheManagerObjectName(
- cacheManagerClusterUUID,
- registeredCacheManagerName
- );
- mBeanServer.registerMBean( ehcacheHibernate, cacheManagerObjectName );
- success = true;
- break;
- }
- catch ( InstanceAlreadyExistsException e ) {
- success = false;
- exception = e;
- }
- tries++;
- } while ( tries < MAX_MBEAN_REGISTRATION_RETRIES );
- if ( !success ) {
- throw new Exception(
- "Cannot register mbean for CacheManager with name" + manager.getName() + " after "
- + MAX_MBEAN_REGISTRATION_RETRIES + " retries. Last tried name=" + registeredCacheManagerName,
- exception
- );
- }
- status = Status.STATUS_ALIVE;
- }
+ private void registerBean(String name, CacheManager manager) throws Exception {
+ ehcacheHibernate = new EhcacheHibernate( manager );
+ int tries = 0;
+ boolean success = false;
+ Exception exception = null;
+ cacheManagerClusterUUID = manager.getClusterUUID();
+ do {
+ this.registeredCacheManagerName = name;
+ if ( tries != 0 ) {
+ registeredCacheManagerName += "_" + tries;
+ }
+ try {
+ // register the CacheManager MBean
+ MBeanServer mBeanServer = getMBeanServer();
+ cacheManagerObjectName = EhcacheHibernateMbeanNames.getCacheManagerObjectName(
+ cacheManagerClusterUUID,
+ registeredCacheManagerName
+ );
+ mBeanServer.registerMBean( ehcacheHibernate, cacheManagerObjectName );
+ success = true;
+ break;
+ }
+ catch (InstanceAlreadyExistsException e) {
+ success = false;
+ exception = e;
+ }
+ tries++;
+ } while ( tries < MAX_MBEAN_REGISTRATION_RETRIES );
+ if ( !success ) {
+ throw new Exception(
+ "Cannot register mbean for CacheManager with name" + manager.getName() + " after "
+ + MAX_MBEAN_REGISTRATION_RETRIES + " retries. Last tried name=" + registeredCacheManagerName,
+ exception
+ );
+ }
+ status = Status.STATUS_ALIVE;
+ }
- private MBeanServer getMBeanServer() {
- return ManagementFactory.getPlatformMBeanServer();
- }
+ private MBeanServer getMBeanServer() {
+ return ManagementFactory.getPlatformMBeanServer();
+ }
- /**
- * {@inheritDoc}
- */
- public void enableHibernateStatisticsSupport(SessionFactory sessionFactory) {
- ehcacheHibernate.enableHibernateStatistics( sessionFactory );
- }
+ /**
+ * {@inheritDoc}
+ */
+ public void enableHibernateStatisticsSupport(SessionFactory sessionFactory) {
+ ehcacheHibernate.enableHibernateStatistics( sessionFactory );
+ }
- /**
- * {@inheritDoc}
- */
- public synchronized void dispose() throws CacheException {
- if ( status == Status.STATUS_SHUTDOWN ) {
- return;
- }
+ /**
+ * {@inheritDoc}
+ */
+ public synchronized void dispose() throws CacheException {
+ if ( status == Status.STATUS_SHUTDOWN ) {
+ return;
+ }
- try {
- getMBeanServer().unregisterMBean( cacheManagerObjectName );
- }
- catch ( Exception e ) {
- LOG.warn(
- "Error unregistering object instance " + cacheManagerObjectName + " . Error was " + e.getMessage(),
- e
- );
- }
- ehcacheHibernate = null;
- cacheManagerObjectName = null;
- status = Status.STATUS_SHUTDOWN;
- }
+ try {
+ getMBeanServer().unregisterMBean( cacheManagerObjectName );
+ }
+ catch (Exception e) {
+ LOG.warn(
+ "Error unregistering object instance " + cacheManagerObjectName + " . Error was " + e.getMessage(),
+ e
+ );
+ }
+ ehcacheHibernate = null;
+ cacheManagerObjectName = null;
+ status = Status.STATUS_SHUTDOWN;
+ }
- /**
- * {@inheritDoc}
- */
- public synchronized Status getStatus() {
- return status;
- }
+ /**
+ * {@inheritDoc}
+ */
+ public synchronized Status getStatus() {
+ return status;
+ }
- /**
- * No-op in this case
- */
- public void init() throws CacheException {
- // no-op
- }
+ /**
+ * No-op in this case
+ */
+ public void init() throws CacheException {
+ // no-op
+ }
- /**
- * No-op in this case
- */
- public void notifyCacheAdded(String cacheName) {
- // no-op
- }
+ /**
+ * No-op in this case
+ */
+ public void notifyCacheAdded(String cacheName) {
+ // no-op
+ }
- /**
- * No-op in this case
- */
- public void notifyCacheRemoved(String cacheName) {
- // no-op
- }
+ /**
+ * No-op in this case
+ */
+ public void notifyCacheRemoved(String cacheName) {
+ // no-op
+ }
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheStatsImpl.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheStatsImpl.java
index 190c9245a2..b3c90f2727 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheStatsImpl.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheStatsImpl.java
@@ -23,12 +23,12 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
@@ -42,7 +42,7 @@ import net.sf.ehcache.management.sampled.SampledCacheManager;
*
* @author Abhishek Sanoujam
*/
-public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
+public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStats {
private static final long MILLIS_PER_SECOND = 1000;
private static final MBeanNotificationInfo NOTIFICATION_INFO;
@@ -156,7 +156,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
*/
public double getCacheHitRate() {
long now = System.currentTimeMillis();
- double deltaSecs = (double) ( now - statsSince ) / MILLIS_PER_SECOND;
+ double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND;
return getCacheHitCount() / deltaSecs;
}
@@ -193,7 +193,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
*/
public double getCacheMissRate() {
long now = System.currentTimeMillis();
- double deltaSecs = (double) ( now - statsSince ) / MILLIS_PER_SECOND;
+ double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND;
return getCacheMissCount() / deltaSecs;
}
@@ -230,7 +230,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
*/
public double getCachePutRate() {
long now = System.currentTimeMillis();
- double deltaSecs = (double) ( now - statsSince ) / MILLIS_PER_SECOND;
+ double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND;
return getCachePutCount() / deltaSecs;
}
@@ -339,8 +339,8 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
rv.put(
name, new int[] {
(int) cache.getSampledCacheStatistics().getCacheHitMostRecentSample(),
- (int) ( cache.getSampledCacheStatistics().getCacheMissNotFoundMostRecentSample()
- + cache.getSampledCacheStatistics().getCacheMissExpiredMostRecentSample() ),
+ (int) (cache.getSampledCacheStatistics().getCacheMissNotFoundMostRecentSample()
+ + cache.getSampledCacheStatistics().getCacheMissExpiredMostRecentSample()),
(int) cache.getSampledCacheStatistics().getCacheElementPutMostRecentSample(),
}
);
@@ -388,7 +388,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
}
}
}
- return rv.toArray( new String[] { } );
+ return rv.toArray( new String[] {} );
}
/**
@@ -680,10 +680,10 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats {
}
/**
- * @see BaseEmitterBean#getNotificationInfo()
+ * @see AbstractEmitterBean#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
- return new MBeanNotificationInfo[] { NOTIFICATION_INFO };
+ return new MBeanNotificationInfo[] {NOTIFICATION_INFO};
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EntityStats.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EntityStats.java
index 6ce06f1cee..a121801db3 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EntityStats.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EntityStats.java
@@ -23,10 +23,6 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
@@ -36,6 +32,10 @@ import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
import org.hibernate.stat.EntityStatistics;
@@ -63,7 +63,7 @@ public class EntityStats implements Serializable {
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Entity";
private static final String TABULAR_TYPE_DESCRIPTION = "All Entity Statistics";
- private static final String[] INDEX_NAMES = new String[] { "name", };
+ private static final String[] INDEX_NAMES = new String[] {"name",};
private static final TabularType TABULAR_TYPE;
static {
@@ -74,7 +74,7 @@ public class EntityStats implements Serializable {
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
@@ -142,7 +142,7 @@ public class EntityStats implements Serializable {
this.fetchCount = BeanUtils.getLongBeanProperty( src, "fetchCount" );
this.optimisticFailureCount = BeanUtils.getLongBeanProperty( src, "optimisticFailureCount" );
}
- catch ( Exception e ) {
+ catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
@@ -167,7 +167,7 @@ public class EntityStats implements Serializable {
try {
return Integer.parseInt( s );
}
- catch ( Exception e ) {
+ catch (Exception e) {
return -1;
}
}
@@ -262,7 +262,7 @@ public class EntityStats implements Serializable {
}
);
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/HibernateStatsImpl.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/HibernateStatsImpl.java
index f75bfa3ebe..85eed55b05 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/HibernateStatsImpl.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/HibernateStatsImpl.java
@@ -23,13 +23,13 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.util.ArrayList;
-import java.util.List;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
+import java.util.ArrayList;
+import java.util.List;
import net.sf.ehcache.hibernate.management.api.HibernateStats;
@@ -43,14 +43,14 @@ import org.hibernate.stat.Statistics;
*
* @author Abhishek Sanoujam
*/
-public class HibernateStatsImpl extends BaseEmitterBean implements HibernateStats {
+public class HibernateStatsImpl extends AbstractEmitterBean implements HibernateStats {
private static final double MILLIS_PER_SECOND = 1000;
private static final MBeanNotificationInfo NOTIFICATION_INFO;
private final SessionFactory sessionFactory;
static {
- final String[] notifTypes = new String[] { };
+ final String[] notifTypes = new String[] {};
final String name = Notification.class.getName();
final String description = "Hibernate Statistics Event";
NOTIFICATION_INFO = new MBeanNotificationInfo( notifTypes, name, description );
@@ -172,7 +172,7 @@ public class HibernateStatsImpl extends BaseEmitterBean implements HibernateStat
public double getQueryExecutionRate() {
long startTime = getStatistics().getStartTime();
long now = System.currentTimeMillis();
- double deltaSecs = ( now - startTime ) / MILLIS_PER_SECOND;
+ double deltaSecs = (now - startTime) / MILLIS_PER_SECOND;
return getQueryExecutionCount() / deltaSecs;
}
@@ -321,10 +321,10 @@ public class HibernateStatsImpl extends BaseEmitterBean implements HibernateStat
}
/**
- * @see BaseEmitterBean#getNotificationInfo()
+ * @see AbstractEmitterBean#getNotificationInfo()
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo() {
- return new MBeanNotificationInfo[] { NOTIFICATION_INFO };
+ return new MBeanNotificationInfo[] {NOTIFICATION_INFO};
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/ProviderMBeanRegistrationHelper.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/ProviderMBeanRegistrationHelper.java
index 10a4c28caf..648cc17cf6 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/ProviderMBeanRegistrationHelper.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/ProviderMBeanRegistrationHelper.java
@@ -31,6 +31,7 @@ import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import net.sf.ehcache.CacheManager;
+
import org.jboss.logging.Logger;
import org.hibernate.SessionFactory;
@@ -48,141 +49,142 @@ import org.hibernate.internal.SessionFactoryRegistry;
* @author Alex Snaps
*/
public class ProviderMBeanRegistrationHelper {
- private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
- EhCacheMessageLogger.class,
- ProviderMBeanRegistrationHelper.class.getName()
- );
- private static final int MILLIS_PER_SECOND = 1000;
- private static final int SLEEP_MILLIS = 500;
+ private static final EhCacheMessageLogger LOG = Logger.getMessageLogger(
+ EhCacheMessageLogger.class,
+ ProviderMBeanRegistrationHelper.class.getName()
+ );
+ private static final int MILLIS_PER_SECOND = 1000;
+ private static final int SLEEP_MILLIS = 500;
- private volatile EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration;
+ private volatile EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration;
- /**
- * Registers mbean for the input cache manager and the session factory name
- *
- * @param manager the backing cachemanager
- * @param properties session factory config properties
- */
- public void registerMBean(final CacheManager manager, final Properties properties) {
- if ( Boolean.getBoolean( "tc.active" ) ) {
- ehcacheHibernateMBeanRegistration = new EhcacheHibernateMBeanRegistrationImpl();
- manager.getTimer().scheduleAtFixedRate(
- new RegisterMBeansTask( ehcacheHibernateMBeanRegistration, manager, properties ), SLEEP_MILLIS,
- SLEEP_MILLIS
- );
- }
- }
+ /**
+ * Registers mbean for the input cache manager and the session factory name
+ *
+ * @param manager the backing cachemanager
+ * @param properties session factory config properties
+ */
+ public void registerMBean(final CacheManager manager, final Properties properties) {
+ if ( Boolean.getBoolean( "tc.active" ) ) {
+ ehcacheHibernateMBeanRegistration = new EhcacheHibernateMBeanRegistrationImpl();
+ manager.getTimer().scheduleAtFixedRate(
+ new RegisterMBeansTask( ehcacheHibernateMBeanRegistration, manager, properties ), SLEEP_MILLIS,
+ SLEEP_MILLIS
+ );
+ }
+ }
- /**
- * Unregisters previously registered mbean.
- */
- public void unregisterMBean() {
- if ( ehcacheHibernateMBeanRegistration != null ) {
- ehcacheHibernateMBeanRegistration.dispose();
- ehcacheHibernateMBeanRegistration = null;
- }
- }
+ /**
+ * Unregisters previously registered mbean.
+ */
+ public void unregisterMBean() {
+ if ( ehcacheHibernateMBeanRegistration != null ) {
+ ehcacheHibernateMBeanRegistration.dispose();
+ ehcacheHibernateMBeanRegistration = null;
+ }
+ }
- /**
- * Task for running mbean registration that can be scheduled in a timer
- */
- private static class RegisterMBeansTask extends TimerTask {
- private static final int NUM_SECONDS = 30;
- private long startTime;
- private final AtomicBoolean mbeanRegistered = new AtomicBoolean( false );
- private final EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration;
- private final CacheManager manager;
- private final Properties properties;
+ /**
+ * Task for running mbean registration that can be scheduled in a timer
+ */
+ private static class RegisterMBeansTask extends TimerTask {
+ private static final int NUM_SECONDS = 30;
+ private long startTime;
+ private final AtomicBoolean mbeanRegistered = new AtomicBoolean( false );
+ private final EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration;
+ private final CacheManager manager;
+ private final Properties properties;
- public RegisterMBeansTask(EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration,
- CacheManager manager, Properties properties) {
- this.ehcacheHibernateMBeanRegistration = ehcacheHibernateMBeanRegistration;
- this.manager = manager;
- this.properties = properties;
- }
+ public RegisterMBeansTask(
+ EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration,
+ CacheManager manager, Properties properties) {
+ this.ehcacheHibernateMBeanRegistration = ehcacheHibernateMBeanRegistration;
+ this.manager = manager;
+ this.properties = properties;
+ }
- @Override
- public void run() {
- LOG.debug( "Running mbean initializer task for ehcache hibernate..." );
- startTime = System.currentTimeMillis();
- if ( mbeanRegistered.compareAndSet( false, true ) ) {
- try {
- ehcacheHibernateMBeanRegistration.registerMBeanForCacheManager( manager, properties );
- LOG.debug( "Successfully registered bean" );
- }
- catch ( Exception e ) {
- throw new CacheException( e );
- }
- }
- SessionFactory sessionFactory = locateSessionFactory();
- if ( sessionFactory == null ) {
- LOG.debug(
- "SessionFactory is probably still being initialized..."
- + " waiting for it to complete before enabling hibernate statistics monitoring via JMX"
- );
- if ( System.currentTimeMillis() > startTime + ( NUM_SECONDS * MILLIS_PER_SECOND ) ) {
- LOG.info( "Hibernate statistics monitoring through JMX is DISABLED." );
- LOG.info(
- "Failed to look up SessionFactory after " + NUM_SECONDS + " seconds using session-factory properties '"
- + properties + "'"
- );
- this.cancel();
- }
- return;
- }
- else {
- ehcacheHibernateMBeanRegistration.enableHibernateStatisticsSupport( sessionFactory );
- LOG.info( "Hibernate statistics monitoring through JMX is ENABLED. " );
- this.cancel();
- }
- }
+ @Override
+ public void run() {
+ LOG.debug( "Running mbean initializer task for ehcache hibernate..." );
+ startTime = System.currentTimeMillis();
+ if ( mbeanRegistered.compareAndSet( false, true ) ) {
+ try {
+ ehcacheHibernateMBeanRegistration.registerMBeanForCacheManager( manager, properties );
+ LOG.debug( "Successfully registered bean" );
+ }
+ catch (Exception e) {
+ throw new CacheException( e );
+ }
+ }
+ SessionFactory sessionFactory = locateSessionFactory();
+ if ( sessionFactory == null ) {
+ LOG.debug(
+ "SessionFactory is probably still being initialized..."
+ + " waiting for it to complete before enabling hibernate statistics monitoring via JMX"
+ );
+ if ( System.currentTimeMillis() > startTime + (NUM_SECONDS * MILLIS_PER_SECOND) ) {
+ LOG.info( "Hibernate statistics monitoring through JMX is DISABLED." );
+ LOG.info(
+ "Failed to look up SessionFactory after " + NUM_SECONDS + " seconds using session-factory properties '"
+ + properties + "'"
+ );
+ this.cancel();
+ }
+ return;
+ }
+ else {
+ ehcacheHibernateMBeanRegistration.enableHibernateStatisticsSupport( sessionFactory );
+ LOG.info( "Hibernate statistics monitoring through JMX is ENABLED. " );
+ this.cancel();
+ }
+ }
- private SessionFactory locateSessionFactory() {
- String jndiName = properties.getProperty( Environment.SESSION_FACTORY_NAME );
- if ( jndiName != null ) {
- return SessionFactoryRegistry.INSTANCE.getNamedSessionFactory( jndiName );
- }
- try {
- Class factoryType = SessionFactoryRegistry.class;
- Field instancesField = getField( factoryType, "sessionFactoryMap" );
- if ( instancesField == null ) {
- throw new RuntimeException( "Expected 'sessionFactoryMap' field on " + SessionFactoryRegistry.class.getName() );
- }
- instancesField.setAccessible( true );
- Map map = (Map) instancesField.get( SessionFactoryRegistry.INSTANCE );
- if ( map == null ) {
- return null;
- }
- Iterator values = map.values().iterator();
- while ( values.hasNext() ) {
- SessionFactory sessionFactory = (SessionFactory) values.next();
- Class sessionFactoryType = sessionFactory.getClass();
- Field propertiesField = getField( sessionFactoryType, "properties" );
- if ( propertiesField != null ) {
- propertiesField.setAccessible( true );
- Properties props = (Properties) propertiesField.get( sessionFactory );
- if ( props != null && props.equals( properties ) ) {
- return sessionFactory;
- }
- }
- }
- }
- catch ( RuntimeException re ) {
- LOG.error( "Error locating Hibernate Session Factory", re );
- }
- catch ( IllegalAccessException iae ) {
- LOG.error( "Error locating Hibernate Session Factory", iae );
- }
- return null;
- }
- }
+ private SessionFactory locateSessionFactory() {
+ String jndiName = properties.getProperty( Environment.SESSION_FACTORY_NAME );
+ if ( jndiName != null ) {
+ return SessionFactoryRegistry.INSTANCE.getNamedSessionFactory( jndiName );
+ }
+ try {
+ Class factoryType = SessionFactoryRegistry.class;
+ Field instancesField = getField( factoryType, "sessionFactoryMap" );
+ if ( instancesField == null ) {
+ throw new RuntimeException( "Expected 'sessionFactoryMap' field on " + SessionFactoryRegistry.class.getName() );
+ }
+ instancesField.setAccessible( true );
+ Map map = (Map) instancesField.get( SessionFactoryRegistry.INSTANCE );
+ if ( map == null ) {
+ return null;
+ }
+ Iterator values = map.values().iterator();
+ while ( values.hasNext() ) {
+ SessionFactory sessionFactory = (SessionFactory) values.next();
+ Class sessionFactoryType = sessionFactory.getClass();
+ Field propertiesField = getField( sessionFactoryType, "properties" );
+ if ( propertiesField != null ) {
+ propertiesField.setAccessible( true );
+ Properties props = (Properties) propertiesField.get( sessionFactory );
+ if ( props != null && props.equals( properties ) ) {
+ return sessionFactory;
+ }
+ }
+ }
+ }
+ catch (RuntimeException re) {
+ LOG.error( "Error locating Hibernate Session Factory", re );
+ }
+ catch (IllegalAccessException iae) {
+ LOG.error( "Error locating Hibernate Session Factory", iae );
+ }
+ return null;
+ }
+ }
- private static Field getField(Class c, String fieldName) {
- for ( Field field : c.getDeclaredFields() ) {
- if ( field.getName().equals( fieldName ) ) {
- return field;
- }
- }
- throw new NoSuchFieldError( "Type '" + c + "' has no field '" + fieldName + "'" );
- }
+ private static Field getField(Class c, String fieldName) {
+ for ( Field field : c.getDeclaredFields() ) {
+ if ( field.getName().equals( fieldName ) ) {
+ return field;
+ }
+ }
+ throw new NoSuchFieldError( "Type '" + c + "' has no field '" + fieldName + "'" );
+ }
}
\ No newline at end of file
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/QueryStats.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/QueryStats.java
index 594b3f022f..27c33bea14 100644
--- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/QueryStats.java
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/QueryStats.java
@@ -23,10 +23,6 @@
*/
package org.hibernate.cache.ehcache.management.impl;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
@@ -36,6 +32,10 @@ import javax.management.openmbean.SimpleType;
import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularDataSupport;
import javax.management.openmbean.TabularType;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
import org.hibernate.stat.QueryStatistics;
@@ -75,7 +75,7 @@ public class QueryStats implements Serializable {
private static final CompositeType COMPOSITE_TYPE;
private static final String TABULAR_TYPE_NAME = "Statistics by Query";
private static final String TABULAR_TYPE_DESCRIPTION = "All Query Statistics";
- private static final String[] INDEX_NAMES = new String[] { "query", };
+ private static final String[] INDEX_NAMES = new String[] {"query",};
private static final TabularType TABULAR_TYPE;
static {
@@ -86,7 +86,7 @@ public class QueryStats implements Serializable {
);
TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES );
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
@@ -161,7 +161,7 @@ public class QueryStats implements Serializable {
this.executionMinTime =
BeanUtils.getLongBeanProperty( src, "executionMinTime" );
}
- catch ( Exception e ) {
+ catch (Exception e) {
e.printStackTrace();
throw new RuntimeException( "Exception retrieving statistics", e );
}
@@ -187,7 +187,7 @@ public class QueryStats implements Serializable {
try {
return Integer.parseInt( s );
}
- catch ( Exception e ) {
+ catch (Exception e) {
return -1;
}
}
@@ -297,7 +297,7 @@ public class QueryStats implements Serializable {
}
);
}
- catch ( OpenDataException e ) {
+ catch (OpenDataException e) {
throw new RuntimeException( e );
}
}
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/package-info.java
new file mode 100644
index 0000000000..3724875d2c
--- /dev/null
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines JMX support for the Ehcache integration
+ */
+package org.hibernate.cache.ehcache.management.impl;
diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/package-info.java
new file mode 100644
index 0000000000..64d91cc77e
--- /dev/null
+++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines the integration with Ehcache as a second-level cache service.
+ */
+package org.hibernate.cache.ehcache;
diff --git a/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.AvailabilityAnnouncer b/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.AvailabilityAnnouncer
deleted file mode 100644
index 4089ec9f31..0000000000
--- a/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.AvailabilityAnnouncer
+++ /dev/null
@@ -1 +0,0 @@
-org.hibernate.cache.ehcache.AvailabilityAnnouncerImpl
\ No newline at end of file
diff --git a/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider b/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider
new file mode 100644
index 0000000000..4f53a53867
--- /dev/null
+++ b/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider
@@ -0,0 +1 @@
+org.hibernate.cache.ehcache.StrategyRegistrationProviderImpl
\ No newline at end of file
diff --git a/hibernate-ehcache/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/hibernate-ehcache/src/main/resources/OSGI-INF/blueprint/blueprint.xml
new file mode 100644
index 0000000000..fbbb6739e6
--- /dev/null
+++ b/hibernate-ehcache/src/main/resources/OSGI-INF/blueprint/blueprint.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/AvailableSettings.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/AvailableSettings.java
index 849158b5ca..d077654831 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/AvailableSettings.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/AvailableSettings.java
@@ -23,7 +23,6 @@
*/
package org.hibernate.jpa;
-
/**
* Defines the available HEM settings, both JPA-defined as well as Hibernate-specific
*
@@ -456,7 +455,10 @@ public interface AvailableSettings extends org.hibernate.cfg.AvailableSettings {
* Consider this as experimental
* It is not recommended to set up this property, the configuration is stored
* in the JNDI in a serialized form
+ *
+ * @deprecated Configuration going away.
*/
+ @Deprecated
public static final String CONFIGURATION_JNDI_NAME = "hibernate.ejb.configuration_jndi_name";
/**
@@ -466,7 +468,7 @@ public interface AvailableSettings extends org.hibernate.cfg.AvailableSettings {
public static final String FLUSH_MODE = "org.hibernate.flushMode";
/**
- * Pass an implementation of {@link org.hibernate.jpa.packaging.spi.Scanner}:
+ * Pass an implementation of {@link org.hibernate.jpa.boot.scan.spi.Scanner}:
* - preferably an actual instance
* - or a class name with a no-arg constructor
*/
@@ -475,13 +477,21 @@ public interface AvailableSettings extends org.hibernate.cfg.AvailableSettings {
/**
* List of classes names
* Internal use only
+ *
+ * @deprecated Was never intended for external use
*/
+ @Deprecated
+ @SuppressWarnings("UnusedDeclaration")
public static final String CLASS_NAMES = "hibernate.ejb.classes";
/**
* List of annotated packages
* Internal use only
+ *
+ * @deprecated Was never intended for external use
*/
+ @Deprecated
+ @SuppressWarnings("UnusedDeclaration")
public static final String PACKAGE_NAMES = "hibernate.ejb.packages";
/**
@@ -497,9 +507,34 @@ public interface AvailableSettings extends org.hibernate.cfg.AvailableSettings {
public static final String XML_FILE_NAMES = "hibernate.ejb.xml_files";
public static final String HBXML_FILES = "hibernate.hbmxml.files";
public static final String LOADED_CLASSES = "hibernate.ejb.loaded.classes";
+
+ /**
+ * Deprecated
+ *
+ * @deprecated Use {@link org.hibernate.cfg.AvailableSettings#JACC_CONTEXT_ID} instead
+ */
+ @Deprecated
public static final String JACC_CONTEXT_ID = org.hibernate.cfg.AvailableSettings.JACC_CONTEXT_ID;
+
+ /**
+ * Deprecated
+ *
+ * @deprecated Use {@link org.hibernate.cfg.AvailableSettings#JACC_PREFIX} instead
+ */
+ @Deprecated
public static final String JACC_PREFIX = org.hibernate.cfg.AvailableSettings.JACC_PREFIX;
+
+ /**
+ * Deprecated
+ *
+ * @deprecated Use {@link org.hibernate.cfg.AvailableSettings#JACC_ENABLED} instead
+ */
+ @Deprecated
public static final String JACC_ENABLED = org.hibernate.cfg.AvailableSettings.JACC_ENABLED;
+
+ /**
+ * Used to pass along the name of the persistence unit.
+ */
public static final String PERSISTENCE_UNIT_NAME = "hibernate.ejb.persistenceUnitName";
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernateEntityManagerFactory.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernateEntityManagerFactory.java
index 95d918118f..d59795c5db 100755
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernateEntityManagerFactory.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernateEntityManagerFactory.java
@@ -42,5 +42,13 @@ public interface HibernateEntityManagerFactory extends EntityManagerFactory, Ser
*/
public SessionFactory getSessionFactory();
+ /**
+ * Retrieve the EntityTypeImpl by name. Use of the Hibernate O/RM notion the "entity name" allows support
+ * for non-strictly-JPA models to be used in JPA APIs
+ *
+ * @param entityName The entity name
+ *
+ * @return The EntityTypeImpl
+ */
public EntityTypeImpl getEntityTypeByName(String entityName);
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernatePersistenceProvider.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernatePersistenceProvider.java
index a20a468232..2226d6555c 100755
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernatePersistenceProvider.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernatePersistenceProvider.java
@@ -80,7 +80,7 @@ public class HibernatePersistenceProvider implements PersistenceProvider {
final Map integration = wrap( properties );
final List units;
try {
- units = PersistenceXmlParser.locatePersistenceUnits( integration );
+ units = PersistenceXmlParser.locatePersistenceUnits( integration );
}
catch (RuntimeException e) {
log.debug( "Unable to locate persistence units", e );
@@ -106,7 +106,7 @@ public class HibernatePersistenceProvider implements PersistenceProvider {
persistenceUnitName
);
- boolean matches = persistenceUnitName == null || persistenceUnit.getName().equals( persistenceUnitName );
+ final boolean matches = persistenceUnitName == null || persistenceUnit.getName().equals( persistenceUnitName );
if ( !matches ) {
log.debug( "Excluding from consideration due to name mis-match" );
continue;
@@ -146,7 +146,7 @@ public class HibernatePersistenceProvider implements PersistenceProvider {
public void generateSchema(PersistenceUnitInfo info, Map map) {
log.tracef( "Starting generateSchema : PUI.name=%s", info.getPersistenceUnitName() );
- EntityManagerFactoryBuilder builder = Bootstrap.getEntityManagerFactoryBuilder( info, map );
+ final EntityManagerFactoryBuilder builder = Bootstrap.getEntityManagerFactoryBuilder( info, map );
builder.generateSchema();
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/QueryHints.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/QueryHints.java
index e06fd91fdf..da1d05ea5b 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/QueryHints.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/QueryHints.java
@@ -26,23 +26,62 @@ import java.util.HashSet;
import java.util.Set;
/**
- * TODO : javadoc
+ * Defines the supported JPA query hints
*
* @author Steve Ebersole
*/
public class QueryHints {
/**
- * @deprecated HINT_TIMEOUT (org.hibernate.timeout),
- * instead use SPEC_HINT_TIMEOUT (javax.persistence.query.timeout)
+ * The hint key for specifying a query timeout per Hibernate O/RM, which defines the timeout in seconds.
+ *
+ * @deprecated use {@link #SPEC_HINT_TIMEOUT} instead
+ */
+ @Deprecated
+ public static final String HINT_TIMEOUT = "org.hibernate.timeout";
+
+ /**
+ * The hint key for specifying a query timeout per JPA, which defines the timeout in milliseconds
+ */
+ public static final String SPEC_HINT_TIMEOUT = "javax.persistence.query.timeout";
+
+ /**
+ * The hint key for specifying a comment which is to be embedded into the SQL sent to the database.
*/
- public static final String HINT_TIMEOUT = "org.hibernate.timeout"; // Query timeout in seconds
- public static final String SPEC_HINT_TIMEOUT = "javax.persistence.query.timeout"; // timeout in milliseconds
public static final String HINT_COMMENT = "org.hibernate.comment";
+
+ /**
+ * The hint key for specifying a JDBC fetch size, used when executing the resulting SQL.
+ */
public static final String HINT_FETCH_SIZE = "org.hibernate.fetchSize";
- public static final String HINT_CACHE_REGION = "org.hibernate.cacheRegion";
+
+ /**
+ * The hint key for specifying whether the query results should be cached for the next (cached) execution of the
+ * "same query".
+ */
public static final String HINT_CACHEABLE = "org.hibernate.cacheable";
+
+ /**
+ * The hint key for specifying the name of the cache region (within Hibernate's query result cache region)
+ * to use for storing the query results.
+ */
+ public static final String HINT_CACHE_REGION = "org.hibernate.cacheRegion";
+
+ /**
+ * The hint key for specifying that objects loaded into the persistence context as a result of this query execution
+ * should be associated with the persistence context as read-only.
+ */
public static final String HINT_READONLY = "org.hibernate.readOnly";
+
+ /**
+ * The hint key for specifying the cache mode ({@link org.hibernate.CacheMode}) to be in effect for the
+ * execution of the hinted query.
+ */
public static final String HINT_CACHE_MODE = "org.hibernate.cacheMode";
+
+ /**
+ * The hint key for specifying the flush mode ({@link org.hibernate.FlushMode}) to be in effect for the
+ * execution of the hinted query.
+ */
public static final String HINT_FLUSH_MODE = "org.hibernate.flushMode";
private static final Set HINTS = buildHintsSet();
@@ -64,4 +103,7 @@ public class QueryHints {
public static Set getDefinedHints() {
return HINTS;
}
+
+ protected QueryHints() {
+ }
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/SchemaGenAction.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/SchemaGenAction.java
index 1a9a63b771..3590f9cf74 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/SchemaGenAction.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/SchemaGenAction.java
@@ -93,10 +93,20 @@ public enum SchemaGenAction {
);
}
+ /**
+ * Does this action include creations?
+ *
+ * @return {@code true} if this action is either {@link #CREATE} or {@link #BOTH}
+ */
public boolean includesCreate() {
return this == CREATE || this == BOTH;
}
+ /**
+ * Does this action include drops?
+ *
+ * @return {@code true} if this action is either {@link #DROP} or {@link #BOTH}
+ */
public boolean includesDrop() {
return this == DROP || this == BOTH;
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ArchiveHelper.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ArchiveHelper.java
index 76caf4db9c..1b5c765bb8 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ArchiveHelper.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ArchiveHelper.java
@@ -36,6 +36,8 @@ import org.jboss.logging.Logger;
import org.hibernate.jpa.boot.archive.spi.ArchiveException;
/**
+ * Helper for dealing with archives
+ *
* @author Emmanuel Bernard
* @author Steve Ebersole
*/
@@ -54,32 +56,36 @@ public class ArchiveHelper {
public static URL getJarURLFromURLEntry(URL url, String entry) throws IllegalArgumentException {
URL jarUrl;
String file = url.getFile();
- if ( ! entry.startsWith( "/" ) ) entry = "/" + entry;
+ if ( ! entry.startsWith( "/" ) ) {
+ entry = "/" + entry;
+ }
file = file.substring( 0, file.length() - entry.length() );
- if ( file.endsWith( "!" ) ) file = file.substring( 0, file.length() - 1 );
+ if ( file.endsWith( "!" ) ) {
+ file = file.substring( 0, file.length() - 1 );
+ }
try {
- String protocol = url.getProtocol();
+ final String protocol = url.getProtocol();
- if ( "jar".equals( protocol )
- || "wsjar".equals( protocol ) ) { //Websphere has it's own way
+ if ( "jar".equals( protocol ) || "wsjar".equals( protocol ) ) {
//Original URL is like jar:protocol
+ //WebSphere has it's own way
jarUrl = new URL( file );
if ( "file".equals( jarUrl.getProtocol() ) ) {
- //not escaped, need to voodoo
if ( file.indexOf( ' ' ) != -1 ) {
- //not escaped, need to voodoo
- jarUrl = new File( jarUrl.getFile() ).toURI().toURL(); //goes by toURI to escape the path
+ //not escaped, need to voodoo; goes by toURI to escape the path
+ jarUrl = new File( jarUrl.getFile() ).toURI().toURL();
}
- } //otherwise left as is
+ }
}
- else if ( "zip".equals( protocol ) //Weblogic has it's own way
- || "code-source".equals( url.getProtocol() ) //OC4J prevent ejb.jar access (ie everything without path)
- || "file".equals( protocol ) //if no wrapping is done
- ) {
+ else if ( "zip".equals( protocol )
+ //OC4J prevent ejb.jar access (ie everything without path)
+ || "code-source".equals( url.getProtocol() )
+ //if no wrapping is done
+ || "file".equals( protocol ) ) {
//we have extracted the zip file, so it should be read as a file
if ( file.indexOf( ' ' ) != -1 ) {
- //not escaped, need to voodoo
- jarUrl = new File(file).toURI().toURL(); //goes by toURI to escape the path
+ //not escaped, need to voodoo; goes by toURI to escape the path
+ jarUrl = new File(file).toURI().toURL();
}
else {
jarUrl = new File(file).toURL();
@@ -92,7 +98,7 @@ public class ArchiveHelper {
jarUrl = new URL( protocol, url.getHost(), url.getPort(), file );
}
//HHH-6442: Arquilian
- catch ( final MalformedURLException murle ) {
+ catch ( final MalformedURLException e ) {
//Just use the provided URL as-is, likely it has a URLStreamHandler
//associated w/ the instance
jarUrl = url;
@@ -104,13 +110,17 @@ public class ArchiveHelper {
"Unable to determine JAR Url from " + url + ". Cause: " + e.getMessage()
);
}
- log.trace("JAR URL from URL Entry: " + url + " >> " + jarUrl);
+ log.trace( "JAR URL from URL Entry: " + url + " >> " + jarUrl );
return jarUrl;
}
/**
* get the URL from a given path string
*
+ * @param jarPath The path that represents a URL
+ *
+ * @return The resolved URL reference
+ *
* @throws IllegalArgumentException is something goes wrong
*/
public static URL getURLFromPath(String jarPath) {
@@ -131,30 +141,17 @@ public class ArchiveHelper {
return jarUrl;
}
- public static String unqualifiedJarFileName(URL jarUrl) {
- // todo : weak algorithm subject to AOOBE
- String fileName = jarUrl.getFile();
- int exclamation = fileName.lastIndexOf( "!" );
- if (exclamation != -1) {
- fileName = fileName.substring( 0, exclamation );
- }
-
- int slash = fileName.lastIndexOf( "/" );
- if ( slash != -1 ) {
- fileName = fileName.substring(
- fileName.lastIndexOf( "/" ) + 1,
- fileName.length()
- );
- }
-
- if ( fileName.length() > 4 && fileName.endsWith( "ar" ) && fileName.charAt( fileName.length() - 4 ) == '.' ) {
- fileName = fileName.substring( 0, fileName.length() - 4 );
- }
-
- return fileName;
- }
-
- public static byte[] getBytesFromInputStreamSafely(InputStream inputStream) {
+ /**
+ * Extracts the bytes out of an InputStream. This form is the same as {@link #getBytesFromInputStream}
+ * except that any {@link IOException} are wrapped as (runtime) {@link ArchiveException}
+ *
+ * @param inputStream The stream from which to extract bytes.
+ *
+ * @return The bytes
+ *
+ * @throws ArchiveException Indicates a problem accessing the stream
+ */
+ public static byte[] getBytesFromInputStreamSafely(InputStream inputStream) throws ArchiveException {
try {
return getBytesFromInputStream( inputStream );
}
@@ -163,18 +160,30 @@ public class ArchiveHelper {
}
}
+ /**
+ * Extracts the bytes out of an InputStream.
+ *
+ * @param inputStream The stream from which to extract bytes.
+ *
+ * @return The bytes
+ *
+ * @throws IOException Indicates a problem accessing the stream
+ *
+ * @see #getBytesFromInputStreamSafely(java.io.InputStream)
+ */
public static byte[] getBytesFromInputStream(InputStream inputStream) throws IOException {
// Optimized by HHH-7835
int size;
- List data = new LinkedList();
- int bufferSize = 4096;
+ final List data = new LinkedList();
+ final int bufferSize = 4096;
byte[] tmpByte = new byte[bufferSize];
int offset = 0;
int total = 0;
for ( ;; ) {
size = inputStream.read( tmpByte, offset, bufferSize - offset );
- if ( size == -1 )
+ if ( size == -1 ) {
break;
+ }
offset += size;
@@ -186,7 +195,7 @@ public class ArchiveHelper {
}
}
- byte[] result = new byte[total + offset];
+ final byte[] result = new byte[total + offset];
int count = 0;
for ( byte[] arr : data ) {
System.arraycopy( arr, 0, result, count * arr.length, arr.length );
@@ -196,4 +205,7 @@ public class ArchiveHelper {
return result;
}
+
+ private ArchiveHelper() {
+ }
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ExplodedArchiveDescriptor.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ExplodedArchiveDescriptor.java
index 50a64a1a2f..2b5fed3ac9 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ExplodedArchiveDescriptor.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ExplodedArchiveDescriptor.java
@@ -43,6 +43,8 @@ import org.hibernate.jpa.boot.spi.InputStreamAccess;
import org.hibernate.jpa.internal.EntityManagerMessageLogger;
/**
+ * Descriptor for exploded (directory) archives
+ *
* @author Steve Ebersole
*/
public class ExplodedArchiveDescriptor extends AbstractArchiveDescriptor {
@@ -51,6 +53,13 @@ public class ExplodedArchiveDescriptor extends AbstractArchiveDescriptor {
ExplodedArchiveDescriptor.class.getName()
);
+ /**
+ * Constructs an ExplodedArchiveDescriptor
+ *
+ * @param archiveDescriptorFactory The factory creating this
+ * @param archiveUrl The directory URL
+ * @param entryBasePrefix the base (within the url) that described the prefix for entries within the archive
+ */
public ExplodedArchiveDescriptor(
ArchiveDescriptorFactory archiveDescriptorFactory,
URL archiveUrl,
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarFileBasedArchiveDescriptor.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarFileBasedArchiveDescriptor.java
index d601d69ae2..259647b041 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarFileBasedArchiveDescriptor.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarFileBasedArchiveDescriptor.java
@@ -55,6 +55,13 @@ public class JarFileBasedArchiveDescriptor extends AbstractArchiveDescriptor {
JarFileBasedArchiveDescriptor.class.getName()
);
+ /**
+ * Constructs a JarFileBasedArchiveDescriptor
+ *
+ * @param archiveDescriptorFactory The factory creating this
+ * @param archiveUrl The url to the JAR file
+ * @param entry The prefix for entries within the JAR url
+ */
public JarFileBasedArchiveDescriptor(
ArchiveDescriptorFactory archiveDescriptorFactory,
URL archiveUrl,
@@ -87,7 +94,7 @@ public class JarFileBasedArchiveDescriptor extends AbstractArchiveDescriptor {
// This algorithm assumes that the zipped file is only the URL root (including entry), not
// just any random entry
try {
- InputStream is = new BufferedInputStream( jarFile.getInputStream( zipEntry ) );
+ final InputStream is = new BufferedInputStream( jarFile.getInputStream( zipEntry ) );
try {
final JarInputStream jarInputStream = new JarInputStream( is );
ZipEntry subZipEntry = jarInputStream.getNextEntry();
@@ -173,7 +180,7 @@ public class JarFileBasedArchiveDescriptor extends AbstractArchiveDescriptor {
private JarFile resolveJarFileReference() {
try {
- String filePart = getArchiveUrl().getFile();
+ final String filePart = getArchiveUrl().getFile();
if ( filePart != null && filePart.indexOf( ' ' ) != -1 ) {
// unescaped (from the container), keep as is
return new JarFile( getArchiveUrl().getFile() );
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarInputStreamBasedArchiveDescriptor.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarInputStreamBasedArchiveDescriptor.java
index 3b7b338535..6a39400040 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarInputStreamBasedArchiveDescriptor.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarInputStreamBasedArchiveDescriptor.java
@@ -52,6 +52,13 @@ public class JarInputStreamBasedArchiveDescriptor extends AbstractArchiveDescrip
JarInputStreamBasedArchiveDescriptor.class.getName()
);
+ /**
+ * Constructs a JarInputStreamBasedArchiveDescriptor
+ *
+ * @param archiveDescriptorFactory The factory creating this
+ * @param url The url to the JAR file
+ * @param entry The prefix for entries within the JAR url
+ */
public JarInputStreamBasedArchiveDescriptor(
ArchiveDescriptorFactory archiveDescriptorFactory,
URL url,
@@ -74,7 +81,7 @@ public class JarInputStreamBasedArchiveDescriptor extends AbstractArchiveDescrip
try {
JarEntry jarEntry;
while ( ( jarEntry = jarInputStream.getNextJarEntry() ) != null ) {
- String jarEntryName = jarEntry.getName();
+ final String jarEntryName = jarEntry.getName();
if ( getEntryBasePrefix() != null && ! jarEntryName.startsWith( getEntryBasePrefix() ) ) {
continue;
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarProtocolArchiveDescriptor.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarProtocolArchiveDescriptor.java
index 4eaa7d8748..d25c981308 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarProtocolArchiveDescriptor.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarProtocolArchiveDescriptor.java
@@ -38,6 +38,13 @@ import org.hibernate.jpa.boot.archive.spi.ArchiveDescriptorFactory;
public class JarProtocolArchiveDescriptor implements ArchiveDescriptor {
private final ArchiveDescriptor delegateDescriptor;
+ /**
+ * Constructs a JarProtocolArchiveDescriptor
+ *
+ * @param archiveDescriptorFactory The factory creating this
+ * @param url The url to the JAR file
+ * @param incomingEntry The prefix for entries within the JAR url
+ */
public JarProtocolArchiveDescriptor(
ArchiveDescriptorFactory archiveDescriptorFactory,
URL url,
@@ -60,7 +67,7 @@ public class JarProtocolArchiveDescriptor implements ArchiveDescriptor {
subEntry = urlFile.substring( subEntryIndex + 1 );
}
- URL fileUrl = archiveDescriptorFactory.getJarURLFromURLEntry( url, subEntry );
+ final URL fileUrl = archiveDescriptorFactory.getJarURLFromURLEntry( url, subEntry );
delegateDescriptor = archiveDescriptorFactory.buildArchiveDescriptor( fileUrl, subEntry );
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/StandardArchiveDescriptorFactory.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/StandardArchiveDescriptorFactory.java
index e502570140..5b974c2a12 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/StandardArchiveDescriptorFactory.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/StandardArchiveDescriptorFactory.java
@@ -32,10 +32,15 @@ import org.hibernate.jpa.boot.archive.spi.ArchiveDescriptor;
import org.hibernate.jpa.boot.archive.spi.ArchiveDescriptorFactory;
/**
+ * Standard implementation of ArchiveDescriptorFactory
+ *
* @author Emmanuel Bernard
* @author Steve Ebersole
*/
public class StandardArchiveDescriptorFactory implements ArchiveDescriptorFactory {
+ /**
+ * Singleton access
+ */
public static final StandardArchiveDescriptorFactory INSTANCE = new StandardArchiveDescriptorFactory();
@Override
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/package-info.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/package-info.java
new file mode 100644
index 0000000000..7fe8de9a17
--- /dev/null
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * The internals of archive scanning support
+ */
+package org.hibernate.jpa.boot.archive.internal;
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/AbstractArchiveDescriptor.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/AbstractArchiveDescriptor.java
index 00f92c6a0b..4e69a02f6c 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/AbstractArchiveDescriptor.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/AbstractArchiveDescriptor.java
@@ -33,6 +33,8 @@ import org.hibernate.jpa.boot.archive.internal.ArchiveHelper;
import org.hibernate.jpa.boot.spi.InputStreamAccess;
/**
+ * Base support for ArchiveDescriptor implementors.
+ *
* @author Steve Ebersole
*/
public abstract class AbstractArchiveDescriptor implements ArchiveDescriptor {
@@ -57,6 +59,7 @@ public abstract class AbstractArchiveDescriptor implements ArchiveDescriptor {
return entryBasePrefix.startsWith( "/" ) ? entryBasePrefix.substring( 1 ) : entryBasePrefix;
}
+ @SuppressWarnings("UnusedDeclaration")
protected ArchiveDescriptorFactory getArchiveDescriptorFactory() {
return archiveDescriptorFactory;
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveContext.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveContext.java
index 8674cc6bb5..eeea27eca4 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveContext.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveContext.java
@@ -26,12 +26,32 @@ package org.hibernate.jpa.boot.archive.spi;
import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
/**
+ * Describes the context for visiting the entries within an archive
+ *
* @author Steve Ebersole
*/
public interface ArchiveContext {
+ /**
+ * The persistence-unit descriptor which led to this archive being scanned.
+ *
+ * @return The persistence-unit descriptor
+ */
public PersistenceUnitDescriptor getPersistenceUnitDescriptor();
+ /**
+ * Is the archive described (and being visited) the root url for the persistence-unit?
+ *
+ * @return {@code true} if it is the root url
+ */
public boolean isRootUrl();
+ /**
+ * Get the handler for the given entry, which generally is indicated by the entry type (a {@code .class} file, a
+ * mapping file, etc).
+ *
+ * @param entry The archive entry
+ *
+ * @return The appropriate handler for the entry
+ */
public ArchiveEntryHandler obtainArchiveEntryHandler(ArchiveEntry entry);
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptor.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptor.java
index b9d07dee0d..8cd12792b2 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptor.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptor.java
@@ -30,5 +30,10 @@ package org.hibernate.jpa.boot.archive.spi;
* @author Emmanuel Bernard
*/
public interface ArchiveDescriptor {
+ /**
+ * Perform visitation using the given context
+ *
+ * @param archiveContext The visitation context
+ */
public void visitArchive(ArchiveContext archiveContext);
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptorFactory.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptorFactory.java
index 441b531b25..937a34d546 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptorFactory.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptorFactory.java
@@ -31,9 +31,48 @@ import java.net.URL;
* @author Steve Ebersole
*/
public interface ArchiveDescriptorFactory {
+ /**
+ * Build a descriptor of the archive indicated by the given url
+ *
+ * @param url The url to the archive
+ *
+ * @return The descriptor
+ */
public ArchiveDescriptor buildArchiveDescriptor(URL url);
- public ArchiveDescriptor buildArchiveDescriptor(URL jarUrl, String entry);
+ /**
+ * Build a descriptor of the archive indicated by the path relative to the given url
+ *
+ * @param url The url to the archive
+ * @param path The path within the given url that refers to the archive
+ *
+ * @return The descriptor
+ */
+ public ArchiveDescriptor buildArchiveDescriptor(URL url, String path);
+
+ /**
+ * Given a URL which defines an entry within a JAR (really any "bundled archive" such as a jar file, zip, etc)
+ * and an entry within that JAR, find the URL to the JAR itself.
+ *
+ * @param url The URL to an entry within a JAR
+ * @param entry The entry that described the thing referred to by the URL relative to the JAR
+ *
+ * @return The URL to the JAR
+ *
+ * @throws IllegalArgumentException Generally indicates a problem with malformed urls.
+ */
public URL getJarURLFromURLEntry(URL url, String entry) throws IllegalArgumentException;
+
+ /**
+ * Not used!
+ *
+ * @param jarPath The jar path
+ *
+ * @return The url from the path?
+ *
+ * @deprecated Not used!
+ */
+ @Deprecated
+ @SuppressWarnings("UnusedDeclaration")
public URL getURLFromPath(String jarPath);
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntry.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntry.java
index 7d7e9185e0..eeaaf85f79 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntry.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntry.java
@@ -34,7 +34,7 @@ public interface ArchiveEntry {
/**
* Get the entry's name
*
- * @return
+ * @return The name
*/
public String getName();
@@ -42,14 +42,14 @@ public interface ArchiveEntry {
* Get the relative name of the entry within the archive. Typically what we are looking for here is
* the ClassLoader resource lookup name.
*
- * @return
+ * @return The name relative to the archive root
*/
public String getNameWithinArchive();
/**
* Get access to the stream for the entry
*
- * @return
+ * @return Obtain stream access to the entry
*/
public InputStreamAccess getStreamAccess();
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntryHandler.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntryHandler.java
index 3fce3402c0..3110b78c87 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntryHandler.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntryHandler.java
@@ -29,5 +29,11 @@ package org.hibernate.jpa.boot.archive.spi;
* @author Steve Ebersole
*/
public interface ArchiveEntryHandler {
+ /**
+ * Handle the entry
+ *
+ * @param entry The entry to handle
+ * @param context The visitation context
+ */
public void handleEntry(ArchiveEntry entry, ArchiveContext context);
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveException.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveException.java
index 1257502318..204ac79b00 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveException.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveException.java
@@ -26,14 +26,27 @@ package org.hibernate.jpa.boot.archive.spi;
import org.hibernate.HibernateException;
/**
+ * Indicates a problem accessing or visiting the archive
+ *
* @author Steve Ebersole
*/
public class ArchiveException extends HibernateException {
+ /**
+ * Constructs an ArchiveException
+ *
+ * @param message Message explaining the exception condition
+ */
public ArchiveException(String message) {
super( message );
}
- public ArchiveException(String message, Throwable root) {
- super( message, root );
+ /**
+ * Constructs an ArchiveException
+ *
+ * @param message Message explaining the exception condition
+ * @param cause The underlying cause
+ */
+ public ArchiveException(String message, Throwable cause) {
+ super( message, cause );
}
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/package-info.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/package-info.java
new file mode 100644
index 0000000000..0f7106647d
--- /dev/null
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/package-info.java
@@ -0,0 +1,15 @@
+/**
+ * Defines the SPI for support of "scanning" of "archives".
+ *
+ * Scanning might mean:
+ *
searching for classes/packages that define certain interfaces
+ *
locating named resources
+ *
+ * And "archive" might mean:
+ *
a {@code .jar} file
+ *
an exploded directory
+ *
an OSGi bundle
+ *
etc
+ *
+ */
+package org.hibernate.jpa.boot.archive.spi;
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java
index 0342df1de4..a172a9afb1 100644
--- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java
@@ -23,12 +23,6 @@
*/
package org.hibernate.jpa.boot.internal;
-import javax.persistence.AttributeConverter;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.EntityNotFoundException;
-import javax.persistence.PersistenceException;
-import javax.persistence.spi.PersistenceUnitTransactionType;
-import javax.sql.DataSource;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
@@ -55,6 +49,12 @@ import org.jboss.jandex.IndexView;
import org.jboss.jandex.Indexer;
import org.jboss.logging.Logger;
+import javax.persistence.AttributeConverter;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityNotFoundException;
+import javax.persistence.PersistenceException;
+import javax.persistence.spi.PersistenceUnitTransactionType;
+import javax.sql.DataSource;
import org.hibernate.Interceptor;
import org.hibernate.InvalidMappingException;
@@ -69,6 +69,7 @@ import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.registry.internal.ConfigLoader;
+import org.hibernate.boot.registry.selector.StrategyRegistrationProvider;
import org.hibernate.boot.registry.selector.spi.StrategySelector;
import org.hibernate.boot.spi.CacheRegionDefinition;
import org.hibernate.cfg.Configuration;
@@ -88,31 +89,34 @@ import org.hibernate.jaxb.spi.cfg.JaxbHibernateConfiguration;
import org.hibernate.jaxb.spi.cfg.JaxbHibernateConfiguration.JaxbSessionFactory.JaxbMapping;
import org.hibernate.internal.util.ValueHolder;
import org.hibernate.jpa.AvailableSettings;
+import org.hibernate.jpa.boot.scan.internal.StandardScanOptions;
+import org.hibernate.jpa.boot.scan.internal.StandardScanner;
+import org.hibernate.jpa.boot.scan.spi.ScanOptions;
+import org.hibernate.jpa.boot.scan.spi.ScanResult;
+import org.hibernate.jpa.boot.scan.spi.Scanner;
+import org.hibernate.jpa.boot.spi.ClassDescriptor;
import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder;
+import org.hibernate.jpa.boot.spi.InputStreamAccess;
import org.hibernate.jpa.boot.spi.IntegratorProvider;
+import org.hibernate.jpa.boot.spi.MappingFileDescriptor;
+import org.hibernate.jpa.boot.spi.NamedInputStream;
+import org.hibernate.jpa.boot.spi.PackageDescriptor;
import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
+import org.hibernate.jpa.boot.spi.StrategyRegistrationProviderList;
+import org.hibernate.jpa.boot.spi.TypeContributorList;
import org.hibernate.jpa.event.spi.JpaIntegrator;
import org.hibernate.jpa.internal.EntityManagerFactoryImpl;
import org.hibernate.jpa.internal.EntityManagerMessageLogger;
import org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator;
import org.hibernate.jpa.internal.util.LogHelper;
import org.hibernate.jpa.internal.util.PersistenceUnitTransactionTypeHelper;
-import org.hibernate.jpa.boot.scan.internal.StandardScanOptions;
-import org.hibernate.jpa.boot.scan.internal.StandardScanner;
-import org.hibernate.jpa.boot.spi.ClassDescriptor;
-import org.hibernate.jpa.boot.spi.InputStreamAccess;
-import org.hibernate.jpa.boot.spi.MappingFileDescriptor;
-import org.hibernate.jpa.boot.spi.NamedInputStream;
-import org.hibernate.jpa.boot.spi.PackageDescriptor;
-import org.hibernate.jpa.boot.scan.spi.ScanOptions;
-import org.hibernate.jpa.boot.scan.spi.ScanResult;
-import org.hibernate.jpa.boot.scan.spi.Scanner;
import org.hibernate.jpa.spi.IdentifierGeneratorStrategyProvider;
import org.hibernate.metamodel.MetadataBuilder;
import org.hibernate.metamodel.SessionFactoryBuilder;
import org.hibernate.metamodel.internal.source.annotations.util.JPADotNames;
import org.hibernate.metamodel.internal.source.annotations.util.JandexHelper;
import org.hibernate.metamodel.spi.MetadataImplementor;
+import org.hibernate.metamodel.spi.TypeContributor;
import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.secure.spi.GrantedPermission;
import org.hibernate.secure.spi.JaccService;
@@ -138,6 +142,16 @@ public class EntityManagerFactoryBuilderImpl implements EntityManagerFactoryBuil
* Names a {@link IntegratorProvider}
*/
public static final String INTEGRATOR_PROVIDER = "hibernate.integrator_provider";
+
+ /**
+ * Names a {@link StrategyRegistrationProviderList}
+ */
+ public static final String STRATEGY_REGISTRATION_PROVIDERS = "hibernate.strategy_registration_provider";
+
+ /**
+ * Names a {@link TypeContributorList}
+ */
+ public static final String TYPE_CONTRIBUTORS = "hibernate.type_contributors";
/**
* Names a Jandex {@link Index} instance to use.
@@ -553,11 +567,19 @@ public class EntityManagerFactoryBuilderImpl implements EntityManagerFactoryBuil
final IntegratorProvider integratorProvider = (IntegratorProvider) integrationSettings.get( INTEGRATOR_PROVIDER );
if ( integratorProvider != null ) {
- integrationSettings.remove( INTEGRATOR_PROVIDER );
for ( Integrator integrator : integratorProvider.getIntegrators() ) {
bootstrapServiceRegistryBuilder.with( integrator );
}
}
+
+ final StrategyRegistrationProviderList strategyRegistrationProviderList
+ = (StrategyRegistrationProviderList) integrationSettings.get( STRATEGY_REGISTRATION_PROVIDERS );
+ if ( strategyRegistrationProviderList != null ) {
+ for ( StrategyRegistrationProvider strategyRegistrationProvider : strategyRegistrationProviderList
+ .getStrategyRegistrationProviders() ) {
+ bootstrapServiceRegistryBuilder.withStrategySelectors( strategyRegistrationProvider );
+ }
+ }
// TODO: If providedClassLoader is present (OSGi, etc.) *and*
// an APP_CLASSLOADER is provided, should throw an exception or
@@ -1316,6 +1338,16 @@ public class EntityManagerFactoryBuilderImpl implements EntityManagerFactoryBuil
for ( String packageName : mockMetadataSources.packageNames ) {
cfg.addPackage( packageName );
}
+
+ final TypeContributorList typeContributorList
+ = (TypeContributorList) configurationValues.get( TYPE_CONTRIBUTORS );
+ if ( typeContributorList != null ) {
+ configurationValues.remove( TYPE_CONTRIBUTORS );
+ for ( TypeContributor typeContributor : typeContributorList.getTypeContributors() ) {
+ cfg.registerTypeContributor( typeContributor );
+ }
+ }
+
return cfg;
}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/StrategyRegistrationProviderList.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/StrategyRegistrationProviderList.java
new file mode 100644
index 0000000000..24ad604705
--- /dev/null
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/StrategyRegistrationProviderList.java
@@ -0,0 +1,37 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2012, Red Hat Inc. 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 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.jpa.boot.spi;
+
+import java.util.List;
+
+import org.hibernate.boot.registry.selector.StrategyRegistrationProvider;
+
+/**
+ * @author Brett Meyer
+ *
+ * TODO: Not a fan of this name or entry point into EMFBuilderImpl
+ */
+public interface StrategyRegistrationProviderList {
+ public List getStrategyRegistrationProviders();
+}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/TypeContributorList.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/TypeContributorList.java
new file mode 100644
index 0000000000..e984c70257
--- /dev/null
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/TypeContributorList.java
@@ -0,0 +1,37 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2012, Red Hat Inc. 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 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.jpa.boot.spi;
+
+import java.util.List;
+
+import org.hibernate.metamodel.spi.TypeContributor;
+
+/**
+ * @author Brett Meyer
+ *
+ * TODO: Not a fan of this name or entry point into EMFBuilderImpl
+ */
+public interface TypeContributorList {
+ public List getTypeContributors();
+}
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/package-info.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/package-info.java
new file mode 100644
index 0000000000..36f0de3969
--- /dev/null
+++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * Defines Hibernate implementation of Java Persistence specification.
+ */
+package org.hibernate.jpa;
diff --git a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java
index bf3be224c3..89360d4a47 100755
--- a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java
+++ b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java
@@ -186,7 +186,7 @@ public class EntityManagerTest extends BaseEntityManagerFunctionalTestCase {
public void testContains() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
- Integer nonManagedObject = new Integer( 4 );
+ Integer nonManagedObject = Integer.valueOf( 4 );
try {
em.contains( nonManagedObject );
fail( "Should have raised an exception" );
diff --git a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/callbacks/CallbackAndDirtyTest.java b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/callbacks/CallbackAndDirtyTest.java
index 2e171c32d5..eb87a016e6 100644
--- a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/callbacks/CallbackAndDirtyTest.java
+++ b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/callbacks/CallbackAndDirtyTest.java
@@ -96,9 +96,9 @@ public class CallbackAndDirtyTest extends BaseEntityManagerFunctionalTestCase {
manager.getTransaction().commit();
manager.getTransaction().begin();
- mark = manager.find( Employee.class, new Long( ids[0] ) );
- joe = manager.find( Customer.class, new Long( ids[1] ) );
- yomomma = manager.find( Person.class, new Long( ids[2] ) );
+ mark = manager.find( Employee.class, Long.valueOf( ids[0] ) );
+ joe = manager.find( Customer.class, Long.valueOf( ids[1] ) );
+ yomomma = manager.find( Person.class, Long.valueOf( ids[2] ) );
mark.setZip( "30306" );
assertEquals( 1, manager.createQuery( "select p from Person p where p.zip = '30306'" ).getResultList().size() );
diff --git a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/packaging/PackagedEntityManagerTest.java b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/packaging/PackagedEntityManagerTest.java
index 6384c1d6ed..8e0b857ec8 100644
--- a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/packaging/PackagedEntityManagerTest.java
+++ b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/packaging/PackagedEntityManagerTest.java
@@ -470,7 +470,7 @@ public class PackagedEntityManagerTest extends PackagingTestCase {
em = emf.createEntityManager();
em.getTransaction().begin();
s = em.find( Scooter.class, s.getModel() );
- assertEquals( new Long( 85 ), s.getSpeed() );
+ assertEquals( Long.valueOf( 85 ), s.getSpeed() );
em.remove( s );
em.getTransaction().commit();
em.close();
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/AuditJoinTable.java b/hibernate-envers/src/main/java/org/hibernate/envers/AuditJoinTable.java
index 894bcbc559..2a22d3a9f1 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/AuditJoinTable.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/AuditJoinTable.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -22,11 +22,12 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.envers;
+
+import javax.persistence.JoinColumn;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
-import javax.persistence.JoinColumn;
/**
* @author Adam Warski (adam at warski dot org)
@@ -34,25 +35,25 @@ import javax.persistence.JoinColumn;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface AuditJoinTable {
- /**
- * @return Name of the join table. Defaults to a concatenation of the names of the primary table of the entity
- * owning the association and of the primary table of the entity referenced by the association.
- */
- String name() default "";
+ /**
+ * Name of the join table. Defaults to a concatenation of the names of the primary table of the entity
+ * owning the association and of the primary table of the entity referenced by the association.
+ */
+ String name() default "";
- /**
- * @return The schema of the join table. Defaults to the schema of the entity owning the association.
- */
- String schema() default "";
+ /**
+ * The schema of the join table. Defaults to the schema of the entity owning the association.
+ */
+ String schema() default "";
- /**
- * @return The catalog of the join table. Defaults to the catalog of the entity owning the association.
- */
- String catalog() default "";
+ /**
+ * The catalog of the join table. Defaults to the catalog of the entity owning the association.
+ */
+ String catalog() default "";
- /**
- * @return The foreign key columns of the join table which reference the primary table of the entity that does not
- * own the association (i.e. the inverse side of the association).
- */
- JoinColumn[] inverseJoinColumns() default {};
+ /**
+ * The foreign key columns of the join table which reference the primary table of the entity that does not
+ * own the association (i.e. the inverse side of the association).
+ */
+ JoinColumn[] inverseJoinColumns() default {};
}
\ No newline at end of file
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/AuditMappedBy.java b/hibernate-envers/src/main/java/org/hibernate/envers/AuditMappedBy.java
index e5b1c4aeb4..8c86beea7e 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/AuditMappedBy.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/AuditMappedBy.java
@@ -1,4 +1,5 @@
package org.hibernate.envers;
+
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -11,7 +12,7 @@ import java.lang.annotation.Target;
* the many side. Then, Envers won't use a join table to audit this relation, but will store changes as in a normal
* bi-directional relation.
*
- *
+ *
*
* This annotation is experimental and may change in future releases.
*
@@ -21,16 +22,17 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface AuditMappedBy {
- /**
- * @return Name of the property in the related entity which maps back to this entity. The property should be
- * mapped with {@code @ManyToOne} and {@code @Column(insertable=false, updatable=false)}.
- */
- String mappedBy();
+ /**
+ * Name of the property in the related entity which maps back to this entity. The property should be
+ * mapped with {@code @ManyToOne} and {@code @Column(insertable=false, updatable=false)}.
+ */
+ String mappedBy();
- /**
- * @return Name of the property in the related entity which maps to the position column. Should be specified only
- * for indexed collection, when @{@link org.hibernate.annotations.IndexColumn} is used on the collection.
- * The property should be mapped with {@code @Column(insertable=false, updatable=false)}.
- */
- String positionMappedBy() default "";
+ /**
+ * Name of the property in the related entity which maps to the position column. Should be specified only
+ * for indexed collection, when @{@link org.hibernate.annotations.IndexColumn} or
+ * {@link javax.persistence.OrderColumn} is used on the collection. The property should be mapped with
+ * {@code @Column(insertable=false, updatable=false)}.
+ */
+ String positionMappedBy() default "";
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverride.java b/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverride.java
index 96dfea8dd1..0b5059fdad 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverride.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverride.java
@@ -1,7 +1,30 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2013, Red Hat Inc. 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 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.envers;
+
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
-import javax.persistence.MappedSuperclass;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
@@ -10,43 +33,44 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* The {@code AuditingOverride} annotation is used to override the auditing
- * behavior of a superclass or single property inherited from {@link MappedSuperclass}
+ * behavior of a superclass or single property inherited from {@link javax.persistence.MappedSuperclass}
* type, or attribute inside an embedded component.
*
* @author Erik-Berndt Scheper
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
+ *
* @see javax.persistence.Embedded
* @see javax.persistence.Embeddable
- * @see javax.persistence.MappedSuperclass
+ * @see javax.persistence.MappedSuperclass
* @see javax.persistence.AssociationOverride
* @see AuditJoinTable
*/
-@Target({ TYPE, METHOD, FIELD })
+@Target({TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface AuditOverride {
/**
- * @return Name of the field (or property) whose mapping is being overridden. Allows empty value if
+ * Name of the field (or property) whose mapping is being overridden. Allows empty value if
* {@link AuditOverride} is used to change auditing behavior of all attributes inherited from
- * {@link MappedSuperclass} type.
+ * {@link javax.persistence.MappedSuperclass} type.
*/
String name() default "";
/**
- * @return Indicates if the field (or property) is audited; defaults to {@code true}.
+ * Indicates if the field (or property) is audited; defaults to {@code true}.
*/
boolean isAudited() default true;
/**
- * @return New {@link AuditJoinTable} used for this field (or property). Its value
+ * New {@link AuditJoinTable} used for this field (or property). Its value
* is ignored if {@link #isAudited()} equals to {@code false}.
*/
AuditJoinTable auditJoinTable() default @AuditJoinTable;
/**
- * @return Specifies class which field (or property) mapping is being overridden. Required if
- * {@link AuditOverride} is used to change auditing behavior of attributes inherited from {@link MappedSuperclass}
- * type.
+ * Specifies class which field (or property) mapping is being overridden. Required if
+ * {@link AuditOverride} is used to change auditing behavior of attributes inherited from
+ * {@link javax.persistence.MappedSuperclass} type.
*/
Class forClass() default void.class;
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverrides.java b/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverrides.java
index b4b4e095de..4f86cee9ae 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverrides.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverrides.java
@@ -1,4 +1,28 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2013, Red Hat Inc. 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 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.envers;
+
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@@ -21,11 +45,11 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
* @see AuditJoinTable
* @see AuditOverride
*/
-@Target({ TYPE, METHOD, FIELD })
+@Target({TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface AuditOverrides {
/**
- * @return An array of {@link AuditOverride} values, to define the new auditing
+ * An array of {@link AuditOverride} values, to define the new auditing
* behavior.
*/
AuditOverride[] value();
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/AuditReader.java b/hibernate-envers/src/main/java/org/hibernate/envers/AuditReader.java
index 498a8ff22d..1230339e2b 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/AuditReader.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/AuditReader.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -40,207 +40,241 @@ import org.hibernate.envers.query.AuditQueryCreator;
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
public interface AuditReader {
- /**
- * Find an entity by primary key at the given revision.
- * @param cls Class of the entity.
- * @param primaryKey Primary key of the entity.
- * @param revision Revision in which to get the entity.
- * @return The found entity instance at the given revision (its properties may be partially filled
- * if not all properties are audited) or null, if an entity with that id didn't exist at that
- * revision.
- * @throws IllegalArgumentException If cls or primaryKey is null or revision is less or equal to 0.
- * @throws NotAuditedException When entities of the given class are not audited.
- * @throws IllegalStateException If the associated entity manager is closed.
- */
- T find(Class cls, Object primaryKey, Number revision) throws
- IllegalArgumentException, NotAuditedException, IllegalStateException;
-
- /**
- * Find an entity by primary key at the given revision with the specified entityName.
- * @param cls Class of the entity.
- * @param entityName Name of the entity (if can't be guessed basing on the {@code cls}).
- * @param primaryKey Primary key of the entity.
- * @param revision Revision in which to get the entity.
- * @return The found entity instance at the given revision (its properties may be partially filled
- * if not all properties are audited) or null, if an entity with that id didn't exist at that
- * revision.
- * @throws IllegalArgumentException If cls or primaryKey is null or revision is less or equal to 0.
- * @throws NotAuditedException When entities of the given class are not audited.
- * @throws IllegalStateException If the associated entity manager is closed.
- */
- T find(Class cls, String entityName, Object primaryKey,
+ /**
+ * Find an entity by primary key at the given revision.
+ *
+ * @param cls Class of the entity.
+ * @param primaryKey Primary key of the entity.
+ * @param revision Revision in which to get the entity.
+ * @param The type of the entity to find
+ *
+ * @return The found entity instance at the given revision (its properties may be partially filled
+ * if not all properties are audited) or null, if an entity with that id didn't exist at that
+ * revision.
+ *
+ * @throws IllegalArgumentException If cls or primaryKey is null or revision is less or equal to 0.
+ * @throws NotAuditedException When entities of the given class are not audited.
+ * @throws IllegalStateException If the associated entity manager is closed.
+ */
+ T find(Class cls, Object primaryKey, Number revision) throws
+ IllegalArgumentException, NotAuditedException, IllegalStateException;
+
+ /**
+ * Find an entity by primary key at the given revision with the specified entityName.
+ *
+ * @param cls Class of the entity.
+ * @param entityName Name of the entity (if can't be guessed basing on the {@code cls}).
+ * @param primaryKey Primary key of the entity.
+ * @param revision Revision in which to get the entity.
+ * @param The type of the entity to find
+ *
+ * @return The found entity instance at the given revision (its properties may be partially filled
+ * if not all properties are audited) or null, if an entity with that id didn't exist at that
+ * revision.
+ *
+ * @throws IllegalArgumentException If cls or primaryKey is null or revision is less or equal to 0.
+ * @throws NotAuditedException When entities of the given class are not audited.
+ * @throws IllegalStateException If the associated entity manager is closed.
+ */
+ T find(
+ Class cls, String entityName, Object primaryKey,
Number revision) throws IllegalArgumentException,
NotAuditedException, IllegalStateException;
- /**
- * Find an entity by primary key at the given revision with the specified entityName,
- * possibly including deleted entities in the search.
- * @param cls Class of the entity.
- * @param entityName Name of the entity (if can't be guessed basing on the {@code cls}).
- * @param primaryKey Primary key of the entity.
- * @param revision Revision in which to get the entity.
- * @param includeDeletions Whether to include deleted entities in the search.
- * @return The found entity instance at the given revision (its properties may be partially filled
- * if not all properties are audited) or null, if an entity with that id didn't exist at that
- * revision.
- * @throws IllegalArgumentException If cls or primaryKey is null or revision is less or equal to 0.
- * @throws NotAuditedException When entities of the given class are not audited.
- * @throws IllegalStateException If the associated entity manager is closed.
- */
- T find(Class cls, String entityName, Object primaryKey,
+ /**
+ * Find an entity by primary key at the given revision with the specified entityName,
+ * possibly including deleted entities in the search.
+ *
+ * @param cls Class of the entity.
+ * @param entityName Name of the entity (if can't be guessed basing on the {@code cls}).
+ * @param primaryKey Primary key of the entity.
+ * @param revision Revision in which to get the entity.
+ * @param includeDeletions Whether to include deleted entities in the search.
+ * @param The type of the entity to find
+ *
+ * @return The found entity instance at the given revision (its properties may be partially filled
+ * if not all properties are audited) or null, if an entity with that id didn't exist at that
+ * revision.
+ *
+ * @throws IllegalArgumentException If cls or primaryKey is null or revision is less or equal to 0.
+ * @throws NotAuditedException When entities of the given class are not audited.
+ * @throws IllegalStateException If the associated entity manager is closed.
+ */
+ T find(
+ Class cls, String entityName, Object primaryKey,
Number revision, boolean includeDeletions) throws IllegalArgumentException,
NotAuditedException, IllegalStateException;
-
- /**
- * Get a list of revision numbers, at which an entity was modified.
- * @param cls Class of the entity.
- * @param primaryKey Primary key of the entity.
- * @return A list of revision numbers, at which the entity was modified, sorted in ascending order (so older
- * revisions come first).
- * @throws NotAuditedException When entities of the given class are not audited.
- * @throws IllegalArgumentException If cls or primaryKey is null.
- * @throws IllegalStateException If the associated entity manager is closed.
- */
- List getRevisions(Class> cls, Object primaryKey)
- throws IllegalArgumentException, NotAuditedException, IllegalStateException;
-
- /**
- * Get a list of revision numbers, at which an entity was modified, looking by entityName.
- * @param cls Class of the entity.
- * @param entityName Name of the entity (if can't be guessed basing on the {@code cls}).
- * @param primaryKey Primary key of the entity.
- * @return A list of revision numbers, at which the entity was modified, sorted in ascending order (so older
- * revisions come first).
- * @throws NotAuditedException When entities of the given class are not audited.
- * @throws IllegalArgumentException If cls or primaryKey is null.
- * @throws IllegalStateException If the associated entity manager is closed.
- */
- List getRevisions(Class> cls, String entityName, Object primaryKey)
+
+ /**
+ * Get a list of revision numbers, at which an entity was modified.
+ *
+ * @param cls Class of the entity.
+ * @param primaryKey Primary key of the entity.
+ *
+ * @return A list of revision numbers, at which the entity was modified, sorted in ascending order (so older
+ * revisions come first).
+ *
+ * @throws NotAuditedException When entities of the given class are not audited.
+ * @throws IllegalArgumentException If cls or primaryKey is null.
+ * @throws IllegalStateException If the associated entity manager is closed.
+ */
+ List getRevisions(Class> cls, Object primaryKey)
+ throws IllegalArgumentException, NotAuditedException, IllegalStateException;
+
+ /**
+ * Get a list of revision numbers, at which an entity was modified, looking by entityName.
+ *
+ * @param cls Class of the entity.
+ * @param entityName Name of the entity (if can't be guessed basing on the {@code cls}).
+ * @param primaryKey Primary key of the entity.
+ *
+ * @return A list of revision numbers, at which the entity was modified, sorted in ascending order (so older
+ * revisions come first).
+ *
+ * @throws NotAuditedException When entities of the given class are not audited.
+ * @throws IllegalArgumentException If cls or primaryKey is null.
+ * @throws IllegalStateException If the associated entity manager is closed.
+ */
+ List getRevisions(Class> cls, String entityName, Object primaryKey)
throws IllegalArgumentException, NotAuditedException,
IllegalStateException;
- /**
- * Get the date, at which a revision was created.
- * @param revision Number of the revision for which to get the date.
- * @return Date of commiting the given revision.
- * @throws IllegalArgumentException If revision is less or equal to 0.
- * @throws RevisionDoesNotExistException If the revision does not exist.
- * @throws IllegalStateException If the associated entity manager is closed.
- */
- Date getRevisionDate(Number revision) throws IllegalArgumentException, RevisionDoesNotExistException,
- IllegalStateException;
-
- /**
- * Gets the revision number, that corresponds to the given date. More precisely, returns
- * the number of the highest revision, which was created on or before the given date. So:
- * getRevisionDate(getRevisionNumberForDate(date)) <= date and
- * getRevisionDate(getRevisionNumberForDate(date)+1) > date.
- * @param date Date for which to get the revision.
- * @return Revision number corresponding to the given date.
- * @throws IllegalStateException If the associated entity manager is closed.
- * @throws RevisionDoesNotExistException If the given date is before the first revision.
- * @throws IllegalArgumentException If date is null.
- */
- Number getRevisionNumberForDate(Date date) throws IllegalStateException, RevisionDoesNotExistException,
- IllegalArgumentException;
-
- /**
- * A helper method; should be used only if a custom revision entity is used. See also {@link RevisionEntity}.
- * @param revisionEntityClass Class of the revision entity. Should be annotated with {@link RevisionEntity}.
- * @param revision Number of the revision for which to get the data.
- * @return Entity containing data for the given revision.
- * @throws IllegalArgumentException If revision is less or equal to 0 or if the class of the revision entity
- * is invalid.
- * @throws RevisionDoesNotExistException If the revision does not exist.
- * @throws IllegalStateException If the associated entity manager is closed.
- */
- T findRevision(Class revisionEntityClass, Number revision) throws IllegalArgumentException,
- RevisionDoesNotExistException, IllegalStateException;
-
- /**
- * Find a map of revisions using the revision numbers specified.
- *
- * @param revisionEntityClass
- * Class of the revision entity. Should be annotated with
- * {@link RevisionEntity}.
- * @param revisions
- * Revision numbers of the revision for which to get the data.
- * @return A map of revision number and the given revision entity.
- * @throws IllegalArgumentException
- * If a revision number is less or equal to 0 or if the class of
- * the revision entity is invalid.
- * @throws IllegalStateException
- * If the associated entity manager is closed.
+ /**
+ * Get the date, at which a revision was created.
+ *
+ * @param revision Number of the revision for which to get the date.
+ *
+ * @return Date of commiting the given revision.
+ *
+ * @throws IllegalArgumentException If revision is less or equal to 0.
+ * @throws RevisionDoesNotExistException If the revision does not exist.
+ * @throws IllegalStateException If the associated entity manager is closed.
*/
- Map findRevisions(Class revisionEntityClass,
+ Date getRevisionDate(Number revision) throws IllegalArgumentException, RevisionDoesNotExistException,
+ IllegalStateException;
+
+ /**
+ * Gets the revision number, that corresponds to the given date. More precisely, returns
+ * the number of the highest revision, which was created on or before the given date. So:
+ * getRevisionDate(getRevisionNumberForDate(date)) <= date and
+ * getRevisionDate(getRevisionNumberForDate(date)+1) > date.
+ *
+ * @param date Date for which to get the revision.
+ *
+ * @return Revision number corresponding to the given date.
+ *
+ * @throws IllegalStateException If the associated entity manager is closed.
+ * @throws RevisionDoesNotExistException If the given date is before the first revision.
+ * @throws IllegalArgumentException If date is null.
+ */
+ Number getRevisionNumberForDate(Date date) throws IllegalStateException, RevisionDoesNotExistException,
+ IllegalArgumentException;
+
+ /**
+ * A helper method; should be used only if a custom revision entity is used. See also {@link RevisionEntity}.
+ *
+ * @param revisionEntityClass Class of the revision entity. Should be annotated with {@link RevisionEntity}.
+ * @param revision Number of the revision for which to get the data.
+ * @param The type of the revision entity to find
+ *
+ * @return Entity containing data for the given revision.
+ *
+ * @throws IllegalArgumentException If revision is less or equal to 0 or if the class of the revision entity
+ * is invalid.
+ * @throws RevisionDoesNotExistException If the revision does not exist.
+ * @throws IllegalStateException If the associated entity manager is closed.
+ */
+ T findRevision(Class revisionEntityClass, Number revision) throws IllegalArgumentException,
+ RevisionDoesNotExistException, IllegalStateException;
+
+ /**
+ * Find a map of revisions using the revision numbers specified.
+ *
+ * @param revisionEntityClass Class of the revision entity. Should be annotated with
+ * {@link RevisionEntity}.
+ * @param revisions Revision numbers of the revision for which to get the data.
+ * @param The type of the revision entity to find
+ *
+ * @return A map of revision number and the given revision entity.
+ *
+ * @throws IllegalArgumentException If a revision number is less or equal to 0 or if the class of
+ * the revision entity is invalid.
+ * @throws IllegalStateException If the associated entity manager is closed.
+ */
+ Map findRevisions(
+ Class revisionEntityClass,
Set revisions) throws IllegalArgumentException,
IllegalStateException;
-
+
/**
* Gets an instance of the current revision entity, to which any entries in the audit tables will be bound.
* Please note the if {@code persist} is {@code false}, and no audited entities are modified in this session,
* then the obtained revision entity instance won't be persisted. If {@code persist} is {@code true}, the revision
* entity instance will always be persisted, regardless of whether audited entities are changed or not.
+ *
* @param revisionEntityClass Class of the revision entity. Should be annotated with {@link RevisionEntity}.
* @param persist If the revision entity is not yet persisted, should it become persisted. This way, the primary
* identifier (id) will be filled (if it's assigned by the DB) and available, but the revision entity will be
* persisted even if there are no changes to audited entities. Otherwise, the revision number (id) can be
* {@code null}.
+ * @param The type of the revision entity to find
+ *
* @return The current revision entity, to which any entries in the audit tables will be bound.
*/
T getCurrentRevision(Class revisionEntityClass, boolean persist);
- /**
- *
- * @return A query creator, associated with this AuditReader instance, with which queries can be
- * created and later executed. Shouldn't be used after the associated Session or EntityManager
- * is closed.
- */
- AuditQueryCreator createQuery();
+ /**
+ * Creates an audit query
+ *
+ * @return A query creator, associated with this AuditReader instance, with which queries can be
+ * created and later executed. Shouldn't be used after the associated Session or EntityManager
+ * is closed.
+ */
+ AuditQueryCreator createQuery();
- /**
+ /**
* Checks if the entityClass was configured to be audited. Calling
* isEntityNameAudited() with the string of the class name will return the
* same value.
- *
- * @param entityClass
- * Class of the entity asking for audit support
- * @return true if the entityClass is audited.
- */
- boolean isEntityClassAudited(Class> entityClass);
-
+ *
+ * @param entityClass Class of the entity asking for audit support
+ *
+ * @return true if the entityClass is audited.
+ */
+ boolean isEntityClassAudited(Class> entityClass);
+
/**
* Checks if the entityName was configured to be audited.
- *
+ *
* @param entityName EntityName of the entity asking for audit support.
+ *
* @return true if the entityName is audited.
*/
- boolean isEntityNameAudited(String entityName);
+ boolean isEntityNameAudited(String entityName);
/**
- *
- * @param entity
- * that was obtained previously from the same AuditReader.
- *
+ * @param entity that was obtained previously from the same AuditReader.
+ *
* @return the entityName for the given entity, null in case the entity is
* not associated with this AuditReader instance.
*/
String getEntityName(Object primaryKey, Number revision, Object entity)
throws HibernateException;
- /**
- * @return Basic implementation of {@link CrossTypeRevisionChangesReader} interface. Raises an exception if the default
- * mechanism of tracking entity names modified during revisions has not been enabled.
- * @throws AuditException If none of the following conditions is satisfied:
- *
- *
org.hibernate.envers.track_entities_changed_in_revision
- * parameter is set to true.
- *
Custom revision entity (annotated with {@link RevisionEntity})
- * extends {@link DefaultTrackingModifiedEntitiesRevisionEntity} base class.
- *
Custom revision entity (annotated with {@link RevisionEntity}) encapsulates a field
- * marked with {@link ModifiedEntityNames} interface.
- *
- */
- public CrossTypeRevisionChangesReader getCrossTypeRevisionChangesReader() throws AuditException;
+ /**
+ * @return Basic implementation of {@link CrossTypeRevisionChangesReader} interface. Raises an exception if the default
+ * mechanism of tracking entity names modified during revisions has not been enabled.
+ *
+ * @throws AuditException If none of the following conditions is satisfied:
+ *
+ *
org.hibernate.envers.track_entities_changed_in_revision
+ * parameter is set to true.
+ *
Custom revision entity (annotated with {@link RevisionEntity})
+ * extends {@link DefaultTrackingModifiedEntitiesRevisionEntity} base class.
+ *
Custom revision entity (annotated with {@link RevisionEntity}) encapsulates a field
+ * marked with {@link ModifiedEntityNames} interface.
+ *
+ */
+ public CrossTypeRevisionChangesReader getCrossTypeRevisionChangesReader() throws AuditException;
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/AuditReaderFactory.java b/hibernate-envers/src/main/java/org/hibernate/envers/AuditReaderFactory.java
index 74302e7fb9..c19facf355 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/AuditReaderFactory.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/AuditReaderFactory.java
@@ -38,20 +38,25 @@ import org.hibernate.event.spi.PostInsertEventListener;
* @author Adam Warski (adam at warski dot org)
*/
public class AuditReaderFactory {
- private AuditReaderFactory() { }
+ private AuditReaderFactory() {
+ }
- /**
- * Create an audit reader associated with an open session.
- * @param session An open session.
- * @return An audit reader associated with the given sesison. It shouldn't be used
- * after the session is closed.
- * @throws AuditException When the given required listeners aren't installed.
- */
- public static AuditReader get(Session session) throws AuditException {
- SessionImplementor sessionImpl;
- if (!(session instanceof SessionImplementor)) {
+ /**
+ * Create an audit reader associated with an open session.
+ *
+ * @param session An open session.
+ *
+ * @return An audit reader associated with the given sesison. It shouldn't be used
+ * after the session is closed.
+ *
+ * @throws AuditException When the given required listeners aren't installed.
+ */
+ public static AuditReader get(Session session) throws AuditException {
+ SessionImplementor sessionImpl;
+ if ( !(session instanceof SessionImplementor) ) {
sessionImpl = (SessionImplementor) session.getSessionFactory().getCurrentSession();
- } else {
+ }
+ else {
sessionImpl = (SessionImplementor) session;
}
@@ -61,37 +66,41 @@ public class AuditReaderFactory {
.getServiceRegistry()
.getService( EventListenerRegistry.class );
- for ( PostInsertEventListener listener : listenerRegistry.getEventListenerGroup( EventType.POST_INSERT ).listeners() ) {
+ for ( PostInsertEventListener listener : listenerRegistry.getEventListenerGroup( EventType.POST_INSERT )
+ .listeners() ) {
if ( listener instanceof EnversListener ) {
// todo : slightly different from original code in that I am not checking the other listener groups...
return new AuditReaderImpl(
- ( (EnversListener) listener ).getAuditConfiguration(),
+ ((EnversListener) listener).getAuditConfiguration(),
session,
sessionImpl
);
}
}
- throw new AuditException( "Envers listeners were not properly registered" );
- }
+ throw new AuditException( "Envers listeners were not properly registered" );
+ }
- /**
- * Create an audit reader associated with an open entity manager.
- * @param entityManager An open entity manager.
- * @return An audit reader associated with the given entity manager. It shouldn't be used
- * after the entity manager is closed.
- * @throws AuditException When the given entity manager is not based on Hibernate, or if the required
- * listeners aren't installed.
- */
- public static AuditReader get(EntityManager entityManager) throws AuditException {
- if (entityManager.getDelegate() instanceof Session) {
- return get((Session) entityManager.getDelegate());
- }
+ /**
+ * Create an audit reader associated with an open entity manager.
+ *
+ * @param entityManager An open entity manager.
+ *
+ * @return An audit reader associated with the given entity manager. It shouldn't be used
+ * after the entity manager is closed.
+ *
+ * @throws AuditException When the given entity manager is not based on Hibernate, or if the required
+ * listeners aren't installed.
+ */
+ public static AuditReader get(EntityManager entityManager) throws AuditException {
+ if ( entityManager.getDelegate() instanceof Session ) {
+ return get( (Session) entityManager.getDelegate() );
+ }
- if (entityManager.getDelegate() instanceof EntityManager) {
- return get((EntityManager) entityManager.getDelegate());
- }
+ if ( entityManager.getDelegate() instanceof EntityManager ) {
+ return get( (EntityManager) entityManager.getDelegate() );
+ }
- throw new AuditException("Hibernate EntityManager not present!");
- }
+ throw new AuditException( "Hibernate EntityManager not present!" );
+ }
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/AuditTable.java b/hibernate-envers/src/main/java/org/hibernate/envers/AuditTable.java
index dfeaed32cc..d4e5b91c23 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/AuditTable.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/AuditTable.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.envers;
+
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -33,15 +34,18 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface AuditTable {
- String value();
+ /**
+ * The name of the table
+ */
+ String value();
- /**
- * @return The schema of the table. Defaults to the schema of the annotated entity.
- */
- String schema() default "";
+ /**
+ * The schema of the table. Defaults to the schema of the annotated entity.
+ */
+ String schema() default "";
- /**
- * @return The catalog of the table. Defaults to the catalog of the annotated entity.
- */
- String catalog() default "";
+ /**
+ * The catalog of the table. Defaults to the catalog of the annotated entity.
+ */
+ String catalog() default "";
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/Audited.java b/hibernate-envers/src/main/java/org/hibernate/envers/Audited.java
index f37e768677..5afb0f5905 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/Audited.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/Audited.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.envers;
+
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -30,6 +31,7 @@ import java.lang.annotation.Target;
/**
* When applied to a class, indicates that all of its properties should be audited.
* When applied to a field, indicates that this field should be audited.
+ *
* @author Adam Warski (adam at warski dot org)
* @author Tomasz Bech
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
@@ -38,33 +40,37 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
public @interface Audited {
- ModificationStore modStore() default ModificationStore.FULL;
+ /**
+ * Specifies modification store to use
+ */
+ ModificationStore modStore() default ModificationStore.FULL;
/**
- * @return Specifies if the entity that is the target of the relation should be audited or not. If not, then when
+ * Specifies if the entity that is the target of the relation should be audited or not. If not, then when
* reading a historic version an audited entity, the relation will always point to the "current" entity.
* This is useful for dictionary-like entities, which don't change and don't need to be audited.
*/
- RelationTargetAuditMode targetAuditMode() default RelationTargetAuditMode.AUDITED;
+ RelationTargetAuditMode targetAuditMode() default RelationTargetAuditMode.AUDITED;
- /**
- * @return Specifies the superclasses for which properties should be audited, even if the superclasses are not
- * annotated with {@link Audited}. Causes all properties of the listed classes to be audited, just as if the
- * classes had {@link Audited} annotation applied on the class level.
- *
- * The scope of this functionality is limited to the class hierarchy of the annotated entity.
- *
- * If a parent type lists any of its parent types using this attribute, all properties in the specified classes
- * will also be audited.
- *
- * @deprecated Use {@code @AuditOverride(forClass=SomeEntity.class)} instead.
- */
- Class[] auditParents() default {};
+ /**
+ * Specifies the superclasses for which properties should be audited, even if the superclasses are not
+ * annotated with {@link Audited}. Causes all properties of the listed classes to be audited, just as if the
+ * classes had {@link Audited} annotation applied on the class level.
+ *
+ * The scope of this functionality is limited to the class hierarchy of the annotated entity.
+ *
+ * If a parent type lists any of its parent types using this attribute, all properties in the specified classes
+ * will also be audited.
+ *
+ * @deprecated Use {@code @AuditOverride(forClass=SomeEntity.class)} instead.
+ */
+ @Deprecated
+ Class[] auditParents() default {};
- /**
- * @return Should a modification flag be stored for each property in the annotated class or for the annotated
- * property. The flag stores information if a property has been changed at a given revision.
- * This can be used for example in queries.
- */
+ /**
+ * Should a modification flag be stored for each property in the annotated class or for the annotated
+ * property. The flag stores information if a property has been changed at a given revision.
+ * This can be used for example in queries.
+ */
boolean withModifiedFlag() default false;
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/CrossTypeRevisionChangesReader.java b/hibernate-envers/src/main/java/org/hibernate/envers/CrossTypeRevisionChangesReader.java
index f488ae0e36..d7675cb7e6 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/CrossTypeRevisionChangesReader.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/CrossTypeRevisionChangesReader.java
@@ -1,3 +1,26 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2013, Red Hat Inc. 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 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.envers;
import java.util.List;
@@ -10,52 +33,67 @@ import org.hibernate.envers.tools.Pair;
* Queries that allow retrieving snapshots of all entities (regardless of their particular type) changed in the given
* revision. Note that this API can be legally used only when default mechanism of tracking modified entity names
* is enabled.
+ *
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
public interface CrossTypeRevisionChangesReader {
- /**
- * Find all entities changed (added, updated and removed) in a given revision. Executes n+1 SQL queries,
- * where n is a number of different entity classes modified within specified revision.
- * @param revision Revision number.
- * @return Snapshots of all audited entities changed in a given revision.
- * @throws IllegalStateException If the associated entity manager is closed.
- * @throws IllegalArgumentException If a revision number is null, less or equal to 0.
- */
- public List findEntities(Number revision) throws IllegalStateException, IllegalArgumentException;
+ /**
+ * Find all entities changed (added, updated and removed) in a given revision. Executes n+1 SQL queries,
+ * where n is a number of different entity classes modified within specified revision.
+ *
+ * @param revision Revision number.
+ *
+ * @return Snapshots of all audited entities changed in a given revision.
+ *
+ * @throws IllegalStateException If the associated entity manager is closed.
+ * @throws IllegalArgumentException If a revision number is null, less or equal to 0.
+ */
+ public List findEntities(Number revision) throws IllegalStateException, IllegalArgumentException;
- /**
- * Find all entities changed (added, updated or removed) in a given revision. Executes n+1 SQL queries,
- * where n is a number of different entity classes modified within specified revision.
- * @param revision Revision number.
- * @param revisionType Type of modification.
- * @return Snapshots of all audited entities changed in a given revision and filtered by modification type.
- * @throws IllegalStateException If the associated entity manager is closed.
- * @throws IllegalArgumentException If a revision number is {@code null}, less or equal to 0.
- */
- public List findEntities(Number revision, RevisionType revisionType) throws IllegalStateException,
- IllegalArgumentException;
+ /**
+ * Find all entities changed (added, updated or removed) in a given revision. Executes n+1 SQL queries,
+ * where n is a number of different entity classes modified within specified revision.
+ *
+ * @param revision Revision number.
+ * @param revisionType Type of modification.
+ *
+ * @return Snapshots of all audited entities changed in a given revision and filtered by modification type.
+ *
+ * @throws IllegalStateException If the associated entity manager is closed.
+ * @throws IllegalArgumentException If a revision number is {@code null}, less or equal to 0.
+ */
+ public List findEntities(Number revision, RevisionType revisionType) throws IllegalStateException,
+ IllegalArgumentException;
- /**
- * Find all entities changed (added, updated and removed) in a given revision grouped by modification type.
- * Executes mn+1 SQL queries, where:
- *
- *
n - number of different entity classes modified within specified revision.
- *
m - number of different revision types. See {@link RevisionType} enum.
- *
- * @param revision Revision number.
- * @return Map containing lists of entity snapshots grouped by modification operation (e.g. addition, update, removal).
- * @throws IllegalStateException If the associated entity manager is closed.
- * @throws IllegalArgumentException If a revision number is {@code null}, less or equal to 0.
- */
- public Map> findEntitiesGroupByRevisionType(Number revision) throws IllegalStateException,
- IllegalArgumentException;
+ /**
+ * Find all entities changed (added, updated and removed) in a given revision grouped by modification type.
+ * Executes mn+1 SQL queries, where:
+ *
+ *
n - number of different entity classes modified within specified revision.
+ *
m - number of different revision types. See {@link RevisionType} enum.
+ *
+ *
+ * @param revision Revision number.
+ *
+ * @return Map containing lists of entity snapshots grouped by modification operation (e.g. addition, update, removal).
+ *
+ * @throws IllegalStateException If the associated entity manager is closed.
+ * @throws IllegalArgumentException If a revision number is {@code null}, less or equal to 0.
+ */
+ public Map> findEntitiesGroupByRevisionType(Number revision)
+ throws IllegalStateException,
+ IllegalArgumentException;
- /**
- * Returns set of entity names and corresponding Java classes modified in a given revision.
- * @param revision Revision number.
- * @return Set of entity names and corresponding Java classes modified in a given revision.
- * @throws IllegalStateException If the associated entity manager is closed.
- * @throws IllegalArgumentException If a revision number is {@code null}, less or equal to 0.
- */
- public Set> findEntityTypes(Number revision) throws IllegalStateException, IllegalArgumentException;
+ /**
+ * Returns set of entity names and corresponding Java classes modified in a given revision.
+ *
+ * @param revision Revision number.
+ *
+ * @return Set of entity names and corresponding Java classes modified in a given revision.
+ *
+ * @throws IllegalStateException If the associated entity manager is closed.
+ * @throws IllegalArgumentException If a revision number is {@code null}, less or equal to 0.
+ */
+ public Set> findEntityTypes(Number revision)
+ throws IllegalStateException, IllegalArgumentException;
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/DefaultRevisionEntity.java b/hibernate-envers/src/main/java/org/hibernate/envers/DefaultRevisionEntity.java
index 13d32a2629..539144bdd0 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/DefaultRevisionEntity.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/DefaultRevisionEntity.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -22,13 +22,14 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.envers;
-import java.io.Serializable;
-import java.text.DateFormat;
-import java.util.Date;
+
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
+import java.io.Serializable;
+import java.text.DateFormat;
+import java.util.Date;
/**
* @author Adam Warski (adam at warski dot org)
@@ -36,56 +37,61 @@ import javax.persistence.Transient;
@MappedSuperclass
public class DefaultRevisionEntity implements Serializable {
private static final long serialVersionUID = 8530213963961662300L;
-
- @Id
- @GeneratedValue
- @RevisionNumber
- private int id;
- @RevisionTimestamp
- private long timestamp;
+ @Id
+ @GeneratedValue
+ @RevisionNumber
+ private int id;
- public int getId() {
- return id;
- }
+ @RevisionTimestamp
+ private long timestamp;
- public void setId(int id) {
- this.id = id;
- }
+ public int getId() {
+ return id;
+ }
- @Transient
- public Date getRevisionDate() {
- return new Date(timestamp);
- }
+ public void setId(int id) {
+ this.id = id;
+ }
- public long getTimestamp() {
- return timestamp;
- }
+ @Transient
+ public Date getRevisionDate() {
+ return new Date( timestamp );
+ }
- public void setTimestamp(long timestamp) {
- this.timestamp = timestamp;
- }
+ public long getTimestamp() {
+ return timestamp;
+ }
- public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof DefaultRevisionEntity)) return false;
+ public void setTimestamp(long timestamp) {
+ this.timestamp = timestamp;
+ }
- DefaultRevisionEntity that = (DefaultRevisionEntity) o;
+ @Override
+ public boolean equals(Object o) {
+ if ( this == o ) {
+ return true;
+ }
+ if ( !(o instanceof DefaultRevisionEntity) ) {
+ return false;
+ }
- if (id != that.id) return false;
- if (timestamp != that.timestamp) return false;
+ final DefaultRevisionEntity that = (DefaultRevisionEntity) o;
+ return id == that.id
+ && timestamp == that.timestamp;
+ }
- return true;
- }
+ @Override
+ public int hashCode() {
+ int result;
+ result = id;
+ result = 31 * result + (int) (timestamp ^ (timestamp >>> 32));
+ return result;
+ }
- public int hashCode() {
- int result;
- result = id;
- result = 31 * result + (int) (timestamp ^ (timestamp >>> 32));
- return result;
- }
-
- public String toString() {
- return "DefaultRevisionEntity(id = " + id + ", revisionDate = " + DateFormat.getDateTimeInstance().format(getRevisionDate()) + ")";
- }
+ @Override
+ public String toString() {
+ return "DefaultRevisionEntity(id = " + id
+ + ", revisionDate = " + DateFormat.getDateTimeInstance().format( getRevisionDate() ) + ")";
+ }
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/DefaultTrackingModifiedEntitiesRevisionEntity.java b/hibernate-envers/src/main/java/org/hibernate/envers/DefaultTrackingModifiedEntitiesRevisionEntity.java
index ca4969ff9c..b6ee60687e 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/DefaultTrackingModifiedEntitiesRevisionEntity.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/DefaultTrackingModifiedEntitiesRevisionEntity.java
@@ -1,13 +1,36 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2013, Red Hat Inc. 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 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.envers;
-import java.util.HashSet;
-import java.util.Set;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.MappedSuperclass;
+import java.util.HashSet;
+import java.util.Set;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
@@ -16,45 +39,57 @@ import org.hibernate.annotations.FetchMode;
* Extension of standard {@link DefaultRevisionEntity} that allows tracking entity names changed in each revision.
* This revision entity is implicitly used when {@code org.hibernate.envers.track_entities_changed_in_revision}
* parameter is set to {@code true}.
+ *
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
@MappedSuperclass
public class DefaultTrackingModifiedEntitiesRevisionEntity extends DefaultRevisionEntity {
- @ElementCollection(fetch = FetchType.EAGER)
- @JoinTable(name = "REVCHANGES", joinColumns = @JoinColumn(name = "REV"))
- @Column(name = "ENTITYNAME")
- @Fetch(FetchMode.JOIN)
- @ModifiedEntityNames
- private Set modifiedEntityNames = new HashSet();
+ @ElementCollection(fetch = FetchType.EAGER)
+ @JoinTable(name = "REVCHANGES", joinColumns = @JoinColumn(name = "REV"))
+ @Column(name = "ENTITYNAME")
+ @Fetch(FetchMode.JOIN)
+ @ModifiedEntityNames
+ private Set modifiedEntityNames = new HashSet();
- public Set getModifiedEntityNames() {
- return modifiedEntityNames;
- }
+ public Set getModifiedEntityNames() {
+ return modifiedEntityNames;
+ }
- public void setModifiedEntityNames(Set modifiedEntityNames) {
- this.modifiedEntityNames = modifiedEntityNames;
- }
+ public void setModifiedEntityNames(Set modifiedEntityNames) {
+ this.modifiedEntityNames = modifiedEntityNames;
+ }
- public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof DefaultTrackingModifiedEntitiesRevisionEntity)) return false;
- if (!super.equals(o)) return false;
+ @Override
+ public boolean equals(Object o) {
+ if ( this == o ) {
+ return true;
+ }
+ if ( !(o instanceof DefaultTrackingModifiedEntitiesRevisionEntity) ) {
+ return false;
+ }
+ if ( !super.equals( o ) ) {
+ return false;
+ }
- DefaultTrackingModifiedEntitiesRevisionEntity that = (DefaultTrackingModifiedEntitiesRevisionEntity) o;
+ final DefaultTrackingModifiedEntitiesRevisionEntity that = (DefaultTrackingModifiedEntitiesRevisionEntity) o;
- if (modifiedEntityNames != null ? !modifiedEntityNames.equals(that.modifiedEntityNames)
- : that.modifiedEntityNames != null) return false;
+ if ( modifiedEntityNames != null ? !modifiedEntityNames.equals( that.modifiedEntityNames )
+ : that.modifiedEntityNames != null ) {
+ return false;
+ }
- return true;
- }
+ return true;
+ }
- public int hashCode() {
- int result = super.hashCode();
- result = 31 * result + (modifiedEntityNames != null ? modifiedEntityNames.hashCode() : 0);
- return result;
- }
+ @Override
+ public int hashCode() {
+ int result = super.hashCode();
+ result = 31 * result + (modifiedEntityNames != null ? modifiedEntityNames.hashCode() : 0);
+ return result;
+ }
- public String toString() {
- return "DefaultTrackingModifiedEntitiesRevisionEntity(" + super.toString() + ", modifiedEntityNames = " + modifiedEntityNames + ")";
- }
+ @Override
+ public String toString() {
+ return "DefaultTrackingModifiedEntitiesRevisionEntity(" + super.toString() + ", modifiedEntityNames = " + modifiedEntityNames + ")";
+ }
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/EntityTrackingRevisionListener.java b/hibernate-envers/src/main/java/org/hibernate/envers/EntityTrackingRevisionListener.java
index 0366b7f183..6fb9139249 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/EntityTrackingRevisionListener.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/EntityTrackingRevisionListener.java
@@ -1,3 +1,26 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2013, Red Hat Inc. 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 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.envers;
import java.io.Serializable;
@@ -5,19 +28,22 @@ import java.io.Serializable;
/**
* Extension of standard {@link RevisionListener} that notifies whenever an entity instance has been
* added, modified or removed within current revision boundaries.
- * @see RevisionListener
+ *
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
+ * @see RevisionListener
*/
public interface EntityTrackingRevisionListener extends RevisionListener {
- /**
- * Called after audited entity data has been persisted.
- * @param entityClass Audited entity class.
- * @param entityName Name of the audited entity. May be useful when Java class is mapped multiple times,
- * potentially to different tables.
- * @param entityId Identifier of modified entity.
- * @param revisionType Modification type (addition, update or removal).
- * @param revisionEntity An instance of the entity annotated with {@link RevisionEntity}.
- */
- void entityChanged(Class entityClass, String entityName, Serializable entityId, RevisionType revisionType,
- Object revisionEntity);
+ /**
+ * Called after audited entity data has been persisted.
+ *
+ * @param entityClass Audited entity class.
+ * @param entityName Name of the audited entity. May be useful when Java class is mapped multiple times,
+ * potentially to different tables.
+ * @param entityId Identifier of modified entity.
+ * @param revisionType Modification type (addition, update or removal).
+ * @param revisionEntity An instance of the entity annotated with {@link RevisionEntity}.
+ */
+ void entityChanged(
+ Class entityClass, String entityName, Serializable entityId, RevisionType revisionType,
+ Object revisionEntity);
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/ModificationStore.java b/hibernate-envers/src/main/java/org/hibernate/envers/ModificationStore.java
index dfc471068b..802dab8181 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/ModificationStore.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/ModificationStore.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -28,5 +28,5 @@ package org.hibernate.envers;
* @author Adam Warski (adam at warski dot org)
*/
public enum ModificationStore {
- FULL
+ FULL
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/ModifiedEntityNames.java b/hibernate-envers/src/main/java/org/hibernate/envers/ModifiedEntityNames.java
index 1bd81775dd..cf02555434 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/ModifiedEntityNames.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/ModifiedEntityNames.java
@@ -1,3 +1,26 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2013, Red Hat Inc. 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 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.envers;
import java.lang.annotation.ElementType;
@@ -8,6 +31,7 @@ import java.lang.annotation.Target;
/**
* Marks a property which holds entity names that have been modified during each revision.
* This annotation expects field of {@literal Set} type.
+ *
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
@Retention(RetentionPolicy.RUNTIME)
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/NotAudited.java b/hibernate-envers/src/main/java/org/hibernate/envers/NotAudited.java
index 4281014749..385589a478 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/NotAudited.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/NotAudited.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.envers;
+
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -29,6 +30,7 @@ import java.lang.annotation.Target;
/**
* When applied to a field, indicates that this field should not be audited.
+ *
* @author Sebastian Komander
*/
@Retention(RetentionPolicy.RUNTIME)
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/RelationTargetAuditMode.java b/hibernate-envers/src/main/java/org/hibernate/envers/RelationTargetAuditMode.java
index 1725a5e946..8b0e4d6808 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/RelationTargetAuditMode.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/RelationTargetAuditMode.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionEntity.java b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionEntity.java
index 37328ff5b9..e8882a141e 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionEntity.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionEntity.java
@@ -34,15 +34,15 @@ import java.lang.annotation.Target;
* and a long-valued property annotated with {@link RevisionTimestamp}. The {@link DefaultRevisionEntity}
* already has those two fields, so you may extend it, but you may also write your own revision entity
* from scratch.
- *
+ *
* @author Adam Warski (adam at warski dot org)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface RevisionEntity {
- /**
- * @return The optional listener that will be used to fill in the custom revision entity.
- * May also be specified using the {@code org.hibernate.envers.revision_listener} configuration property.
- */
- Class extends RevisionListener> value() default RevisionListener.class;
+ /**
+ * The optional listener that will be used to fill in the custom revision entity.
+ * May also be specified using the {@code org.hibernate.envers.revision_listener} configuration property.
+ */
+ Class extends RevisionListener> value() default RevisionListener.class;
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionListener.java b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionListener.java
index 26956d5dc0..a49eed8530 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionListener.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionListener.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -27,13 +27,15 @@ package org.hibernate.envers;
/**
* An implementation of this class, having a no-arg constructor, should be passed as an argument to the
* {@link RevisionEntity} annotation.
+ *
* @author Adam Warski (adam at warski dot org)
*/
public interface RevisionListener {
- /**
- * Called when a new revision is created.
- * @param revisionEntity An instance of the entity annotated with {@link RevisionEntity}, which will be persisted
- * after this method returns. All properties on this entity that are to be persisted should be set by this method.
- */
- void newRevision(Object revisionEntity);
+ /**
+ * Called when a new revision is created.
+ *
+ * @param revisionEntity An instance of the entity annotated with {@link RevisionEntity}, which will be persisted
+ * after this method returns. All properties on this entity that are to be persisted should be set by this method.
+ */
+ void newRevision(Object revisionEntity);
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionNumber.java b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionNumber.java
index 290b6b2c2e..26fa3749b9 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionNumber.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionNumber.java
@@ -33,7 +33,7 @@ import java.lang.annotation.Target;
* {@link RevisionListener}. Values of this property should form a strictly-increasing sequence
* of numbers. The value of this property won't be set by Envers. In most cases, this should be
* an auto-generated database-assigned primary id.
- *
+ *
* @author Adam Warski (adam at warski dot org)
* @author Sanne Grinovero
*/
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionTimestamp.java b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionTimestamp.java
index 967ed178af..c27b70c770 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionTimestamp.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionTimestamp.java
@@ -31,7 +31,7 @@ import java.lang.annotation.Target;
/**
* Marks a property which will hold the timestamp of the revision in a revision entity, see
* {@link RevisionListener}. The value of this property will be automatically set by Envers.
- *
+ *
* @author Adam Warski (adam at warski dot org)
* @author Sanne Grinovero
*/
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionType.java b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionType.java
index 79ab421292..a24e2f55a1 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionType.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionType.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -26,43 +26,51 @@ package org.hibernate.envers;
/**
* Type of the revision.
+ *
* @author Adam Warski (adam at warski dot org)
*/
public enum RevisionType {
- /**
- * Indicates that the entity was added (persisted) at that revision.
- */
- ADD((byte) 0),
- /**
- * Indicates that the entity was modified (one or more of its fields) at that revision.
- */
- MOD((byte) 1),
- /**
- * Indicates that the entity was deleted (removed) at that revision.
- */
- DEL((byte) 2);
+ /**
+ * Indicates that the entity was added (persisted) at that revision.
+ */
+ ADD( (byte) 0 ),
+ /**
+ * Indicates that the entity was modified (one or more of its fields) at that revision.
+ */
+ MOD( (byte) 1 ),
+ /**
+ * Indicates that the entity was deleted (removed) at that revision.
+ */
+ DEL( (byte) 2 );
- private Byte representation;
+ private Byte representation;
- RevisionType(byte representation) {
- this.representation = representation;
- }
+ RevisionType(byte representation) {
+ this.representation = representation;
+ }
- public Byte getRepresentation() {
- return representation;
- }
+ public Byte getRepresentation() {
+ return representation;
+ }
- public static RevisionType fromRepresentation(Object representation) {
- if (representation == null || !(representation instanceof Byte)) {
- return null;
- }
+ public static RevisionType fromRepresentation(Object representation) {
+ if ( representation == null || !(representation instanceof Byte) ) {
+ return null;
+ }
- switch ((Byte) representation) {
- case 0: return ADD;
- case 1: return MOD;
- case 2: return DEL;
- }
-
- throw new IllegalArgumentException("Unknown representation: " + representation);
- }
+ switch ( (Byte) representation ) {
+ case 0: {
+ return ADD;
+ }
+ case 1: {
+ return MOD;
+ }
+ case 2: {
+ return DEL;
+ }
+ default: {
+ throw new IllegalArgumentException( "Unknown representation: " + representation );
+ }
+ }
+ }
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTable.java b/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTable.java
index bb26ef2be8..da566e7dd6 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTable.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTable.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.envers;
+
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -33,7 +34,7 @@ import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SecondaryAuditTable {
- String secondaryTableName();
+ String secondaryTableName();
- String secondaryAuditTableName();
+ String secondaryAuditTableName();
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTables.java b/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTables.java
index ea7a81a625..97d80a178a 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTables.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTables.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.envers;
+
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -33,5 +34,5 @@ import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SecondaryAuditTables {
- SecondaryAuditTable[] value();
+ SecondaryAuditTable[] value();
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/EnversSettings.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/EnversSettings.java
index a2eb5c7e76..374428cefe 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/EnversSettings.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/EnversSettings.java
@@ -1,7 +1,28 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2013, Red Hat Inc. 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 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.envers.configuration;
-import org.hibernate.envers.strategy.DefaultAuditStrategy;
-
/**
* Configuration property names.
*
@@ -69,7 +90,7 @@ public interface EnversSettings {
public static final String AUDIT_TABLE_SUFFIX = "org.hibernate.envers.audit_table_suffix";
/**
- * Audit strategy. Defaults to {@link DefaultAuditStrategy}.
+ * Audit strategy. Defaults to {@link org.hibernate.envers.strategy.DefaultAuditStrategy}.
*/
public static final String AUDIT_STRATEGY = "org.hibernate.envers.audit_strategy";
@@ -99,7 +120,7 @@ public interface EnversSettings {
* Defaults to {@literal REVEND_TSTMP}.
*/
public static final String AUDIT_STRATEGY_VALIDITY_REVEND_TIMESTAMP_FIELD_NAME = "org.hibernate.envers.audit_strategy_validity_revend_timestamp_field_name";
-
+
/**
* Name of column used for storing ordinal of the change in sets of embeddable elements. Defaults to {@literal SETORDINAL}.
*/
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/AuditEntitiesConfiguration.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/AuditEntitiesConfiguration.java
index 1460ec3b4a..ae0a63010a 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/AuditEntitiesConfiguration.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/AuditEntitiesConfiguration.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -59,7 +59,7 @@ public class AuditEntitiesConfiguration {
private final boolean revisionEndTimestampEnabled;
private final String revisionEndTimestampFieldName;
-
+
private final String embeddableSetOrdinalPropertyName;
public AuditEntitiesConfiguration(Properties properties, String revisionInfoEntityName) {
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/ClassesAuditingData.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/ClassesAuditingData.java
index d9a95069f3..6a8ed4f48f 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/ClassesAuditingData.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/ClassesAuditingData.java
@@ -1,4 +1,28 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2013, Red Hat Inc. 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 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.envers.configuration.internal;
+
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
@@ -15,84 +39,100 @@ import org.hibernate.mapping.PersistentClass;
/**
* A helper class holding auditing meta-data for all persistent classes.
+ *
* @author Adam Warski (adam at warski dot org)
*/
public class ClassesAuditingData {
+ private static final EnversMessageLogger LOG = Logger.getMessageLogger(
+ EnversMessageLogger.class,
+ ClassesAuditingData.class.getName()
+ );
- public static final EnversMessageLogger LOG = Logger.getMessageLogger(EnversMessageLogger.class, ClassesAuditingData.class.getName());
+ private final Map entityNameToAuditingData = new HashMap();
+ private final Map persistentClassToAuditingData = new LinkedHashMap();
- private final Map entityNameToAuditingData = new HashMap();
- private final Map persistentClassToAuditingData = new LinkedHashMap();
+ /**
+ * Stores information about auditing meta-data for the given class.
+ *
+ * @param pc Persistent class.
+ * @param cad Auditing meta-data for the given class.
+ */
+ public void addClassAuditingData(PersistentClass pc, ClassAuditingData cad) {
+ entityNameToAuditingData.put( pc.getEntityName(), cad );
+ persistentClassToAuditingData.put( pc, cad );
+ }
- /**
- * Stores information about auditing meta-data for the given class.
- * @param pc Persistent class.
- * @param cad Auditing meta-data for the given class.
- */
- public void addClassAuditingData(PersistentClass pc, ClassAuditingData cad) {
- entityNameToAuditingData.put(pc.getEntityName(), cad);
- persistentClassToAuditingData.put(pc, cad);
- }
+ /**
+ * @return A collection of all auditing meta-data for persistent classes.
+ */
+ public Collection> getAllClassAuditedData() {
+ return persistentClassToAuditingData.entrySet();
+ }
- /**
- * @return A collection of all auditing meta-data for persistent classes.
- */
- public Collection> getAllClassAuditedData() {
- return persistentClassToAuditingData.entrySet();
- }
+ /**
+ * @param entityName Name of the entity.
+ *
+ * @return Auditing meta-data for the given entity.
+ */
+ public ClassAuditingData getClassAuditingData(String entityName) {
+ return entityNameToAuditingData.get( entityName );
+ }
- /**
- * @param entityName Name of the entity.
- * @return Auditing meta-data for the given entity.
- */
- public ClassAuditingData getClassAuditingData(String entityName) {
- return entityNameToAuditingData.get(entityName);
- }
+ /**
+ * After all meta-data is read, updates calculated fields. This includes:
+ *
+ *
setting {@code forceInsertable} to {@code true} for properties specified by {@code @AuditMappedBy}
+ *
+ */
+ public void updateCalculatedFields() {
+ for ( Map.Entry classAuditingDataEntry : persistentClassToAuditingData.entrySet() ) {
+ final PersistentClass pc = classAuditingDataEntry.getKey();
+ final ClassAuditingData classAuditingData = classAuditingDataEntry.getValue();
+ for ( String propertyName : classAuditingData.getPropertyNames() ) {
+ final PropertyAuditingData propertyAuditingData = classAuditingData.getPropertyAuditingData( propertyName );
+ // If a property had the @AuditMappedBy annotation, setting the referenced fields to be always insertable.
+ if ( propertyAuditingData.getAuditMappedBy() != null ) {
+ final String referencedEntityName = MappingTools.getReferencedEntityName(
+ pc.getProperty( propertyName ).getValue()
+ );
- /**
- * After all meta-data is read, updates calculated fields. This includes:
- *
- *
setting {@code forceInsertable} to {@code true} for properties specified by {@code @AuditMappedBy}
- *
- */
- public void updateCalculatedFields() {
- for (Map.Entry classAuditingDataEntry : persistentClassToAuditingData.entrySet()) {
- PersistentClass pc = classAuditingDataEntry.getKey();
- ClassAuditingData classAuditingData = classAuditingDataEntry.getValue();
- for (String propertyName : classAuditingData.getPropertyNames()) {
- PropertyAuditingData propertyAuditingData = classAuditingData.getPropertyAuditingData(propertyName);
- // If a property had the @AuditMappedBy annotation, setting the referenced fields to be always insertable.
- if (propertyAuditingData.getAuditMappedBy() != null) {
- String referencedEntityName = MappingTools.getReferencedEntityName(pc.getProperty(propertyName).getValue());
+ final ClassAuditingData referencedClassAuditingData = entityNameToAuditingData.get( referencedEntityName );
- ClassAuditingData referencedClassAuditingData = entityNameToAuditingData.get(referencedEntityName);
+ forcePropertyInsertable(
+ referencedClassAuditingData, propertyAuditingData.getAuditMappedBy(),
+ pc.getEntityName(), referencedEntityName
+ );
- forcePropertyInsertable(referencedClassAuditingData, propertyAuditingData.getAuditMappedBy(),
- pc.getEntityName(), referencedEntityName);
+ forcePropertyInsertable(
+ referencedClassAuditingData, propertyAuditingData.getPositionMappedBy(),
+ pc.getEntityName(), referencedEntityName
+ );
+ }
+ }
+ }
+ }
- forcePropertyInsertable(referencedClassAuditingData, propertyAuditingData.getPositionMappedBy(),
- pc.getEntityName(), referencedEntityName);
- }
- }
- }
- }
+ private void forcePropertyInsertable(
+ ClassAuditingData classAuditingData, String propertyName,
+ String entityName, String referencedEntityName) {
+ if ( propertyName != null ) {
+ if ( classAuditingData.getPropertyAuditingData( propertyName ) == null ) {
+ throw new MappingException(
+ "@AuditMappedBy points to a property that doesn't exist: " +
+ referencedEntityName + "." + propertyName
+ );
+ }
- private void forcePropertyInsertable(ClassAuditingData classAuditingData, String propertyName,
- String entityName, String referencedEntityName) {
- if (propertyName != null) {
- if (classAuditingData.getPropertyAuditingData(propertyName) == null) {
- throw new MappingException("@AuditMappedBy points to a property that doesn't exist: " +
- referencedEntityName + "." + propertyName);
- }
+ LOG.debugf(
+ "Non-insertable property %s.%s will be made insertable because a matching @AuditMappedBy was found in the %s entity",
+ referencedEntityName,
+ propertyName,
+ entityName
+ );
- LOG.debugf("Non-insertable property %s.%s will be made insertable because a matching @AuditMappedBy was found in the %s entity",
- referencedEntityName,
- propertyName,
- entityName);
-
- classAuditingData
- .getPropertyAuditingData(propertyName)
- .setForceInsertable(true);
- }
- }
+ classAuditingData
+ .getPropertyAuditingData( propertyName )
+ .setForceInsertable( true );
+ }
+ }
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/EntitiesConfigurator.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/EntitiesConfigurator.java
index a12f588edb..540e439c4c 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/EntitiesConfigurator.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/EntitiesConfigurator.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -57,108 +57,118 @@ import org.hibernate.mapping.PersistentClass;
* @author Adam Warski (adam at warski dot org)
*/
public class EntitiesConfigurator {
- public EntitiesConfigurations configure(Configuration cfg, ReflectionManager reflectionManager,
- GlobalConfiguration globalCfg, AuditEntitiesConfiguration verEntCfg,
- AuditStrategy auditStrategy, ClassLoaderService classLoaderService,
- Document revisionInfoXmlMapping, Element revisionInfoRelationMapping) {
- // Creating a name register to capture all audit entity names created.
- AuditEntityNameRegister auditEntityNameRegister = new AuditEntityNameRegister();
- DOMWriter writer = new DOMWriter();
+ public EntitiesConfigurations configure(
+ Configuration cfg, ReflectionManager reflectionManager,
+ GlobalConfiguration globalCfg, AuditEntitiesConfiguration verEntCfg,
+ AuditStrategy auditStrategy, ClassLoaderService classLoaderService,
+ Document revisionInfoXmlMapping, Element revisionInfoRelationMapping) {
+ // Creating a name register to capture all audit entity names created.
+ final AuditEntityNameRegister auditEntityNameRegister = new AuditEntityNameRegister();
+ final DOMWriter writer = new DOMWriter();
- // Sorting the persistent class topologically - superclass always before subclass
- Iterator classes = GraphTopologicalSort.sort(new PersistentClassGraphDefiner(cfg)).iterator();
+ // Sorting the persistent class topologically - superclass always before subclass
+ final Iterator classes = GraphTopologicalSort.sort( new PersistentClassGraphDefiner( cfg ) )
+ .iterator();
- ClassesAuditingData classesAuditingData = new ClassesAuditingData();
- Map xmlMappings = new HashMap();
+ final ClassesAuditingData classesAuditingData = new ClassesAuditingData();
+ final Map xmlMappings = new HashMap();
- // Reading metadata from annotations
- while (classes.hasNext()) {
- PersistentClass pc = classes.next();
+ // Reading metadata from annotations
+ while ( classes.hasNext() ) {
+ final PersistentClass pc = classes.next();
- // Collecting information from annotations on the persistent class pc
- AnnotationsMetadataReader annotationsMetadataReader =
- new AnnotationsMetadataReader(globalCfg, reflectionManager, pc);
- ClassAuditingData auditData = annotationsMetadataReader.getAuditData();
+ // Collecting information from annotations on the persistent class pc
+ final AnnotationsMetadataReader annotationsMetadataReader =
+ new AnnotationsMetadataReader( globalCfg, reflectionManager, pc );
+ final ClassAuditingData auditData = annotationsMetadataReader.getAuditData();
- classesAuditingData.addClassAuditingData(pc, auditData);
- }
+ classesAuditingData.addClassAuditingData( pc, auditData );
+ }
- // Now that all information is read we can update the calculated fields.
- classesAuditingData.updateCalculatedFields();
+ // Now that all information is read we can update the calculated fields.
+ classesAuditingData.updateCalculatedFields();
- AuditMetadataGenerator auditMetaGen = new AuditMetadataGenerator(cfg, globalCfg, verEntCfg, auditStrategy,
- classLoaderService, revisionInfoRelationMapping, auditEntityNameRegister);
+ final AuditMetadataGenerator auditMetaGen = new AuditMetadataGenerator(
+ cfg, globalCfg, verEntCfg, auditStrategy,
+ classLoaderService, revisionInfoRelationMapping, auditEntityNameRegister
+ );
- // First pass
- for (Map.Entry pcDatasEntry : classesAuditingData.getAllClassAuditedData()) {
- PersistentClass pc = pcDatasEntry.getKey();
- ClassAuditingData auditData = pcDatasEntry.getValue();
+ // First pass
+ for ( Map.Entry pcDatasEntry : classesAuditingData.getAllClassAuditedData() ) {
+ final PersistentClass pc = pcDatasEntry.getKey();
+ final ClassAuditingData auditData = pcDatasEntry.getValue();
- EntityXmlMappingData xmlMappingData = new EntityXmlMappingData();
- if (auditData.isAudited()) {
- if (!StringTools.isEmpty(auditData.getAuditTable().value())) {
- verEntCfg.addCustomAuditTableName(pc.getEntityName(), auditData.getAuditTable().value());
- }
+ final EntityXmlMappingData xmlMappingData = new EntityXmlMappingData();
+ if ( auditData.isAudited() ) {
+ if ( !StringTools.isEmpty( auditData.getAuditTable().value() ) ) {
+ verEntCfg.addCustomAuditTableName( pc.getEntityName(), auditData.getAuditTable().value() );
+ }
- auditMetaGen.generateFirstPass(pc, auditData, xmlMappingData, true);
- } else {
- auditMetaGen.generateFirstPass(pc, auditData, xmlMappingData, false);
+ auditMetaGen.generateFirstPass( pc, auditData, xmlMappingData, true );
+ }
+ else {
+ auditMetaGen.generateFirstPass( pc, auditData, xmlMappingData, false );
}
- xmlMappings.put(pc, xmlMappingData);
- }
+ xmlMappings.put( pc, xmlMappingData );
+ }
- // Second pass
- for (Map.Entry pcDatasEntry : classesAuditingData.getAllClassAuditedData()) {
- EntityXmlMappingData xmlMappingData = xmlMappings.get(pcDatasEntry.getKey());
+ // Second pass
+ for ( Map.Entry pcDatasEntry : classesAuditingData.getAllClassAuditedData() ) {
+ final EntityXmlMappingData xmlMappingData = xmlMappings.get( pcDatasEntry.getKey() );
- if (pcDatasEntry.getValue().isAudited()) {
- auditMetaGen.generateSecondPass(pcDatasEntry.getKey(), pcDatasEntry.getValue(), xmlMappingData);
- try {
- cfg.addDocument(writer.write(xmlMappingData.getMainXmlMapping()));
- //writeDocument(xmlMappingData.getMainXmlMapping());
+ if ( pcDatasEntry.getValue().isAudited() ) {
+ auditMetaGen.generateSecondPass( pcDatasEntry.getKey(), pcDatasEntry.getValue(), xmlMappingData );
+ try {
+ cfg.addDocument( writer.write( xmlMappingData.getMainXmlMapping() ) );
+ //writeDocument(xmlMappingData.getMainXmlMapping());
- for (Document additionalMapping : xmlMappingData.getAdditionalXmlMappings()) {
- cfg.addDocument(writer.write(additionalMapping));
- //writeDocument(additionalMapping);
- }
- } catch (DocumentException e) {
- throw new MappingException(e);
- }
- }
- }
+ for ( Document additionalMapping : xmlMappingData.getAdditionalXmlMappings() ) {
+ cfg.addDocument( writer.write( additionalMapping ) );
+ //writeDocument(additionalMapping);
+ }
+ }
+ catch (DocumentException e) {
+ throw new MappingException( e );
+ }
+ }
+ }
- // Only if there are any versioned classes
- if (auditMetaGen.getEntitiesConfigurations().size() > 0) {
- try {
- if (revisionInfoXmlMapping != null) {
- //writeDocument(revisionInfoXmlMapping);
- cfg.addDocument(writer.write(revisionInfoXmlMapping));
- }
- } catch (DocumentException e) {
- throw new MappingException(e);
- }
- }
+ // Only if there are any versioned classes
+ if ( auditMetaGen.getEntitiesConfigurations().size() > 0 ) {
+ try {
+ if ( revisionInfoXmlMapping != null ) {
+ //writeDocument(revisionInfoXmlMapping);
+ cfg.addDocument( writer.write( revisionInfoXmlMapping ) );
+ }
+ }
+ catch (DocumentException e) {
+ throw new MappingException( e );
+ }
+ }
- return new EntitiesConfigurations(auditMetaGen.getEntitiesConfigurations(),
- auditMetaGen.getNotAuditedEntitiesConfigurations());
- }
+ return new EntitiesConfigurations(
+ auditMetaGen.getEntitiesConfigurations(),
+ auditMetaGen.getNotAuditedEntitiesConfigurations()
+ );
+ }
- @SuppressWarnings({"UnusedDeclaration"})
- private void writeDocument(Document e) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- Writer w = new PrintWriter(baos);
+ @SuppressWarnings({"UnusedDeclaration"})
+ private void writeDocument(Document e) {
+ final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ final Writer w = new PrintWriter( baos );
- try {
- XMLWriter xw = new XMLWriter(w, new OutputFormat(" ", true));
- xw.write(e);
- w.flush();
- } catch (IOException e1) {
- e1.printStackTrace();
- }
+ try {
+ final XMLWriter xw = new XMLWriter( w, new OutputFormat( " ", true ) );
+ xw.write( e );
+ w.flush();
+ }
+ catch (IOException e1) {
+ e1.printStackTrace();
+ }
- System.out.println("-----------");
- System.out.println(baos.toString());
- System.out.println("-----------");
- }
+ System.out.println( "-----------" );
+ System.out.println( baos.toString() );
+ System.out.println( "-----------" );
+ }
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/GlobalConfiguration.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/GlobalConfiguration.java
index 295f9d4585..658451430f 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/GlobalConfiguration.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/GlobalConfiguration.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -116,13 +116,16 @@ public class GlobalConfiguration {
EnversSettings.MODIFIED_FLAG_SUFFIX, properties, "_MOD"
);
- String revisionListenerClassName = properties.getProperty( EnversSettings.REVISION_LISTENER, null );
+ final String revisionListenerClassName = properties.getProperty( EnversSettings.REVISION_LISTENER, null );
if ( revisionListenerClassName != null ) {
try {
revisionListenerClass = ReflectionTools.loadClass( revisionListenerClassName, classLoaderService );
}
- catch ( ClassLoadingException e ) {
- throw new MappingException( "Revision listener class not found: " + revisionListenerClassName + ".", e );
+ catch (ClassLoadingException e) {
+ throw new MappingException(
+ "Revision listener class not found: " + revisionListenerClassName + ".",
+ e
+ );
}
}
else {
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/PersistentClassGraphDefiner.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/PersistentClassGraphDefiner.java
index f82ef769a5..c26a22474a 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/PersistentClassGraphDefiner.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/PersistentClassGraphDefiner.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.envers.configuration.internal;
+
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -34,43 +35,48 @@ import org.hibernate.mapping.PersistentClass;
/**
* Defines a graph, where the vertexes are all persistent classes, and there is an edge from
* p.c. A to p.c. B iff A is a superclass of B.
+ *
* @author Adam Warski (adam at warski dot org)
*/
public class PersistentClassGraphDefiner implements GraphDefiner {
- private Configuration cfg;
+ private Configuration cfg;
- public PersistentClassGraphDefiner(Configuration cfg) {
- this.cfg = cfg;
- }
+ public PersistentClassGraphDefiner(Configuration cfg) {
+ this.cfg = cfg;
+ }
- public String getRepresentation(PersistentClass pc) {
- return pc.getEntityName();
- }
+ @Override
+ public String getRepresentation(PersistentClass pc) {
+ return pc.getEntityName();
+ }
- public PersistentClass getValue(String entityName) {
- return cfg.getClassMapping(entityName);
- }
+ @Override
+ public PersistentClass getValue(String entityName) {
+ return cfg.getClassMapping( entityName );
+ }
- @SuppressWarnings({"unchecked"})
- private void addNeighbours(List neighbours, Iterator subclassIterator) {
- while (subclassIterator.hasNext()) {
- PersistentClass subclass = subclassIterator.next();
- neighbours.add(subclass);
- addNeighbours(neighbours, (Iterator) subclass.getSubclassIterator());
- }
- }
+ @SuppressWarnings({"unchecked"})
+ private void addNeighbours(List neighbours, Iterator subclassIterator) {
+ while ( subclassIterator.hasNext() ) {
+ final PersistentClass subclass = subclassIterator.next();
+ neighbours.add( subclass );
+ addNeighbours( neighbours, (Iterator) subclass.getSubclassIterator() );
+ }
+ }
- @SuppressWarnings({"unchecked"})
- public List getNeighbours(PersistentClass pc) {
- List neighbours = new ArrayList();
+ @Override
+ @SuppressWarnings({"unchecked"})
+ public List getNeighbours(PersistentClass pc) {
+ final List neighbours = new ArrayList();
- addNeighbours(neighbours, (Iterator) pc.getSubclassIterator());
+ addNeighbours( neighbours, (Iterator) pc.getSubclassIterator() );
- return neighbours;
- }
+ return neighbours;
+ }
- @SuppressWarnings({"unchecked"})
- public List getValues() {
- return Tools.iteratorToList( cfg.getClassMappings() );
- }
+ @Override
+ @SuppressWarnings({"unchecked"})
+ public List getValues() {
+ return Tools.iteratorToList( cfg.getClassMappings() );
+ }
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfiguration.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfiguration.java
index 7e14efa32b..104b96fa6c 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfiguration.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfiguration.java
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * Copyright (c) 2008, 2013, Red Hat Inc. 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.
+ * 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
@@ -22,10 +22,11 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.envers.configuration.internal;
+
+import javax.persistence.Column;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
-import javax.persistence.Column;
import org.dom4j.Document;
import org.dom4j.Element;
@@ -65,301 +66,394 @@ import org.hibernate.type.Type;
* @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com)
*/
public class RevisionInfoConfiguration {
- private String revisionInfoEntityName;
- private PropertyData revisionInfoIdData;
- private PropertyData revisionInfoTimestampData;
- private PropertyData modifiedEntityNamesData;
- private Type revisionInfoTimestampType;
- private GlobalConfiguration globalCfg;
+ private String revisionInfoEntityName;
+ private PropertyData revisionInfoIdData;
+ private PropertyData revisionInfoTimestampData;
+ private PropertyData modifiedEntityNamesData;
+ private Type revisionInfoTimestampType;
+ private GlobalConfiguration globalCfg;
- private String revisionPropType;
- private String revisionPropSqlType;
+ private String revisionPropType;
+ private String revisionPropSqlType;
- public RevisionInfoConfiguration(GlobalConfiguration globalCfg) {
- this.globalCfg = globalCfg;
- if (globalCfg.isUseRevisionEntityWithNativeId()) {
- revisionInfoEntityName = "org.hibernate.envers.DefaultRevisionEntity";
- } else {
- revisionInfoEntityName = "org.hibernate.envers.enhanced.SequenceIdRevisionEntity";
- }
- revisionInfoIdData = new PropertyData("id", "id", "field", null);
- revisionInfoTimestampData = new PropertyData("timestamp", "timestamp", "field", null);
- modifiedEntityNamesData = new PropertyData("modifiedEntityNames", "modifiedEntityNames", "field", null);
- revisionInfoTimestampType = new LongType();
+ public RevisionInfoConfiguration(GlobalConfiguration globalCfg) {
+ this.globalCfg = globalCfg;
+ if ( globalCfg.isUseRevisionEntityWithNativeId() ) {
+ revisionInfoEntityName = "org.hibernate.envers.DefaultRevisionEntity";
+ }
+ else {
+ revisionInfoEntityName = "org.hibernate.envers.enhanced.SequenceIdRevisionEntity";
+ }
+ revisionInfoIdData = new PropertyData( "id", "id", "field", null );
+ revisionInfoTimestampData = new PropertyData( "timestamp", "timestamp", "field", null );
+ modifiedEntityNamesData = new PropertyData( "modifiedEntityNames", "modifiedEntityNames", "field", null );
+ revisionInfoTimestampType = new LongType();
- revisionPropType = "integer";
- }
+ revisionPropType = "integer";
+ }
- private Document generateDefaultRevisionInfoXmlMapping() {
- Document document = XMLHelper.getDocumentFactory().createDocument();
+ private Document generateDefaultRevisionInfoXmlMapping() {
+ final Document document = XMLHelper.getDocumentFactory().createDocument();
- Element class_mapping = MetadataTools.createEntity(document, new AuditTableData(null, null, globalCfg.getDefaultSchemaName(), globalCfg.getDefaultCatalogName()), null, null);
+ final Element classMapping = MetadataTools.createEntity(
+ document,
+ new AuditTableData( null, null, globalCfg.getDefaultSchemaName(), globalCfg.getDefaultCatalogName() ),
+ null,
+ null
+ );
- class_mapping.addAttribute("name", revisionInfoEntityName);
- class_mapping.addAttribute("table", "REVINFO");
+ classMapping.addAttribute( "name", revisionInfoEntityName );
+ classMapping.addAttribute( "table", "REVINFO" );
- Element idProperty = MetadataTools.addNativelyGeneratedId(class_mapping, revisionInfoIdData.getName(),
- revisionPropType, globalCfg.isUseRevisionEntityWithNativeId());
- MetadataTools.addColumn(idProperty, "REV", null, null, null, null, null, null, false);
+ final Element idProperty = MetadataTools.addNativelyGeneratedId(
+ classMapping,
+ revisionInfoIdData.getName(),
+ revisionPropType,
+ globalCfg.isUseRevisionEntityWithNativeId()
+ );
+ MetadataTools.addColumn( idProperty, "REV", null, null, null, null, null, null, false );
- Element timestampProperty = MetadataTools.addProperty(class_mapping, revisionInfoTimestampData.getName(),
- revisionInfoTimestampType.getName(), true, false);
- MetadataTools.addColumn(timestampProperty, "REVTSTMP", null, null, null, null, null, null, false);
+ final Element timestampProperty = MetadataTools.addProperty(
+ classMapping,
+ revisionInfoTimestampData.getName(),
+ revisionInfoTimestampType.getName(),
+ true,
+ false
+ );
+ MetadataTools.addColumn( timestampProperty, "REVTSTMP", null, null, null, null, null, null, false );
- if (globalCfg.isTrackEntitiesChangedInRevision()) {
- generateEntityNamesTrackingTableMapping(class_mapping, "modifiedEntityNames",
- globalCfg.getDefaultSchemaName(), globalCfg.getDefaultCatalogName(),
- "REVCHANGES", "REV", "ENTITYNAME", "string");
- }
+ if ( globalCfg.isTrackEntitiesChangedInRevision() ) {
+ generateEntityNamesTrackingTableMapping(
+ classMapping,
+ "modifiedEntityNames",
+ globalCfg.getDefaultSchemaName(),
+ globalCfg.getDefaultCatalogName(),
+ "REVCHANGES",
+ "REV",
+ "ENTITYNAME",
+ "string"
+ );
+ }
- return document;
- }
+ return document;
+ }
- /**
- * Generates mapping that represents a set of primitive types.
- *
- * <set name="propertyName" table="joinTableName" schema="joinTableSchema" catalog="joinTableCatalog"
- * cascade="persist, delete" lazy="false" fetch="join">
- * <key column="joinTablePrimaryKeyColumnName" />
- * <element type="joinTableValueColumnType">
- * <column name="joinTableValueColumnName" />
- * </element>
- * </set>
- *
- */
- private void generateEntityNamesTrackingTableMapping(Element class_mapping, String propertyName,
- String joinTableSchema, String joinTableCatalog, String joinTableName,
- String joinTablePrimaryKeyColumnName, String joinTableValueColumnName,
- String joinTableValueColumnType) {
- Element set = class_mapping.addElement("set");
- set.addAttribute("name", propertyName);
- set.addAttribute("table", joinTableName);
- set.addAttribute("schema", joinTableSchema);
- set.addAttribute("catalog", joinTableCatalog);
- set.addAttribute("cascade", "persist, delete");
- set.addAttribute("fetch", "join");
- set.addAttribute("lazy", "false");
- Element key = set.addElement("key");
- key.addAttribute("column", joinTablePrimaryKeyColumnName);
- Element element = set.addElement("element");
- element.addAttribute("type", joinTableValueColumnType);
- Element column = element.addElement("column");
- column.addAttribute("name", joinTableValueColumnName);
- }
+ /**
+ * Generates mapping that represents a set of primitive types.
+ *
+ * <set name="propertyName" table="joinTableName" schema="joinTableSchema" catalog="joinTableCatalog"
+ * cascade="persist, delete" lazy="false" fetch="join">
+ * <key column="joinTablePrimaryKeyColumnName" />
+ * <element type="joinTableValueColumnType">
+ * <column name="joinTableValueColumnName" />
+ * </element>
+ * </set>
+ *
+ */
+ private void generateEntityNamesTrackingTableMapping(
+ Element classMapping,
+ String propertyName,
+ String joinTableSchema,
+ String joinTableCatalog,
+ String joinTableName,
+ String joinTablePrimaryKeyColumnName,
+ String joinTableValueColumnName,
+ String joinTableValueColumnType) {
+ final Element set = classMapping.addElement( "set" );
+ set.addAttribute( "name", propertyName );
+ set.addAttribute( "table", joinTableName );
+ set.addAttribute( "schema", joinTableSchema );
+ set.addAttribute( "catalog", joinTableCatalog );
+ set.addAttribute( "cascade", "persist, delete" );
+ set.addAttribute( "fetch", "join" );
+ set.addAttribute( "lazy", "false" );
+ final Element key = set.addElement( "key" );
+ key.addAttribute( "column", joinTablePrimaryKeyColumnName );
+ final Element element = set.addElement( "element" );
+ element.addAttribute( "type", joinTableValueColumnType );
+ final Element column = element.addElement( "column" );
+ column.addAttribute( "name", joinTableValueColumnName );
+ }
- private Element generateRevisionInfoRelationMapping() {
- Document document = XMLHelper.getDocumentFactory().createDocument();
- Element rev_rel_mapping = document.addElement("key-many-to-one");
- rev_rel_mapping.addAttribute("type", revisionPropType);
- rev_rel_mapping.addAttribute("class", revisionInfoEntityName);
+ private Element generateRevisionInfoRelationMapping() {
+ final Document document = XMLHelper.getDocumentFactory().createDocument();
+ final Element revRelMapping = document.addElement( "key-many-to-one" );
+ revRelMapping.addAttribute( "type", revisionPropType );
+ revRelMapping.addAttribute( "class", revisionInfoEntityName );
- if (revisionPropSqlType != null) {
- // Putting a fake name to make Hibernate happy. It will be replaced later anyway.
- MetadataTools.addColumn(rev_rel_mapping, "*" , null, null, null, revisionPropSqlType, null, null, false);
- }
+ if ( revisionPropSqlType != null ) {
+ // Putting a fake name to make Hibernate happy. It will be replaced later anyway.
+ MetadataTools.addColumn( revRelMapping, "*", null, null, null, revisionPropSqlType, null, null, false );
+ }
- return rev_rel_mapping;
- }
+ return revRelMapping;
+ }
- private void searchForRevisionInfoCfgInProperties(XClass clazz, ReflectionManager reflectionManager,
- MutableBoolean revisionNumberFound, MutableBoolean revisionTimestampFound,
- MutableBoolean modifiedEntityNamesFound, String accessType) {
- for (XProperty property : clazz.getDeclaredProperties(accessType)) {
- RevisionNumber revisionNumber = property.getAnnotation(RevisionNumber.class);
- RevisionTimestamp revisionTimestamp = property.getAnnotation(RevisionTimestamp.class);
- ModifiedEntityNames modifiedEntityNames = property.getAnnotation(ModifiedEntityNames.class);
+ private void searchForRevisionInfoCfgInProperties(
+ XClass clazz,
+ ReflectionManager reflectionManager,
+ MutableBoolean revisionNumberFound,
+ MutableBoolean revisionTimestampFound,
+ MutableBoolean modifiedEntityNamesFound,
+ String accessType) {
+ for ( XProperty property : clazz.getDeclaredProperties( accessType ) ) {
+ final RevisionNumber revisionNumber = property.getAnnotation( RevisionNumber.class );
+ final RevisionTimestamp revisionTimestamp = property.getAnnotation( RevisionTimestamp.class );
+ final ModifiedEntityNames modifiedEntityNames = property.getAnnotation( ModifiedEntityNames.class );
- if (revisionNumber != null) {
- if (revisionNumberFound.isSet()) {
- throw new MappingException("Only one property may be annotated with @RevisionNumber!");
- }
+ if ( revisionNumber != null ) {
+ if ( revisionNumberFound.isSet() ) {
+ throw new MappingException( "Only one property may be annotated with @RevisionNumber!" );
+ }
- XClass revisionNumberClass = property.getType();
- if (reflectionManager.equals(revisionNumberClass, Integer.class) ||
- reflectionManager.equals(revisionNumberClass, Integer.TYPE)) {
- revisionInfoIdData = new PropertyData(property.getName(), property.getName(), accessType, null);
- revisionNumberFound.set();
- } else if (reflectionManager.equals(revisionNumberClass, Long.class) ||
- reflectionManager.equals(revisionNumberClass, Long.TYPE)) {
- revisionInfoIdData = new PropertyData(property.getName(), property.getName(), accessType, null);
- revisionNumberFound.set();
+ final XClass revisionNumberClass = property.getType();
+ if ( reflectionManager.equals( revisionNumberClass, Integer.class ) ||
+ reflectionManager.equals( revisionNumberClass, Integer.TYPE ) ) {
+ revisionInfoIdData = new PropertyData( property.getName(), property.getName(), accessType, null );
+ revisionNumberFound.set();
+ }
+ else if ( reflectionManager.equals( revisionNumberClass, Long.class ) ||
+ reflectionManager.equals( revisionNumberClass, Long.TYPE ) ) {
+ revisionInfoIdData = new PropertyData( property.getName(), property.getName(), accessType, null );
+ revisionNumberFound.set();
- // The default is integer
- revisionPropType = "long";
- } else {
- throw new MappingException("The field annotated with @RevisionNumber must be of type " +
- "int, Integer, long or Long");
- }
+ // The default is integer
+ revisionPropType = "long";
+ }
+ else {
+ throw new MappingException(
+ "The field annotated with @RevisionNumber must be of type " +
+ "int, Integer, long or Long"
+ );
+ }
- // Getting the @Column definition of the revision number property, to later use that info to
- // generate the same mapping for the relation from an audit table's revision number to the
- // revision entity revision number.
- Column revisionPropColumn = property.getAnnotation(Column.class);
- if (revisionPropColumn != null) {
- revisionPropSqlType = revisionPropColumn.columnDefinition();
- }
- }
+ // Getting the @Column definition of the revision number property, to later use that info to
+ // generate the same mapping for the relation from an audit table's revision number to the
+ // revision entity revision number.
+ final Column revisionPropColumn = property.getAnnotation( Column.class );
+ if ( revisionPropColumn != null ) {
+ revisionPropSqlType = revisionPropColumn.columnDefinition();
+ }
+ }
- if (revisionTimestamp != null) {
- if (revisionTimestampFound.isSet()) {
- throw new MappingException("Only one property may be annotated with @RevisionTimestamp!");
- }
+ if ( revisionTimestamp != null ) {
+ if ( revisionTimestampFound.isSet() ) {
+ throw new MappingException( "Only one property may be annotated with @RevisionTimestamp!" );
+ }
- XClass revisionTimestampClass = property.getType();
- if (reflectionManager.equals(revisionTimestampClass, Long.class) ||
- reflectionManager.equals(revisionTimestampClass, Long.TYPE) ||
- reflectionManager.equals(revisionTimestampClass, Date.class) ||
- reflectionManager.equals(revisionTimestampClass, java.sql.Date.class)) {
- revisionInfoTimestampData = new PropertyData(property.getName(), property.getName(), accessType, null);
- revisionTimestampFound.set();
- } else {
- throw new MappingException("The field annotated with @RevisionTimestamp must be of type " +
- "long, Long, java.util.Date or java.sql.Date");
- }
- }
+ final XClass revisionTimestampClass = property.getType();
+ if ( reflectionManager.equals( revisionTimestampClass, Long.class ) ||
+ reflectionManager.equals( revisionTimestampClass, Long.TYPE ) ||
+ reflectionManager.equals( revisionTimestampClass, Date.class ) ||
+ reflectionManager.equals( revisionTimestampClass, java.sql.Date.class ) ) {
+ revisionInfoTimestampData = new PropertyData(
+ property.getName(),
+ property.getName(),
+ accessType,
+ null
+ );
+ revisionTimestampFound.set();
+ }
+ else {
+ throw new MappingException(
+ "The field annotated with @RevisionTimestamp must be of type " +
+ "long, Long, java.util.Date or java.sql.Date"
+ );
+ }
+ }
- if (modifiedEntityNames != null) {
- if (modifiedEntityNamesFound.isSet()) {
- throw new MappingException("Only one property may be annotated with @ModifiedEntityNames!");
- }
- XClass modifiedEntityNamesClass = property.getType();
- if (reflectionManager.equals(modifiedEntityNamesClass, Set.class) &&
- reflectionManager.equals(property.getElementClass(), String.class)) {
- modifiedEntityNamesData = new PropertyData(property.getName(), property.getName(), accessType, null);
- modifiedEntityNamesFound.set();
- } else {
- throw new MappingException("The field annotated with @ModifiedEntityNames must be of Set type.");
- }
- }
- }
- }
+ if ( modifiedEntityNames != null ) {
+ if ( modifiedEntityNamesFound.isSet() ) {
+ throw new MappingException( "Only one property may be annotated with @ModifiedEntityNames!" );
+ }
+ final XClass modifiedEntityNamesClass = property.getType();
+ if ( reflectionManager.equals( modifiedEntityNamesClass, Set.class ) &&
+ reflectionManager.equals( property.getElementClass(), String.class ) ) {
+ modifiedEntityNamesData = new PropertyData(
+ property.getName(),
+ property.getName(),
+ accessType,
+ null
+ );
+ modifiedEntityNamesFound.set();
+ }
+ else {
+ throw new MappingException(
+ "The field annotated with @ModifiedEntityNames must be of Set type."
+ );
+ }
+ }
+ }
+ }
- private void searchForRevisionInfoCfg(XClass clazz, ReflectionManager reflectionManager,
- MutableBoolean revisionNumberFound, MutableBoolean revisionTimestampFound,
- MutableBoolean modifiedEntityNamesFound) {
- XClass superclazz = clazz.getSuperclass();
- if (!"java.lang.Object".equals(superclazz.getName())) {
- searchForRevisionInfoCfg(superclazz, reflectionManager, revisionNumberFound, revisionTimestampFound, modifiedEntityNamesFound);
- }
+ private void searchForRevisionInfoCfg(
+ XClass clazz, ReflectionManager reflectionManager,
+ MutableBoolean revisionNumberFound, MutableBoolean revisionTimestampFound,
+ MutableBoolean modifiedEntityNamesFound) {
+ final XClass superclazz = clazz.getSuperclass();
+ if ( !"java.lang.Object".equals( superclazz.getName() ) ) {
+ searchForRevisionInfoCfg(
+ superclazz,
+ reflectionManager,
+ revisionNumberFound,
+ revisionTimestampFound,
+ modifiedEntityNamesFound
+ );
+ }
- searchForRevisionInfoCfgInProperties(clazz, reflectionManager, revisionNumberFound, revisionTimestampFound,
- modifiedEntityNamesFound, "field");
- searchForRevisionInfoCfgInProperties(clazz, reflectionManager, revisionNumberFound, revisionTimestampFound,
- modifiedEntityNamesFound, "property");
- }
+ searchForRevisionInfoCfgInProperties(
+ clazz, reflectionManager, revisionNumberFound, revisionTimestampFound,
+ modifiedEntityNamesFound, "field"
+ );
+ searchForRevisionInfoCfgInProperties(
+ clazz, reflectionManager, revisionNumberFound, revisionTimestampFound,
+ modifiedEntityNamesFound, "property"
+ );
+ }
- public RevisionInfoConfigurationResult configure(Configuration cfg, ReflectionManager reflectionManager) {
- Iterator classes = cfg.getClassMappings();
- boolean revisionEntityFound = false;
- RevisionInfoGenerator revisionInfoGenerator = null;
+ public RevisionInfoConfigurationResult configure(Configuration cfg, ReflectionManager reflectionManager) {
+ boolean revisionEntityFound = false;
+ RevisionInfoGenerator revisionInfoGenerator = null;
+ Class> revisionInfoClass = null;
- Class> revisionInfoClass = null;
+ final Iterator classes = cfg.getClassMappings();
+ while ( classes.hasNext() ) {
+ PersistentClass pc = classes.next();
+ XClass clazz;
+ try {
+ clazz = reflectionManager.classForName( pc.getClassName(), this.getClass() );
+ }
+ catch (ClassNotFoundException e) {
+ throw new MappingException( e );
+ }
- while (classes.hasNext()) {
- PersistentClass pc = classes.next();
- XClass clazz;
- try {
- clazz = reflectionManager.classForName(pc.getClassName(), this.getClass());
- } catch (ClassNotFoundException e) {
- throw new MappingException(e);
- }
+ final RevisionEntity revisionEntity = clazz.getAnnotation( RevisionEntity.class );
+ if ( revisionEntity != null ) {
+ if ( revisionEntityFound ) {
+ throw new MappingException( "Only one entity may be annotated with @RevisionEntity!" );
+ }
- RevisionEntity revisionEntity = clazz.getAnnotation(RevisionEntity.class);
- if (revisionEntity != null) {
- if (revisionEntityFound) {
- throw new MappingException("Only one entity may be annotated with @RevisionEntity!");
- }
+ // Checking if custom revision entity isn't audited
+ if ( clazz.getAnnotation( Audited.class ) != null ) {
+ throw new MappingException( "An entity annotated with @RevisionEntity cannot be audited!" );
+ }
- // Checking if custom revision entity isn't audited
- if (clazz.getAnnotation(Audited.class) != null) {
- throw new MappingException("An entity annotated with @RevisionEntity cannot be audited!");
- }
+ revisionEntityFound = true;
- revisionEntityFound = true;
+ final MutableBoolean revisionNumberFound = new MutableBoolean();
+ final MutableBoolean revisionTimestampFound = new MutableBoolean();
+ final MutableBoolean modifiedEntityNamesFound = new MutableBoolean();
- MutableBoolean revisionNumberFound = new MutableBoolean();
- MutableBoolean revisionTimestampFound = new MutableBoolean();
- MutableBoolean modifiedEntityNamesFound = new MutableBoolean();
+ searchForRevisionInfoCfg(
+ clazz,
+ reflectionManager,
+ revisionNumberFound,
+ revisionTimestampFound,
+ modifiedEntityNamesFound
+ );
- searchForRevisionInfoCfg(clazz, reflectionManager, revisionNumberFound, revisionTimestampFound, modifiedEntityNamesFound);
+ if ( !revisionNumberFound.isSet() ) {
+ throw new MappingException(
+ "An entity annotated with @RevisionEntity must have a field annotated " +
+ "with @RevisionNumber!"
+ );
+ }
- if (!revisionNumberFound.isSet()) {
- throw new MappingException("An entity annotated with @RevisionEntity must have a field annotated " +
- "with @RevisionNumber!");
- }
+ if ( !revisionTimestampFound.isSet() ) {
+ throw new MappingException(
+ "An entity annotated with @RevisionEntity must have a field annotated " +
+ "with @RevisionTimestamp!"
+ );
+ }
- if (!revisionTimestampFound.isSet()) {
- throw new MappingException("An entity annotated with @RevisionEntity must have a field annotated " +
- "with @RevisionTimestamp!");
- }
+ revisionInfoEntityName = pc.getEntityName();
+ revisionInfoClass = pc.getMappedClass();
+ final Class extends RevisionListener> revisionListenerClass = getRevisionListenerClass( revisionEntity.value() );
+ revisionInfoTimestampType = pc.getProperty( revisionInfoTimestampData.getName() ).getType();
+ if ( globalCfg.isTrackEntitiesChangedInRevision()
+ || (globalCfg.isUseRevisionEntityWithNativeId() && DefaultTrackingModifiedEntitiesRevisionEntity.class
+ .isAssignableFrom( revisionInfoClass ))
+ || (!globalCfg.isUseRevisionEntityWithNativeId() && SequenceIdTrackingModifiedEntitiesRevisionEntity.class
+ .isAssignableFrom( revisionInfoClass ))
+ || modifiedEntityNamesFound.isSet() ) {
+ // If tracking modified entities parameter is enabled, custom revision info entity is a subtype
+ // of DefaultTrackingModifiedEntitiesRevisionEntity class, or @ModifiedEntityNames annotation is used.
+ revisionInfoGenerator = new DefaultTrackingModifiedEntitiesRevisionInfoGenerator(
+ revisionInfoEntityName,
+ revisionInfoClass, revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate(),
+ modifiedEntityNamesData
+ );
+ globalCfg.setTrackEntitiesChangedInRevision( true );
+ }
+ else {
+ revisionInfoGenerator = new DefaultRevisionInfoGenerator(
+ revisionInfoEntityName, revisionInfoClass,
+ revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate()
+ );
+ }
+ }
+ }
- revisionInfoEntityName = pc.getEntityName();
- revisionInfoClass = pc.getMappedClass();
- Class extends RevisionListener> revisionListenerClass = getRevisionListenerClass(revisionEntity.value());
- revisionInfoTimestampType = pc.getProperty(revisionInfoTimestampData.getName()).getType();
- if (globalCfg.isTrackEntitiesChangedInRevision()
- || (globalCfg.isUseRevisionEntityWithNativeId() && DefaultTrackingModifiedEntitiesRevisionEntity.class.isAssignableFrom(revisionInfoClass))
- || (!globalCfg.isUseRevisionEntityWithNativeId() && SequenceIdTrackingModifiedEntitiesRevisionEntity.class.isAssignableFrom(revisionInfoClass))
- || modifiedEntityNamesFound.isSet()) {
- // If tracking modified entities parameter is enabled, custom revision info entity is a subtype
- // of DefaultTrackingModifiedEntitiesRevisionEntity class, or @ModifiedEntityNames annotation is used.
- revisionInfoGenerator = new DefaultTrackingModifiedEntitiesRevisionInfoGenerator(revisionInfoEntityName,
- revisionInfoClass, revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate(),
- modifiedEntityNamesData);
- globalCfg.setTrackEntitiesChangedInRevision(true);
- } else {
- revisionInfoGenerator = new DefaultRevisionInfoGenerator(revisionInfoEntityName, revisionInfoClass,
- revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate());
- }
- }
- }
+ // In case of a custom revision info generator, the mapping will be null.
+ Document revisionInfoXmlMapping = null;
- // In case of a custom revision info generator, the mapping will be null.
- Document revisionInfoXmlMapping = null;
+ final Class extends RevisionListener> revisionListenerClass = getRevisionListenerClass( RevisionListener.class );
- Class extends RevisionListener> revisionListenerClass = getRevisionListenerClass(RevisionListener.class);
+ if ( revisionInfoGenerator == null ) {
+ if ( globalCfg.isTrackEntitiesChangedInRevision() ) {
+ revisionInfoClass = globalCfg.isUseRevisionEntityWithNativeId() ?
+ DefaultTrackingModifiedEntitiesRevisionEntity.class
+ :
+ SequenceIdTrackingModifiedEntitiesRevisionEntity.class;
+ revisionInfoEntityName = revisionInfoClass.getName();
+ revisionInfoGenerator = new DefaultTrackingModifiedEntitiesRevisionInfoGenerator(
+ revisionInfoEntityName, revisionInfoClass,
+ revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate(), modifiedEntityNamesData
+ );
+ }
+ else {
+ revisionInfoClass = globalCfg.isUseRevisionEntityWithNativeId() ? DefaultRevisionEntity.class
+ : SequenceIdRevisionEntity.class;
+ revisionInfoGenerator = new DefaultRevisionInfoGenerator(
+ revisionInfoEntityName, revisionInfoClass,
+ revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate()
+ );
+ }
+ revisionInfoXmlMapping = generateDefaultRevisionInfoXmlMapping();
+ }
- if (revisionInfoGenerator == null) {
- if (globalCfg.isTrackEntitiesChangedInRevision()) {
- revisionInfoClass = globalCfg.isUseRevisionEntityWithNativeId() ? DefaultTrackingModifiedEntitiesRevisionEntity.class
- : SequenceIdTrackingModifiedEntitiesRevisionEntity.class;
- revisionInfoEntityName = revisionInfoClass.getName();
- revisionInfoGenerator = new DefaultTrackingModifiedEntitiesRevisionInfoGenerator(revisionInfoEntityName, revisionInfoClass,
- revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate(), modifiedEntityNamesData);
- } else {
- revisionInfoClass = globalCfg.isUseRevisionEntityWithNativeId() ? DefaultRevisionEntity.class
- : SequenceIdRevisionEntity.class;
- revisionInfoGenerator = new DefaultRevisionInfoGenerator(revisionInfoEntityName, revisionInfoClass,
- revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate());
- }
- revisionInfoXmlMapping = generateDefaultRevisionInfoXmlMapping();
- }
+ return new RevisionInfoConfigurationResult(
+ revisionInfoGenerator, revisionInfoXmlMapping,
+ new RevisionInfoQueryCreator(
+ revisionInfoEntityName, revisionInfoIdData.getName(),
+ revisionInfoTimestampData.getName(), isTimestampAsDate()
+ ),
+ generateRevisionInfoRelationMapping(),
+ new RevisionInfoNumberReader( revisionInfoClass, revisionInfoIdData ),
+ globalCfg.isTrackEntitiesChangedInRevision() ? new ModifiedEntityNamesReader(
+ revisionInfoClass,
+ modifiedEntityNamesData
+ )
+ : null,
+ revisionInfoEntityName, revisionInfoClass, revisionInfoTimestampData
+ );
+ }
- return new RevisionInfoConfigurationResult(
- revisionInfoGenerator, revisionInfoXmlMapping,
- new RevisionInfoQueryCreator(revisionInfoEntityName, revisionInfoIdData.getName(),
- revisionInfoTimestampData.getName(), isTimestampAsDate()),
- generateRevisionInfoRelationMapping(),
- new RevisionInfoNumberReader(revisionInfoClass, revisionInfoIdData),
- globalCfg.isTrackEntitiesChangedInRevision() ? new ModifiedEntityNamesReader(revisionInfoClass, modifiedEntityNamesData)
- : null,
- revisionInfoEntityName, revisionInfoClass, revisionInfoTimestampData);
- }
+ private boolean isTimestampAsDate() {
+ final String typename = revisionInfoTimestampType.getName();
+ return "date".equals( typename ) || "time".equals( typename ) || "timestamp".equals( typename );
+ }
- private boolean isTimestampAsDate() {
- String typename = revisionInfoTimestampType.getName();
- return "date".equals(typename) || "time".equals(typename) || "timestamp".equals(typename);
- }
-
- /**
- * @param defaultListener Revision listener that shall be applied if {@code org.hibernate.envers.revision_listener}
- * parameter has not been set.
- * @return Revision listener.
- */
- private Class extends RevisionListener> getRevisionListenerClass(Class extends RevisionListener> defaultListener) {
- if (globalCfg.getRevisionListenerClass() != null) {
- return globalCfg.getRevisionListenerClass();
- }
- return defaultListener;
- }
+ /**
+ * @param defaultListener Revision listener that shall be applied if {@code org.hibernate.envers.revision_listener}
+ * parameter has not been set.
+ *
+ * @return Revision listener.
+ */
+ private Class extends RevisionListener> getRevisionListenerClass(Class extends RevisionListener> defaultListener) {
+ if ( globalCfg.getRevisionListenerClass() != null ) {
+ return globalCfg.getRevisionListenerClass();
+ }
+ return defaultListener;
+ }
}
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfigurationResult.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfigurationResult.java
index 0b89067929..33267cfc33 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfigurationResult.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfigurationResult.java
@@ -1,3 +1,26 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2013, Red Hat Inc. 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 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.envers.configuration.internal;
import org.dom4j.Document;
@@ -23,11 +46,12 @@ public class RevisionInfoConfigurationResult {
private final Class> revisionInfoClass;
private final PropertyData revisionInfoTimestampData;
- RevisionInfoConfigurationResult(RevisionInfoGenerator revisionInfoGenerator,
- Document revisionInfoXmlMapping, RevisionInfoQueryCreator revisionInfoQueryCreator,
- Element revisionInfoRelationMapping, RevisionInfoNumberReader revisionInfoNumberReader,
- ModifiedEntityNamesReader modifiedEntityNamesReader, String revisionInfoEntityName,
- Class> revisionInfoClass, PropertyData revisionInfoTimestampData) {
+ RevisionInfoConfigurationResult(
+ RevisionInfoGenerator revisionInfoGenerator,
+ Document revisionInfoXmlMapping, RevisionInfoQueryCreator revisionInfoQueryCreator,
+ Element revisionInfoRelationMapping, RevisionInfoNumberReader revisionInfoNumberReader,
+ ModifiedEntityNamesReader modifiedEntityNamesReader, String revisionInfoEntityName,
+ Class> revisionInfoClass, PropertyData revisionInfoTimestampData) {
this.revisionInfoGenerator = revisionInfoGenerator;
this.revisionInfoXmlMapping = revisionInfoXmlMapping;
this.revisionInfoQueryCreator = revisionInfoQueryCreator;
diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditEntityNameRegister.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditEntityNameRegister.java
index c2d00fdcf6..8f5b76a05c 100644
--- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditEntityNameRegister.java
+++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditEntityNameRegister.java
@@ -1,4 +1,28 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2013, Red Hat Inc. 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 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.envers.configuration.internal.metadata;
+
import java.util.HashSet;
import java.util.Set;
@@ -6,46 +30,49 @@ import org.hibernate.MappingException;
/**
* A register of all audit entity names used so far.
+ *
* @author Adam Warski (adam at warski dot org)
*/
public class AuditEntityNameRegister {
- private final Set auditEntityNames = new HashSet();
+ private final Set auditEntityNames = new HashSet