merge master

This commit is contained in:
Strong Liu 2013-04-15 18:33:46 +08:00
commit f29a670378
730 changed files with 19826 additions and 8092 deletions

View File

@ -4,9 +4,8 @@ apply from: "./libraries.gradle"
allprojects { allprojects {
repositories { repositories {
mavenCentral() mavenCentral()
mavenLocal() mavenLocal()
mavenRepo name: 'jboss-nexus', url: "http://repository.jboss.org/nexus/content/groups/public/" mavenRepo name: 'jboss-nexus', url: "http://repository.jboss.org/nexus/content/groups/public/"
mavenRepo name: "jboss-snapshots", url: "http://snapshots.jboss.org/maven2/" mavenRepo name: "jboss-snapshots", url: "http://snapshots.jboss.org/maven2/"
} }
@ -14,8 +13,8 @@ allprojects {
buildscript { buildscript {
repositories { repositories {
mavenCentral() mavenCentral()
mavenLocal() mavenLocal()
mavenRepo name: 'jboss-nexus', url: "http://repository.jboss.org/nexus/content/groups/public/" mavenRepo name: 'jboss-nexus', url: "http://repository.jboss.org/nexus/content/groups/public/"
mavenRepo name: "jboss-snapshots", url: "http://snapshots.jboss.org/maven2/" mavenRepo name: "jboss-snapshots", url: "http://snapshots.jboss.org/maven2/"
@ -26,10 +25,15 @@ buildscript {
} }
ext.hibernateTargetVersion = '5.0.0-SNAPSHOT' ext.hibernateTargetVersion = '5.0.0-SNAPSHOT'
ext.javaLanguageLevel = "1.6"
task wrapper(type: Wrapper) {
gradleVersion = '1.5'
}
idea { idea {
project { project {
languageLevel = '1.6' languageLevel = javaLanguageLevel
ipr { ipr {
withXml { provider -> withXml { provider ->
provider.node.component.find { it.@name == 'VcsDirectoryMappings' }.mapping.@vcs = 'Git' provider.node.component.find { it.@name == 'VcsDirectoryMappings' }.mapping.@vcs = 'Git'
@ -65,8 +69,14 @@ subprojects { subProject ->
apply plugin: 'maven' // for install task as well as deploy dependencies apply plugin: 'maven' // for install task as well as deploy dependencies
apply plugin: 'uploadAuth' apply plugin: 'uploadAuth'
apply plugin: 'osgi' apply plugin: 'osgi'
apply from: "../utilities.gradle" apply from: "../utilities.gradle"
apply plugin: 'findbugs'
apply plugin: 'checkstyle'
apply plugin: 'build-dashboard'
apply plugin: 'project-report'
configurations { configurations {
provided { provided {
// todo : need to make sure these are non-exported // todo : need to make sure these are non-exported
@ -93,6 +103,7 @@ subprojects { subProject ->
// appropriately inject the common dependencies into each sub-project // appropriately inject the common dependencies into each sub-project
dependencies { dependencies {
compile( libraries.logging ) compile( libraries.logging )
testCompile( libraries.junit ) testCompile( libraries.junit )
testCompile( libraries.byteman ) testCompile( libraries.byteman )
testCompile( libraries.byteman_install ) testCompile( libraries.byteman_install )
@ -104,8 +115,11 @@ subprojects { subProject ->
testRuntime( libraries.jcl ) testRuntime( libraries.jcl )
testRuntime( libraries.javassist ) testRuntime( libraries.javassist )
testRuntime( libraries.h2 ) testRuntime( libraries.h2 )
jbossLoggingTool( libraries.logging_processor ) jbossLoggingTool( libraries.logging_processor )
hibernateJpaModelGenTool( libraries.jpa_modelgen ) hibernateJpaModelGenTool( libraries.jpa_modelgen )
jaxb( libraries.jaxb ){ jaxb( libraries.jaxb ){
exclude group: "javax.xml.stream" exclude group: "javax.xml.stream"
} }
@ -117,12 +131,17 @@ subprojects { subProject ->
deployerJars "org.apache.maven.wagon:wagon-http:1.0" deployerJars "org.apache.maven.wagon:wagon-http:1.0"
} }
// mac-specific stuff ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ext.toolsJar = file("${System.getProperty('java.home')}/../lib/tools.jar") ext.toolsJar = file("${System.getProperty('java.home')}/../lib/tools.jar")
if ( ext.toolsJar.exists() ) { if ( ext.toolsJar.exists() ) {
dependencies{ dependencies{
testCompile files( toolsJar ) testCompile files( toolsJar )
} }
} }
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
targetCompatibility = rootProject.javaLanguageLevel
sourceCompatibility = rootProject.javaLanguageLevel
task compile task compile
compile.dependsOn compileJava, compileTestJava compile.dependsOn compileJava, compileTestJava
@ -150,8 +169,8 @@ subprojects { subProject ->
"-processor", "org.jboss.logging.processor.apt.LoggingToolsProcessor", "-processor", "org.jboss.logging.processor.apt.LoggingToolsProcessor",
"-s", "$sourceSets.main.generatedLoggingSrcDir.absolutePath", "-s", "$sourceSets.main.generatedLoggingSrcDir.absolutePath",
"-AloggingVersion=3.0", "-AloggingVersion=3.0",
"-source", "1.6", "-source", rootProject.javaLanguageLevel,
"-target", "1.6", "-target", rootProject.javaLanguageLevel,
"-AtranslationFilesPath=${project.rootDir}/src/main/resources" "-AtranslationFilesPath=${project.rootDir}/src/main/resources"
] ]
); );
@ -177,33 +196,33 @@ subprojects { subProject ->
jar { jar {
Set<String> exportPackages = new HashSet<String>() Set<String> exportPackages = new HashSet<String>()
Set<String> privatePackages = new HashSet<String>() Set<String> privatePackages = new HashSet<String>()
// TODO: Could more of this be pulled into utilities.gradle? // TODO: Could more of this be pulled into utilities.gradle?
sourceSets.each { SourceSet sourceSet -> sourceSets.each { sourceSet ->
// skip certain source sets // skip certain source sets
if ( ! ['test','matrix'].contains( sourceSet.name ) ) { if ( ! ['test','matrix'].contains( sourceSet.name ) ) {
sourceSet.java.each { javaFile -> sourceSet.java.each { javaFile ->
// - org.hibernate.boot.registry.classloading.internal // - org.hibernate.boot.registry.classloading.internal
// until EntityManagerFactoryBuilderImpl no longer imports ClassLoaderServiceImpl // until EntityManagerFactoryBuilderImpl no longer imports ClassLoaderServiceImpl
// - .util for external module use (especially envers) // - .util for external module use (especially envers)
final String[] temporaryExports = [ final String[] temporaryExports = [
'org.hibernate.boot.registry.classloading.internal', 'org.hibernate.boot.registry.classloading.internal',
'org.hibernate.internal.util' ] 'org.hibernate.internal.util' ]
final String packageName = determinePackageName( sourceSet.java, javaFile ); final String packageName = determinePackageName( sourceSet.java, javaFile );
if ( ! temporaryExports.contains( packageName ) if ( ! temporaryExports.contains( packageName )
&& ( packageName.endsWith( ".internal" ) && ( packageName.endsWith( ".internal" )
|| packageName.contains( ".internal." ) || packageName.contains( ".internal." )
|| packageName.endsWith( ".test" ) || packageName.endsWith( ".test" )
|| packageName.contains( ".test." ) ) ) { || packageName.contains( ".test." ) ) ) {
privatePackages.add( packageName ); privatePackages.add( packageName );
} }
else { else {
exportPackages.add( packageName ); exportPackages.add( packageName );
}
}
} }
} }
}
}
manifest = osgiManifest { manifest = osgiManifest {
// GRADLE-1411: Even if we override Imports and Exports // GRADLE-1411: Even if we override Imports and Exports
@ -211,11 +230,17 @@ subprojects { subProject ->
// need to be here (temporarily). // need to be here (temporarily).
classesDir = sourceSets.main.output.classesDir classesDir = sourceSets.main.output.classesDir
classpath = configurations.runtime classpath = configurations.runtime
instruction 'Import-Package',
// Temporarily support JTA 1.1 -- Karaf and other frameworks still
// use it. Without this, the plugin generates [1.2,2).
'javax.transaction;version="[1.1,2)"',
'*'
instruction 'Export-Package', exportPackages.toArray(new String[0]) instruction 'Export-Package', exportPackages.toArray(new String[0])
instruction 'Private-Package', privatePackages.toArray(new String[0]) instruction 'Private-Package', privatePackages.toArray(new String[0])
instruction 'Bundle-Vendor', 'Hibernate.org'
instruction 'Bundle-Vendor', 'Hibernate.org'
instruction 'Implementation-Url', 'http://hibernate.org' instruction 'Implementation-Url', 'http://hibernate.org'
instruction 'Implementation-Version', version instruction 'Implementation-Version', version
instruction 'Implementation-Vendor', 'Hibernate.org' instruction 'Implementation-Vendor', 'Hibernate.org'
@ -234,10 +259,10 @@ subprojects { subProject ->
systemProperties['hibernate.test.validatefailureexpected'] = true systemProperties['hibernate.test.validatefailureexpected'] = true
systemProperties += System.properties.findAll { it.key.startsWith( "hibernate.") } systemProperties += System.properties.findAll { it.key.startsWith( "hibernate.") }
maxHeapSize = "1024m" maxHeapSize = "1024m"
// Not strictly needed but useful to attach a profiler:
jvmArgs '-XX:MaxPermSize=256m'
} }
processTestResources.doLast( { processTestResources.doLast( {
copy { copy {
from( sourceSets.test.java.srcDirs ) { from( sourceSets.test.java.srcDirs ) {
@ -251,9 +276,6 @@ subprojects { subProject ->
assemble.doLast( { install } ) assemble.doLast( { install } )
uploadArchives.dependsOn install uploadArchives.dependsOn install
targetCompatibility = "1.6"
sourceCompatibility = "1.6"
idea { idea {
module { module {
iml { iml {
@ -287,6 +309,40 @@ subprojects { subProject ->
} }
} }
// eclipseClasspath will not add sources to classpath unless the dirs actually exist.
eclipseClasspath.dependsOn("generateSources")
// specialized API/SPI checkstyle tasks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
task checkstylePublicSources(type: Checkstyle) {
checkstyleClasspath = checkstyleMain.checkstyleClasspath
classpath = checkstyleMain.classpath
configFile = rootProject.file( 'shared/config/checkstyle/public_checks.xml' )
source subProject.sourceSets.main.originalJavaSrcDirs
exclude '**/internal/**'
exclude '**/internal/*'
ignoreFailures = false
showViolations = true
reports {
xml {
destination "$buildDir/reports/checkstyle/public.xml"
}
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Report configs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
checkstyle {
configFile = rootProject.file( 'shared/config/checkstyle/checkstyle.xml' )
showViolations = false
ignoreFailures = true
}
findbugs {
ignoreFailures = true
}
buildDashboard.dependsOn check
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// elements used to customize the generated POM used during upload // elements used to customize the generated POM used during upload
def pomConfig = { def pomConfig = {
name 'A Hibernate O/RM Module' name 'A Hibernate O/RM Module'
@ -352,13 +408,3 @@ subprojects { subProject ->
} }
} }
// This is a task that generates the gradlew scripts, allowing users to run gradle without having gradle installed
// on their system.
// This task should be run by "build master" and the resulting output committed to source control. Its outputs include:
// 1) /gradlew which is the *NIX shell script for executing builds
// 2) /gradlew.bat which is the windows bat script for for executing builds
// 3) /wrapper which is a directory named by the "jarPath" config which contains other needed files.
task wrapper(type: Wrapper) {
gradleVersion = '1.5'
}

View File

@ -51,9 +51,10 @@ class DatabaseAllocator {
public static def SUPPORTED_DB_NAMES = [ public static def SUPPORTED_DB_NAMES = [
"oracle9i", "oracle10g", "oracle11gR1", "oracle11gR2", "oracle11gR2RAC", "oracle11gR1RAC", "oracle9i", "oracle10g", "oracle11gR1", "oracle11gR2", "oracle11gR2RAC", "oracle11gR1RAC",
"postgresql82", "postgresql83", "postgresql84", "postgresql91", "postgresql82", "postgresql83", "postgresql84", "postgresql91", "postgresql92",
"postgresplus92",
"mysql50", "mysql51","mysql55", "mysql50", "mysql51","mysql55",
"db2-91", "db2-97", "db2-91", "db2-97", "db2-10",
"mssql2005", "mssql2008R1", "mssql2008R2", "mssql2012", "mssql2005", "mssql2008R1", "mssql2008R2", "mssql2012",
"sybase155", "sybase157" "sybase155", "sybase157"
]; ];

View File

@ -4890,7 +4890,7 @@ Changes in version 0.9.5 (8.2.2002)
* fixed potential bug related to cacheing of compiled queries * fixed potential bug related to cacheing of compiled queries
* major rewrite of code relating to O-R mappings * major rewrite of code relating to O-R mappings
* Session.copy() and Session.equals() as convenience for users * Session.copy() and Session.equals() as convenience for users
* fixed repeated invocations of hasNext() on iterator + iterators now always work with distinct SQL resultsets * fixed repeated invocations of hasNext() on iterator + wrappedIterators now always work with distinct SQL resultsets
* McKoi dialect was contributed by Gabe Hicks * McKoi dialect was contributed by Gabe Hicks
Changes in version 0.9.4 (29.1.2002) Changes in version 0.9.4 (29.1.2002)

View File

@ -1,4 +1,4 @@
<?xml version='1.0' encoding='utf-8' ?> <?xml version='1.0' encoding='utf-8'?>
<chapter xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink" > <chapter xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink" >
<info> <info>
@ -40,7 +40,7 @@
which stores the historical data, whenever you commit a transaction. Envers automatically creates audit which stores the historical data, whenever you commit a transaction. Envers automatically creates audit
tables if <literal>hibernate.hbm2ddl.auto</literal> option is set to <literal>create</literal>, tables if <literal>hibernate.hbm2ddl.auto</literal> option is set to <literal>create</literal>,
<literal>create-drop</literal> or <literal>update</literal>. Otherwise, to export complete database schema <literal>create-drop</literal> or <literal>update</literal>. Otherwise, to export complete database schema
programatically, use <literal>org.hibernate.tool.EnversSchemaGenerator</literal>. Appropriate DDL programatically, use <literal>org.hibernate.envers.tools.hbm2ddl.EnversSchemaGenerator</literal>. Appropriate DDL
statements can be also generated with Ant task described later in this manual. statements can be also generated with Ant task described later in this manual.
</para> </para>
@ -58,7 +58,7 @@
</para> </para>
</section> </section>
<section> <section xml:id="envers-configuration">
<title>Configuration</title> <title>Configuration</title>
<para> <para>
It is possible to configure various aspects of Hibernate Envers behavior, such as table names, etc. It is possible to configure various aspects of Hibernate Envers behavior, such as table names, etc.
@ -300,7 +300,7 @@
When set to false, such column can be added to selected entities or properties using the When set to false, such column can be added to selected entities or properties using the
<literal>@Audited</literal> annotation. <literal>@Audited</literal> annotation.
For more information refer to <xref linkend="envers-tracking-properties-changes"/> For more information refer to <xref linkend="envers-tracking-properties-changes"/>
and <xref linkend="envers-envers-tracking-properties-changes-queries"/>. and <xref linkend="envers-tracking-properties-changes-queries"/>.
</entry> </entry>
</row> </row>
<row> <row>
@ -315,6 +315,17 @@
For example: a property called "age", will by default get modified flag with column name "age_MOD". For example: a property called "age", will by default get modified flag with column name "age_MOD".
</entry> </entry>
</row> </row>
<row>
<entry>
<property>org.hibernate.envers.embeddable_set_ordinal_field_name</property>
</entry>
<entry>
SETORDINAL
</entry>
<entry>
Name of column used for storing ordinal of the change in sets of embeddable elements.
</entry>
</row>
</tbody> </tbody>
</tgroup> </tgroup>
</table> </table>
@ -480,7 +491,7 @@
class is inaccessible from <interfacename>@RevisionEntity</interfacename> (e.g. exists in a different class is inaccessible from <interfacename>@RevisionEntity</interfacename> (e.g. exists in a different
module), set <property>org.hibernate.envers.revision_listener</property> property to it's fully module), set <property>org.hibernate.envers.revision_listener</property> property to it's fully
qualified name. Class name defined by the configuration parameter overrides revision entity's qualified name. Class name defined by the configuration parameter overrides revision entity's
<methodname>value</methodname> attribute. <methodname>value</methodname> attribute.
</para> </para>
</listitem> </listitem>
</orderedlist> </orderedlist>
@ -621,7 +632,7 @@ public class AnnotatedTrackingRevisionEntity {
<interfacename>EntityTrackingRevisionListener</interfacename> interface exposes one method that notifies <interfacename>EntityTrackingRevisionListener</interfacename> interface exposes one method that notifies
whenever audited entity instance has been added, modified or removed within current revision boundaries. whenever audited entity instance has been added, modified or removed within current revision boundaries.
</para> </para>
<example> <example>
<title>Custom implementation of tracking entity classes modified during revisions</title> <title>Custom implementation of tracking entity classes modified during revisions</title>
<programlisting> <programlisting>
@ -735,7 +746,7 @@ Set<ModifiedEntityTypeEntity> modifiedEntityTypes = revEntity.getModifiedEntityT
</para> </para>
<para> <para>
To see how "Modified Flags" can be utilized, check out the very To see how "Modified Flags" can be utilized, check out the very
simple query API that uses them: <xref linkend="envers-envers-tracking-properties-changes-queries"/>. simple query API that uses them: <xref linkend="envers-tracking-properties-changes-queries"/>.
</para> </para>
</section> </section>
@ -771,7 +782,7 @@ Set<ModifiedEntityTypeEntity> modifiedEntityTypes = revEntity.getModifiedEntityT
<para> <para>
In the future, queries will be improved both in terms of speed and possibilities, when using the valid-time In the future, queries will be improved both in terms of speed and possibilities, when using the valid-time
audit strategy, that is when storing both start and end revisions for entities. See audit strategy, that is when storing both start and end revisions for entities. See
<xref linkend="configuration"/>. <xref linkend="envers-configuration"/>.
</para> </para>
<section xml:id="entities-at-revision"> <section xml:id="entities-at-revision">
@ -929,7 +940,7 @@ query.add(AuditEntity.relatedId("address").eq(relatedEntityId));]]></programlist
</section> </section>
<section xml:id="envers-envers-tracking-properties-changes-queries"> <section xml:id="envers-tracking-properties-changes-queries">
<title>Querying for revisions of entity that modified given property</title> <title>Querying for revisions of entity that modified given property</title>
@ -948,11 +959,10 @@ query.add(AuditEntity.relatedId("address").eq(relatedEntityId));]]></programlist
Let's have a look at following examples: Let's have a look at following examples:
</para> </para>
<programlisting><![CDATA[ <programlisting><![CDATA[AuditQuery query = getAuditReader().createQuery()
AuditQuery query = getAuditReader().createQuery() .forRevisionsOfEntity(MyEntity.class, false, true)
.forRevisionsOfEntity(MyEntity.class, false, true) .add(AuditEntity.id().eq(id));
.add(AuditEntity.id().eq(id)); .add(AuditEntity.property("actualDate").hasChanged())]]>
.add(AuditEntity.property("actualDate").hasChanged())]]>
</programlisting> </programlisting>
<para> <para>
@ -967,11 +977,10 @@ query.add(AuditEntity.relatedId("address").eq(relatedEntityId));]]></programlist
can be used here in a normal way. can be used here in a normal way.
</para> </para>
<programlisting><![CDATA[ <programlisting><![CDATA[AuditQuery query = getAuditReader().createQuery()
AuditQuery query = getAuditReader().createQuery() .forEntitiesAtRevision(MyEntity.class, revisionNumber)
.forEntitiesAtRevision(MyEntity.class, revisionNumber) .add(AuditEntity.property("prop1").hasChanged())
.add(AuditEntity.property("prop1").hasChanged()) .add(AuditEntity.property("prop2").hasNotChanged());]]>
.add(AuditEntity.property("prop2").hasNotChanged());]]>
</programlisting> </programlisting>
<para> <para>
@ -991,11 +1000,10 @@ query.add(AuditEntity.relatedId("address").eq(relatedEntityId));]]></programlist
<literal>forEntitiesModifiedAtRevision</literal> query: <literal>forEntitiesModifiedAtRevision</literal> query:
</para> </para>
<programlisting><![CDATA[ <programlisting><![CDATA[AuditQuery query = getAuditReader().createQuery()
AuditQuery query = getAuditReader().createQuery() .forEntitiesModifiedAtRevision(MyEntity.class, revisionNumber)
.forEntitiesModifiedAtRevision(MyEntity.class, revisionNumber) .add(AuditEntity.property("prop1").hasChanged())
.add(AuditEntity.property("prop1").hasChanged()) .add(AuditEntity.property("prop2").hasNotChanged());]]>
.add(AuditEntity.property("prop2").hasNotChanged());]]>
</programlisting> </programlisting>
</section> </section>
@ -1049,7 +1057,7 @@ query.add(AuditEntity.relatedId("address").eq(relatedEntityId));]]></programlist
<title>Conditional auditing</title> <title>Conditional auditing</title>
<para> <para>
Envers persists audit data in reaction to various Hibernate events (e.g. post update, post insert, and Envers persists audit data in reaction to various Hibernate events (e.g. post update, post insert, and
so on), using a series of even listeners from the <literal>org.hibernate.envers.event</literal> so on), using a series of even listeners from the <literal>org.hibernate.envers.event.spi</literal>
package. By default, if the Envers jar is in the classpath, the event listeners are auto-registered with package. By default, if the Envers jar is in the classpath, the event listeners are auto-registered with
Hibernate. Hibernate.
</para> </para>
@ -1062,13 +1070,13 @@ query.add(AuditEntity.relatedId("address").eq(relatedEntityId));]]></programlist
Turn off automatic Envers event listeners registration by setting the Turn off automatic Envers event listeners registration by setting the
<literal>hibernate.listeners.envers.autoRegister</literal> Hibernate property to <literal>hibernate.listeners.envers.autoRegister</literal> Hibernate property to
<literal>false</literal>. <literal>false</literal>.
</para> </para>
</listitem> </listitem>
<listitem> <listitem>
<para> <para>
Create subclasses for appropriate event listeners. For example, if you want to Create subclasses for appropriate event listeners. For example, if you want to
conditionally audit entity insertions, extend the conditionally audit entity insertions, extend the
<literal>org.hibernate.envers.eventEnversPostInsertEventListenerImpl</literal> <literal>org.hibernate.envers.event.spi.EnversPostInsertEventListenerImpl</literal>
class. Place the conditional-auditing logic in the subclasses, call the super method if class. Place the conditional-auditing logic in the subclasses, call the super method if
auditing should be performed. auditing should be performed.
</para> </para>
@ -1076,7 +1084,7 @@ query.add(AuditEntity.relatedId("address").eq(relatedEntityId));]]></programlist
<listitem> <listitem>
<para> <para>
Create your own implementation of <literal>org.hibernate.integrator.spi.Integrator</literal>, Create your own implementation of <literal>org.hibernate.integrator.spi.Integrator</literal>,
similar to <literal>org.hibernate.envers.event.EnversIntegrator</literal>. Use your event similar to <literal>org.hibernate.envers.event.spi.EnversIntegrator</literal>. Use your event
listener classes instead of the default ones. listener classes instead of the default ones.
</para> </para>
</listitem> </listitem>
@ -1398,7 +1406,7 @@ query.add(AuditEntity.relatedId("address").eq(relatedEntityId));]]></programlist
</para> </para>
<para> <para>
Optionally, you can also override the default values following properties: Optionally, you can also override the default values using following properties:
</para> </para>
<para> <para>
<literal>org.hibernate.envers.audit_strategy_validity_end_rev_field_name</literal> <literal>org.hibernate.envers.audit_strategy_validity_end_rev_field_name</literal>
@ -1408,7 +1416,7 @@ query.add(AuditEntity.relatedId("address").eq(relatedEntityId));]]></programlist
</para> </para>
<para> <para>
For more information, see <xref linkend="configuration"/>. For more information, see <xref linkend="envers-configuration"/>.
</para> </para>
</note> </note>
</para> </para>

View File

@ -584,13 +584,16 @@ public class Order {
</example> </example>
<note> <note>
<para>We recommend you to convert <classname>the legacy <para>
@org.hibernate.annotations.IndexColumn</classname> usages to We recommend you to convert the legacy <classname>@org.hibernate.annotations.IndexColumn</classname>
<classname>@OrderColumn</classname> unless you are making use of the usages to the JPA standard <classname>@javax.persistence.OrderColumn</classname>.
base property. The <literal>base</literal> property lets you define </para>
the index value of the first element (aka as base index). The usual <para>
value is <literal>0</literal> or <literal>1</literal>. The default If you are leveraging a custom list index base (maybe currently using the
is 0 like in Java.</para> <methodname>org.hibernate.annotations.IndexColumn.literal</methodname> attribute), you can
specify this using the <classname>@org.hibernate.annotations.ListIndexBase</classname> in conjunction
with <classname>@javax.persistence.OrderColumn</classname>. The default base is 0 like in Java.
</para>
</note> </note>
<para>Looking again at the Hibernate mapping file equivalent, the <para>Looking again at the Hibernate mapping file equivalent, the

View File

@ -13,6 +13,5 @@ dependencies {
jar { jar {
manifest { manifest {
instruction 'Bundle-Description', 'Hibernate ORM C3P0' instruction 'Bundle-Description', 'Hibernate ORM C3P0'
instruction 'Bundle-SymbolicName', 'org.hibernate.c3p0'
} }
} }

View File

@ -40,7 +40,6 @@ manifest.mainAttributes(
jar { jar {
manifest { manifest {
instruction 'Bundle-Description', 'Hibernate ORM Core' instruction 'Bundle-Description', 'Hibernate ORM Core'
instruction 'Bundle-SymbolicName', 'org.hibernate.core'
instruction 'Import-Package', instruction 'Import-Package',
'javax.security.auth;resolution:=optional', 'javax.security.auth;resolution:=optional',
@ -49,6 +48,13 @@ jar {
'javax.validation.constraints;resolution:=optional', 'javax.validation.constraints;resolution:=optional',
'javax.validation.groups;resolution:=optional', 'javax.validation.groups;resolution:=optional',
'javax.validation.metadata;resolution:=optional', 'javax.validation.metadata;resolution:=optional',
// TODO: Shouldn't have to explicitly list this, but the plugin
// generates it with a [1.0,2) version.
'javax.persistence;version="2.1.0"',
// Temporarily support JTA 1.1 -- Karaf and other frameworks still
// use it. Without this, the plugin generates [1.2,2).
// build.gradle adds javax.transaction for all modules
'javax.transaction.xa;version="[1.1,2)"',
'*' '*'
// TODO: Uncomment once EntityManagerFactoryBuilderImpl no longer // TODO: Uncomment once EntityManagerFactoryBuilderImpl no longer

View File

@ -23,25 +23,30 @@
*/ */
package org.hibernate; package org.hibernate;
/** /**
* Annotation related exception. * Annotation related exception.
* The EJB3 EG will probably set a generic exception. *
* I'll then use this one. * The EJB3 EG will probably set a generic exception. I'll then use this one.
* *
* @author Emmanuel Bernard * @author Emmanuel Bernard
*/ */
public class AnnotationException extends MappingException { public class AnnotationException extends MappingException {
/**
public AnnotationException(String msg, Throwable root) { * Constructs an AnnotationException using the given message and cause.
super( msg, root ); *
* @param msg The message explaining the reason for the exception.
* @param cause The underlying cause.
*/
public AnnotationException(String msg, Throwable cause) {
super( msg, cause );
} }
public AnnotationException(Throwable root) { /**
super( root ); * Constructs an AnnotationException using the given message.
} *
* @param msg The message explaining the reason for the exception.
public AnnotationException(String s) { */
super( s ); public AnnotationException(String msg) {
super( msg );
} }
} }

View File

@ -33,19 +33,28 @@ import org.hibernate.internal.CoreMessageLogger;
* @author Gavin King * @author Gavin King
*/ */
public class AssertionFailure extends RuntimeException { public class AssertionFailure extends RuntimeException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, AssertionFailure.class.getName()); private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, AssertionFailure.class.getName());
public AssertionFailure( String s ) { /**
super(s); * Creates an instance of AssertionFailure using the given message.
LOG.failed(this); *
* @param message The message explaining the reason for the exception
*/
public AssertionFailure(String message) {
super( message );
LOG.failed( this );
} }
public AssertionFailure( String s, /**
Throwable t ) { * Creates an instance of AssertionFailure using the given message and underlying cause.
super(s, t); *
LOG.failed(t); * @param message The message explaining the reason for the exception
* @param cause The underlying cause.
*/
public AssertionFailure(String message, Throwable cause) {
super( message, cause );
LOG.failed( cause );
} }
} }

View File

@ -47,6 +47,8 @@ public interface BasicQueryContract {
* *
* @param flushMode The new FlushMode to use. * @param flushMode The new FlushMode to use.
* *
* @return {@code this}, for method chaining
*
* @see #getFlushMode() * @see #getFlushMode()
*/ */
public BasicQueryContract setFlushMode(FlushMode flushMode); public BasicQueryContract setFlushMode(FlushMode flushMode);
@ -70,6 +72,8 @@ public interface BasicQueryContract {
* *
* @param cacheMode The new CacheMode to use. * @param cacheMode The new CacheMode to use.
* *
* @return {@code this}, for method chaining
*
* @see #getCacheMode() * @see #getCacheMode()
*/ */
public BasicQueryContract setCacheMode(CacheMode cacheMode); public BasicQueryContract setCacheMode(CacheMode cacheMode);
@ -93,6 +97,8 @@ public interface BasicQueryContract {
* *
* @param cacheable Should the query results be cacheable? * @param cacheable Should the query results be cacheable?
* *
* @return {@code this}, for method chaining
*
* @see #isCacheable * @see #isCacheable
*/ */
public BasicQueryContract setCacheable(boolean cacheable); public BasicQueryContract setCacheable(boolean cacheable);
@ -113,6 +119,8 @@ public interface BasicQueryContract {
* @param cacheRegion the name of a query cache region, or {@code null} to indicate that the default region * @param cacheRegion the name of a query cache region, or {@code null} to indicate that the default region
* should be used. * should be used.
* *
* @return {@code this}, for method chaining
*
* @see #getCacheRegion() * @see #getCacheRegion()
*/ */
public BasicQueryContract setCacheRegion(String cacheRegion); public BasicQueryContract setCacheRegion(String cacheRegion);
@ -136,6 +144,8 @@ public interface BasicQueryContract {
* *
* @param timeout the timeout <b>in seconds</b> * @param timeout the timeout <b>in seconds</b>
* *
* @return {@code this}, for method chaining
*
* @see #getTimeout() * @see #getTimeout()
*/ */
public BasicQueryContract setTimeout(int timeout); public BasicQueryContract setTimeout(int timeout);
@ -160,6 +170,8 @@ public interface BasicQueryContract {
* *
* @param fetchSize the fetch size hint * @param fetchSize the fetch size hint
* *
* @return {@code this}, for method chaining
*
* @see #getFetchSize() * @see #getFetchSize()
*/ */
public BasicQueryContract setFetchSize(int fetchSize); public BasicQueryContract setFetchSize(int fetchSize);
@ -201,6 +213,8 @@ public interface BasicQueryContract {
* The read-only/modifiable setting has no impact on entities/proxies * The read-only/modifiable setting has no impact on entities/proxies
* returned by the query that existed in the session before the query was executed. * returned by the query that existed in the session before the query was executed.
* *
* @return {@code this}, for method chaining
*
* @param readOnly true, entities and proxies loaded by the query will be put in read-only mode * @param readOnly true, entities and proxies loaded by the query will be put in read-only mode
* false, entities and proxies loaded by the query will be put in modifiable mode * false, entities and proxies loaded by the query will be put in modifiable mode
*/ */
@ -211,5 +225,5 @@ public interface BasicQueryContract {
* *
* @return an array of types * @return an array of types
*/ */
public Type[] getReturnTypes() throws HibernateException; public Type[] getReturnTypes();
} }

View File

@ -24,27 +24,25 @@
package org.hibernate; package org.hibernate;
/** /**
* Controls how the session interacts with the second-level * Controls how the session interacts with the second-level cache and query cache.
* cache and query cache.
* *
* @author Gavin King * @author Gavin King
* @author Strong Liu * @author Strong Liu
* @see Session#setCacheMode(CacheMode) * @see Session#setCacheMode(CacheMode)
*/ */
public enum CacheMode { public enum CacheMode {
/** /**
* The session may read items from the cache, and add items to the cache * The session may read items from the cache, and add items to the cache.
*/ */
NORMAL( true, true ), NORMAL( true, true ),
/** /**
* The session will never interact with the cache, except to invalidate * The session will never interact with the cache, except to invalidate
* cache items when updates occur * cache items when updates occur.
*/ */
IGNORE( false, false ), IGNORE( false, false ),
/** /**
* The session may read items from the cache, but will not add items, * The session may read items from the cache, but will not add items,
* except to invalidate items when updates occur * except to invalidate items when updates occur.
*/ */
GET( false, true ), GET( false, true ),
/** /**
@ -54,9 +52,9 @@ public enum CacheMode {
PUT( true, false ), PUT( true, false ),
/** /**
* The session will never read items from the cache, but will add items * The session will never read items from the cache, but will add items
* to the cache as it reads them from the database. In this mode, the * to the cache as it reads them from the database. In this mode, the
* effect of <tt>hibernate.cache.use_minimal_puts</tt> is bypassed, in * effect of <tt>hibernate.cache.use_minimal_puts</tt> is bypassed, in
* order to <em>force</em> a cache refresh * order to <em>force</em> a cache refresh.
*/ */
REFRESH( true, false ); REFRESH( true, false );
@ -64,19 +62,38 @@ public enum CacheMode {
private final boolean isPutEnabled; private final boolean isPutEnabled;
private final boolean isGetEnabled; private final boolean isGetEnabled;
CacheMode( boolean isPutEnabled, boolean isGetEnabled) { private CacheMode( boolean isPutEnabled, boolean isGetEnabled) {
this.isPutEnabled = isPutEnabled; this.isPutEnabled = isPutEnabled;
this.isGetEnabled = isGetEnabled; this.isGetEnabled = isGetEnabled;
} }
/**
* Does this cache mode indicate that reads are allowed?
*
* @return {@code true} if cache reads are allowed; {@code false} otherwise.
*/
public boolean isGetEnabled() { public boolean isGetEnabled() {
return isGetEnabled; return isGetEnabled;
} }
/**
* Does this cache mode indicate that writes are allowed?
*
* @return {@code true} if cache writes are allowed; {@code false} otherwise.
*/
public boolean isPutEnabled() { public boolean isPutEnabled() {
return isPutEnabled; return isPutEnabled;
} }
/**
* Used to interpret externalized forms of this enum.
*
* @param setting The externalized form.
*
* @return The matching enum value.
*
* @throws MappingException Indicates the external form was not recognized as a valid enum value.
*/
public static CacheMode interpretExternalSetting(String setting) { public static CacheMode interpretExternalSetting(String setting) {
if (setting == null) { if (setting == null) {
return null; return null;

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,38 +20,44 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
/** /**
* Should be thrown by persistent objects from <tt>Lifecycle</tt> * Intended to be thrown from {@link org.hibernate.classic.Lifecycle} and {@link Interceptor} callbacks.
* or <tt>Interceptor</tt> callbacks. * <p/>
* IMPL NOTE : This is a legacy exception type from back in the day before Hibernate moved to a untyped (runtime)
* exception strategy.
* *
* @see org.hibernate.classic.Lifecycle
* @see Interceptor
* @author Gavin King * @author Gavin King
*/ */
public class CallbackException extends HibernateException { public class CallbackException extends HibernateException {
/**
public CallbackException(Exception root) { * Creates a CallbackException using the given underlying cause.
super("An exception occurred in a callback", root); *
* @param cause The underlying cause
*/
public CallbackException(Exception cause) {
this( "An exception occurred in a callback", cause );
} }
/**
* Creates a CallbackException using the given message.
*
* @param message The message explaining the reason for the exception
*/
public CallbackException(String message) { public CallbackException(String message) {
super(message); super( message );
} }
public CallbackException(String message, Exception e) { /**
super(message, e); * Creates a CallbackException using the given message and underlying cause.
*
* @param message The message explaining the reason for the exception
* @param cause The underlying cause
*/
public CallbackException(String message, Exception cause) {
super( message, cause );
} }
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,7 +20,6 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
@ -31,7 +30,6 @@ package org.hibernate;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public enum ConnectionReleaseMode{ public enum ConnectionReleaseMode{
/** /**
* Indicates that JDBC connection should be aggressively released after each * Indicates that JDBC connection should be aggressively released after each
* SQL statement is executed. In this mode, the application <em>must</em> * SQL statement is executed. In this mode, the application <em>must</em>
@ -55,7 +53,14 @@ public enum ConnectionReleaseMode{
*/ */
ON_CLOSE; ON_CLOSE;
public static ConnectionReleaseMode parse(String name){ /**
* Alias for {@link ConnectionReleaseMode#valueOf(String)} using upper-case version of the incoming name.
*
* @param name The name to parse
*
* @return The matched enum value.
*/
public static ConnectionReleaseMode parse(final String name){
return ConnectionReleaseMode.valueOf( name.toUpperCase() ); return ConnectionReleaseMode.valueOf( name.toUpperCase() );
} }
} }

View File

@ -143,7 +143,7 @@ public interface Criteria extends CriteriaSpecification {
public Criteria setFetchMode(String associationPath, FetchMode mode) throws HibernateException; public Criteria setFetchMode(String associationPath, FetchMode mode) throws HibernateException;
/** /**
* Set the lock mode of the current entity * Set the lock mode of the current entity.
* *
* @param lockMode The lock mode to be applied * @param lockMode The lock mode to be applied
* *
@ -152,7 +152,7 @@ public interface Criteria extends CriteriaSpecification {
public Criteria setLockMode(LockMode lockMode); public Criteria setLockMode(LockMode lockMode);
/** /**
* Set the lock mode of the aliased entity * Set the lock mode of the aliased entity.
* *
* @param alias The previously assigned alias representing the entity to * @param alias The previously assigned alias representing the entity to
* which the given lock mode should apply. * which the given lock mode should apply.
@ -533,7 +533,7 @@ public interface Criteria extends CriteriaSpecification {
public List list() throws HibernateException; public List list() throws HibernateException;
/** /**
* Get the results as an instance of {@link ScrollableResults} * Get the results as an instance of {@link ScrollableResults}.
* *
* @return The {@link ScrollableResults} representing the matched * @return The {@link ScrollableResults} representing the matched
* query results. * query results.

View File

@ -94,7 +94,7 @@ public interface CustomEntityDirtinessStrategy {
public static interface DirtyCheckContext { public static interface DirtyCheckContext {
/** /**
* The callback to indicate that dirty checking (the dirty attribute determination phase) should be handled * The callback to indicate that dirty checking (the dirty attribute determination phase) should be handled
* by the calling {@link CustomEntityDirtinessStrategy} using the given {@link AttributeChecker} * by the calling {@link CustomEntityDirtinessStrategy} using the given {@link AttributeChecker}.
* *
* @param attributeChecker The delegate usable by the context for determining which attributes are dirty. * @param attributeChecker The delegate usable by the context for determining which attributes are dirty.
*/ */
@ -139,7 +139,7 @@ public interface CustomEntityDirtinessStrategy {
public int getAttributeIndex(); public int getAttributeIndex();
/** /**
* Get the name of this attribute * Get the name of this attribute.
* *
* @return The attribute name * @return The attribute name
*/ */

View File

@ -1,7 +1,7 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as * Copyright (c) 2008, 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc. * distributed under license by Red Hat Inc.
@ -24,36 +24,80 @@
package org.hibernate; package org.hibernate;
/** /**
* Raised whenever a duplicate for a certain type occurs. * Raised whenever a duplicate for a certain type occurs. Duplicate class, table, property name etc.
* Duplicate class, table, property name etc.
* *
* @author Max Rydahl Andersen * @author Max Rydahl Andersen
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class DuplicateMappingException extends MappingException { public class DuplicateMappingException extends MappingException {
/**
* Enumeration of the types of things that can be duplicated.
*/
public static enum Type { public static enum Type {
/**
* A duplicate entity definition was encountered.
*/
ENTITY, ENTITY,
/**
* A duplicate table definition was encountered.
*/
TABLE, TABLE,
/**
* A duplicate property/attribute definition was encountered.
*/
PROPERTY, PROPERTY,
/**
* A duplicate column definition was encountered.
*/
COLUMN COLUMN
} }
private final String name; private final String name;
private final String type; private final String type;
/**
* Creates a DuplicateMappingException using the given type and name.
*
* @param type The type of the duplicated thing.
* @param name The name of the duplicated thing.
*/
public DuplicateMappingException(Type type, String name) { public DuplicateMappingException(Type type, String name) {
this( type.name(), name ); this( type.name(), name );
} }
/**
* Creates a DuplicateMappingException using the given type and name.
*
* @param type The type of the duplicated thing.
* @param name The name of the duplicated thing.
*
* @deprecated Use the for taking {@link Type} instead.
*/
@Deprecated @Deprecated
public DuplicateMappingException(String type, String name) { public DuplicateMappingException(String type, String name) {
this( "Duplicate " + type + " mapping " + name, type, name ); this( "Duplicate " + type + " mapping " + name, type, name );
} }
/**
* Creates a DuplicateMappingException using the given customMessage, type and name.
*
* @param customMessage A custom exception message explaining the exception condition
* @param type The type of the duplicated thing.
* @param name The name of the duplicated thing.
*/
public DuplicateMappingException(String customMessage, Type type, String name) { public DuplicateMappingException(String customMessage, Type type, String name) {
this( customMessage, type.name(), name ); this( customMessage, type.name(), name );
} }
/**
* Creates a DuplicateMappingException using the given customMessage, type and name.
*
* @param customMessage A custom exception message explaining the exception condition
* @param type The type of the duplicated thing.
* @param name The name of the duplicated thing.
*
* @deprecated Use the for taking {@link Type} instead.
*/
@Deprecated @Deprecated
public DuplicateMappingException(String customMessage, String type, String name) { public DuplicateMappingException(String customMessage, String type, String name) {
super( customMessage ); super( customMessage );

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,26 +20,29 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
import java.io.Serializable; import java.io.Serializable;
import java.util.Iterator; import java.util.Iterator;
import org.hibernate.type.Type; import org.hibernate.type.Type;
/** /**
* An interceptor that does nothing. May be used as a base class * An interceptor that does nothing. May be used as a base class for application-defined custom interceptors.
* for application-defined custom interceptors.
* *
* @author Gavin King * @author Gavin King
*/ */
public class EmptyInterceptor implements Interceptor, Serializable { public class EmptyInterceptor implements Interceptor, Serializable {
/**
* The singleton reference.
*/
public static final Interceptor INSTANCE = new EmptyInterceptor(); public static final Interceptor INSTANCE = new EmptyInterceptor();
protected EmptyInterceptor() {}
protected EmptyInterceptor() {
}
@Override
public void onDelete( public void onDelete(
Object entity, Object entity,
Serializable id, Serializable id,
@ -47,6 +50,7 @@ public class EmptyInterceptor implements Interceptor, Serializable {
String[] propertyNames, String[] propertyNames,
Type[] types) {} Type[] types) {}
@Override
public boolean onFlushDirty( public boolean onFlushDirty(
Object entity, Object entity,
Serializable id, Serializable id,
@ -57,6 +61,7 @@ public class EmptyInterceptor implements Interceptor, Serializable {
return false; return false;
} }
@Override
public boolean onLoad( public boolean onLoad(
Object entity, Object entity,
Serializable id, Serializable id,
@ -66,6 +71,7 @@ public class EmptyInterceptor implements Interceptor, Serializable {
return false; return false;
} }
@Override
public boolean onSave( public boolean onSave(
Object entity, Object entity,
Serializable id, Serializable id,
@ -75,18 +81,27 @@ public class EmptyInterceptor implements Interceptor, Serializable {
return false; return false;
} }
public void postFlush(Iterator entities) {} @Override
public void preFlush(Iterator entities) {} public void postFlush(Iterator entities) {
}
@Override
public void preFlush(Iterator entities) {
}
@Override
public Boolean isTransient(Object entity) { public Boolean isTransient(Object entity) {
return null; return null;
} }
@Override
public Object instantiate(String entityName, EntityMode entityMode, Serializable id) { public Object instantiate(String entityName, EntityMode entityMode, Serializable id) {
return null; return null;
} }
public int[] findDirty(Object entity, @Override
public int[] findDirty(
Object entity,
Serializable id, Serializable id,
Object[] currentState, Object[] currentState,
Object[] previousState, Object[] previousState,
@ -95,26 +110,43 @@ public class EmptyInterceptor implements Interceptor, Serializable {
return null; return null;
} }
@Override
public String getEntityName(Object object) { public String getEntityName(Object object) {
return null; return null;
} }
@Override
public Object getEntity(String entityName, Serializable id) { public Object getEntity(String entityName, Serializable id) {
return null; return null;
} }
public void afterTransactionBegin(Transaction tx) {} @Override
public void afterTransactionCompletion(Transaction tx) {} public void afterTransactionBegin(Transaction tx) {
public void beforeTransactionCompletion(Transaction tx) {} }
@Override
public void afterTransactionCompletion(Transaction tx) {
}
@Override
public void beforeTransactionCompletion(Transaction tx) {
}
@Override
public String onPrepareStatement(String sql) { public String onPrepareStatement(String sql) {
return sql; return sql;
} }
public void onCollectionRemove(Object collection, Serializable key) throws CallbackException {} @Override
public void onCollectionRemove(Object collection, Serializable key) throws CallbackException {
}
public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException {} @Override
public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException {
}
public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException {} @Override
public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException {
}
} }

View File

@ -29,12 +29,20 @@ package org.hibernate;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public enum EntityMode { public enum EntityMode {
/**
* The {@code pojo} entity mode describes an entity model made up of entity classes (loosely) following
* the java bean convention.
*/
POJO( "pojo" ), POJO( "pojo" ),
/**
* The {@code dynamic-map} entity mode describes an entity model defined using {@link java.util.Map} references.
*/
MAP( "dynamic-map" ); MAP( "dynamic-map" );
private final String name; private final String name;
EntityMode(String name) { private EntityMode(String name) {
this.name = name; this.name = name;
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,7 +20,6 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
@ -32,6 +31,7 @@ package org.hibernate;
* For HQL queries, use the <tt>FETCH</tt> keyword instead. * For HQL queries, use the <tt>FETCH</tt> keyword instead.
* *
* @see Criteria#setFetchMode(java.lang.String, FetchMode) * @see Criteria#setFetchMode(java.lang.String, FetchMode)
*
* @author Gavin King * @author Gavin King
*/ */
public enum FetchMode { public enum FetchMode {
@ -52,18 +52,16 @@ public enum FetchMode {
/** /**
* Fetch lazily. Equivalent to <tt>outer-join="false"</tt>. * Fetch lazily. Equivalent to <tt>outer-join="false"</tt>.
*
* @deprecated use <tt>FetchMode.SELECT</tt> * @deprecated use <tt>FetchMode.SELECT</tt>
*/ */
@Deprecated
public static final FetchMode LAZY = SELECT; public static final FetchMode LAZY = SELECT;
/** /**
* Fetch eagerly, using an outer join. Equivalent to * Fetch eagerly, using an outer join. Equivalent to <tt>outer-join="true"</tt>.
* <tt>outer-join="true"</tt>. *
* @deprecated use <tt>FetchMode.JOIN</tt> * @deprecated use <tt>FetchMode.JOIN</tt>
*/ */
@Deprecated
public static final FetchMode EAGER = JOIN; public static final FetchMode EAGER = JOIN;
} }

View File

@ -35,13 +35,14 @@ package org.hibernate;
* @author Gavin King * @author Gavin King
*/ */
public enum FlushMode { public enum FlushMode {
/** /**
* The {@link Session} is never flushed unless {@link Session#flush} * The {@link Session} is never flushed unless {@link Session#flush}
* is explicitly called by the application. This mode is very * is explicitly called by the application. This mode is very
* efficient for read only transactions. * efficient for read only transactions.
* *
* @deprecated use {@link #MANUAL} instead. * @deprecated use {@link #MANUAL} instead.
*/ */
@Deprecated
NEVER ( 0 ), NEVER ( 0 ),
/** /**
@ -75,25 +76,53 @@ public enum FlushMode {
private FlushMode(int level) { private FlushMode(int level) {
this.level = level; this.level = level;
} }
/**
* Checks to see if {@code this} flush mode is less than the given flush mode.
*
* @param other THe flush mode value to be checked against {@code this}
*
* @return {@code true} indicates {@code other} is less than {@code this}; {@code false} otherwise
*/
public boolean lessThan(FlushMode other) { public boolean lessThan(FlushMode other) {
return this.level<other.level; return this.level < other.level;
} }
/**
* Checks to see if the given mode is the same as {@link #MANUAL}.
*
* @param mode The mode to check
*
* @return true/false
*
* @deprecated Just use equality check against {@link #MANUAL}. Legacy from before this was an enum
*/
@Deprecated
public static boolean isManualFlushMode(FlushMode mode) { public static boolean isManualFlushMode(FlushMode mode) {
return MANUAL.level == mode.level; return MANUAL.level == mode.level;
} }
public static FlushMode interpretExternalSetting(String setting) { /**
if ( setting == null ) { * Interprets an external representation of the flush mode. {@code null} is returned as {@code null}, otherwise
* {@link FlushMode#valueOf(String)} is used with the upper-case version of the incoming value. An unknown,
* non-null value results in a MappingException being thrown.
*
* @param externalName The external representation
*
* @return The interpreted FlushMode value.
*
* @throws MappingException Indicates an unrecognized external representation
*/
public static FlushMode interpretExternalSetting(String externalName) {
if ( externalName == null ) {
return null; return null;
} }
try { try {
return FlushMode.valueOf( setting.toUpperCase() ); return FlushMode.valueOf( externalName.toUpperCase() );
} }
catch ( IllegalArgumentException e ) { catch ( IllegalArgumentException e ) {
throw new MappingException( "unknown FlushMode : " + setting ); throw new MappingException( "unknown FlushMode : " + externalName );
} }
} }
} }

View File

@ -70,8 +70,9 @@ public final class Hibernate {
if ( proxy == null ) { if ( proxy == null ) {
return; return;
} }
else if ( proxy instanceof HibernateProxy ) {
( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().initialize(); if ( proxy instanceof HibernateProxy ) {
( (HibernateProxy) proxy ).getHibernateLazyInitializer().initialize();
} }
else if ( proxy instanceof PersistentCollection ) { else if ( proxy instanceof PersistentCollection ) {
( (PersistentCollection) proxy ).forceInitialization(); ( (PersistentCollection) proxy ).forceInitialization();
@ -84,12 +85,13 @@ public final class Hibernate {
* @param proxy a persistable object, proxy, persistent collection or <tt>null</tt> * @param proxy a persistable object, proxy, persistent collection or <tt>null</tt>
* @return true if the argument is already initialized, or is not a proxy or collection * @return true if the argument is already initialized, or is not a proxy or collection
*/ */
@SuppressWarnings("SimplifiableIfStatement")
public static boolean isInitialized(Object proxy) { public static boolean isInitialized(Object proxy) {
if ( proxy instanceof HibernateProxy ) { if ( proxy instanceof HibernateProxy ) {
return !( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().isUninitialized(); return !( (HibernateProxy) proxy ).getHibernateLazyInitializer().isUninitialized();
} }
else if ( proxy instanceof PersistentCollection ) { else if ( proxy instanceof PersistentCollection ) {
return ( ( PersistentCollection ) proxy ).wasInitialized(); return ( (PersistentCollection) proxy ).wasInitialized();
} }
else { else {
return true; return true;
@ -106,7 +108,7 @@ public final class Hibernate {
*/ */
public static Class getClass(Object proxy) { public static Class getClass(Object proxy) {
if ( proxy instanceof HibernateProxy ) { if ( proxy instanceof HibernateProxy ) {
return ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer() return ( (HibernateProxy) proxy ).getHibernateLazyInitializer()
.getImplementation() .getImplementation()
.getClass(); .getClass();
} }
@ -115,10 +117,24 @@ public final class Hibernate {
} }
} }
/**
* Obtain a lob creator for the given session.
*
* @param session The session for which to obtain a lob creator
*
* @return The log creator reference
*/
public static LobCreator getLobCreator(Session session) { public static LobCreator getLobCreator(Session session) {
return getLobCreator( (SessionImplementor) session ); return getLobCreator( (SessionImplementor) session );
} }
/**
* Obtain a lob creator for the given session.
*
* @param session The session for which to obtain a lob creator
*
* @return The log creator reference
*/
public static LobCreator getLobCreator(SessionImplementor session) { public static LobCreator getLobCreator(SessionImplementor session) {
return session.getFactory() return session.getFactory()
.getJdbcServices() .getJdbcServices()
@ -126,17 +142,19 @@ public final class Hibernate {
} }
/** /**
* Close an <tt>Iterator</tt> created by <tt>iterate()</tt> immediately, * Close an {@link Iterator} instances obtained from {@link org.hibernate.Query#iterate()} immediately
* instead of waiting until the session is closed or disconnected. * instead of waiting until the session is closed or disconnected.
* *
* @param iterator an <tt>Iterator</tt> created by <tt>iterate()</tt> * @param iterator an Iterator created by iterate()
* @throws HibernateException *
* @see org.hibernate.Query#iterate * @throws HibernateException Indicates a problem closing the Hibernate iterator.
* @throws IllegalArgumentException If the Iterator is not a "Hibernate Iterator".
*
* @see Query#iterate() * @see Query#iterate()
*/ */
public static void close(Iterator iterator) throws HibernateException { public static void close(Iterator iterator) throws HibernateException {
if ( iterator instanceof HibernateIterator ) { if ( iterator instanceof HibernateIterator ) {
( ( HibernateIterator ) iterator ).close(); ( (HibernateIterator) iterator ).close();
} }
else { else {
throw new IllegalArgumentException( "not a Hibernate iterator" ); throw new IllegalArgumentException( "not a Hibernate iterator" );
@ -152,10 +170,9 @@ public final class Hibernate {
* @return true if the named property of the object is not listed as uninitialized; false otherwise * @return true if the named property of the object is not listed as uninitialized; false otherwise
*/ */
public static boolean isPropertyInitialized(Object proxy, String propertyName) { public static boolean isPropertyInitialized(Object proxy, String propertyName) {
final Object entity;
Object entity;
if ( proxy instanceof HibernateProxy ) { if ( proxy instanceof HibernateProxy ) {
LazyInitializer li = ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer(); final LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer();
if ( li.isUninitialized() ) { if ( li.isUninitialized() ) {
return false; return false;
} }
@ -168,13 +185,12 @@ public final class Hibernate {
} }
if ( FieldInterceptionHelper.isInstrumented( entity ) ) { if ( FieldInterceptionHelper.isInstrumented( entity ) ) {
FieldInterceptor interceptor = FieldInterceptionHelper.extractFieldInterceptor( entity ); final FieldInterceptor interceptor = FieldInterceptionHelper.extractFieldInterceptor( entity );
return interceptor == null || interceptor.isInitialized( propertyName ); return interceptor == null || interceptor.isInitialized( propertyName );
} }
else { else {
return true; return true;
} }
} }
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as * Copyright (c) 2013, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -21,18 +21,23 @@
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*/ */
package org.hibernate.envers.ant; package org.hibernate;
import org.hibernate.cfg.Configuration;
import org.hibernate.envers.configuration.AuditConfiguration;
import org.hibernate.tool.ant.JPAConfigurationTask;
/** /**
* @author Adam Warski (adam at warski dot org) * Marks a group of exceptions that generally indicate an internal Hibernate error or bug.
*
* @author Steve Ebersole
*/ */
public class JPAConfigurationTaskWithEnvers extends JPAConfigurationTask { public abstract class HibernateError extends HibernateException {
protected void doConfiguration(Configuration configuration) { public HibernateError(String message) {
AuditConfiguration.getFor(configuration); super( message );
}
super.doConfiguration(configuration); public HibernateError(Throwable root) {
} super( root );
}
public HibernateError(String message, Throwable root) {
super( message, root );
}
} }

View File

@ -1,7 +1,7 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* Copyright (c) 2007-2011, Red Hat Inc. or third-party contributors as * Copyright (c) 2007,2011, 2013, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc. * distributed under license by Red Hat Inc.
@ -23,9 +23,8 @@
*/ */
package org.hibernate; package org.hibernate;
/** /**
* The base {@link Throwable} type for Hibernate. * The base exception type for Hibernate exceptions.
* <p/> * <p/>
* Note that all {@link java.sql.SQLException SQLExceptions} will be wrapped in some form of * Note that all {@link java.sql.SQLException SQLExceptions} will be wrapped in some form of
* {@link JDBCException}. * {@link JDBCException}.
@ -35,16 +34,32 @@ package org.hibernate;
* @author Gavin King * @author Gavin King
*/ */
public class HibernateException extends RuntimeException { public class HibernateException extends RuntimeException {
/**
* Constructs a HibernateException using the given exception message.
*
* @param message The message explaining the reason for the exception
*/
public HibernateException(String message) { public HibernateException(String message) {
super( message ); super( message );
} }
public HibernateException(Throwable root) { /**
super( root ); * Constructs a HibernateException using the given message and underlying cause.
*
* @param cause The underlying cause.
*/
public HibernateException(Throwable cause) {
super( cause );
} }
public HibernateException(String message, Throwable root) { /**
super( message, root ); * Constructs a HibernateException using the given message and underlying cause.
*
* @param message The message explaining the reason for the exception.
* @param cause The underlying cause.
*/
public HibernateException(String message, Throwable cause) {
super( message, cause );
} }
} }

View File

@ -26,7 +26,7 @@ package org.hibernate;
import java.io.Serializable; import java.io.Serializable;
/** /**
* Loads an entity by its primary identifier * Loads an entity by its primary identifier.
* *
* @author Eric Dalquist * @author Eric Dalquist
* @author Steve Ebersole * @author Steve Ebersole

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,49 +20,75 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
/** /**
* Thrown if Hibernate can't instantiate an entity or component * Thrown if Hibernate can't instantiate a class at runtime.
* class at runtime.
* *
* @author Gavin King * @author Gavin King
*/ */
public class InstantiationException extends HibernateException { public class InstantiationException extends HibernateException {
private final Class clazz; private final Class clazz;
public InstantiationException(String s, Class clazz, Throwable root) { /**
super(s, root); * Constructs a InstantiationException.
*
* @param message A message explaining the exception condition
* @param clazz The Class we are attempting to instantiate
* @param cause The underlying exception
*/
public InstantiationException(String message, Class clazz, Throwable cause) {
super( message, cause );
this.clazz = clazz; this.clazz = clazz;
} }
public InstantiationException(String s, Class clazz) { /**
super(s); * Constructs a InstantiationException.
this.clazz = clazz; *
} * @param message A message explaining the exception condition
* @param clazz The Class we are attempting to instantiate
public InstantiationException(String s, Class clazz, Exception e) { */
super(s, e); public InstantiationException(String message, Class clazz) {
this( message, clazz, null );
}
/**
* Constructs a InstantiationException.
*
* @param message A message explaining the exception condition
* @param clazz The Class we are attempting to instantiate
* @param cause The underlying exception
*/
public InstantiationException(String message, Class clazz, Exception cause) {
super( message, cause );
this.clazz = clazz; this.clazz = clazz;
} }
/**
* Returns the Class we were attempting to instantiate.
*
* @deprecated Use {@link #getUninstantiatableClass} instead
*
* @return The class we are unable to instantiate
*/
@Deprecated
public Class getPersistentClass() { public Class getPersistentClass() {
return clazz; return clazz;
} }
/**
* Returns the Class we were attempting to instantiate.
*
* @return The class we are unable to instantiate
*/
public Class getUninstantiatableClass() {
return clazz;
}
@Override
public String getMessage() { public String getMessage() {
return super.getMessage() + clazz.getName(); return super.getMessage() + " : " + clazz.getName();
} }
} }

View File

@ -30,18 +30,18 @@ import org.hibernate.type.Type;
/** /**
* Allows user code to inspect and/or change property values. * Allows user code to inspect and/or change property values.
* <br><br> *
* Inspection occurs before property values are written and after they are read * Inspection occurs before property values are written and after they are read
* from the database.<br> * from the database.
* <br> *
* There might be a single instance of <tt>Interceptor</tt> for a <tt>SessionFactory</tt>, or a new instance * There might be a single instance of <tt>Interceptor</tt> for a <tt>SessionFactory</tt>, or a new instance
* might be specified for each <tt>Session</tt>. Whichever approach is used, the interceptor must be * might be specified for each <tt>Session</tt>. Whichever approach is used, the interceptor must be
* serializable if the <tt>Session</tt> is to be serializable. This means that <tt>SessionFactory</tt>-scoped * serializable if the <tt>Session</tt> is to be serializable. This means that <tt>SessionFactory</tt>-scoped
* interceptors should implement <tt>readResolve()</tt>.<br> * interceptors should implement <tt>readResolve()</tt>.
* <br> *
* The <tt>Session</tt> may not be invoked from a callback (nor may a callback cause a collection or proxy to * The <tt>Session</tt> may not be invoked from a callback (nor may a callback cause a collection or proxy to
* be lazily initialized).<br> * be lazily initialized).
* <br> *
* Instead of implementing this interface directly, it is usually better to extend <tt>EmptyInterceptor</tt> * Instead of implementing this interface directly, it is usually better to extend <tt>EmptyInterceptor</tt>
* and override only the callback methods of interest. * and override only the callback methods of interest.
* *
@ -155,9 +155,9 @@ public interface Interceptor {
public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException; public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException;
/** /**
* Called before a flush * Called before a flush.
* *
* @param entities The entities to be flushed * @param entities The entities to be flushed.
* *
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback. * @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
*/ */
@ -215,6 +215,7 @@ public interface Interceptor {
* @param entityName the name of the entity * @param entityName the name of the entity
* @param entityMode The type of entity instance to be returned. * @param entityMode The type of entity instance to be returned.
* @param id the identifier of the new instance * @param id the identifier of the new instance
*
* @return an instance of the class, or <tt>null</tt> to choose default behaviour * @return an instance of the class, or <tt>null</tt> to choose default behaviour
* *
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback. * @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
@ -222,8 +223,10 @@ public interface Interceptor {
public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException; public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException;
/** /**
* Get the entity name for a persistent or transient instance * Get the entity name for a persistent or transient instance.
*
* @param object an entity instance * @param object an entity instance
*
* @return the name of the entity * @return the name of the entity
* *
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback. * @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
@ -231,9 +234,11 @@ public interface Interceptor {
public String getEntityName(Object object) throws CallbackException; public String getEntityName(Object object) throws CallbackException;
/** /**
* Get a fully loaded entity instance that is cached externally * Get a fully loaded entity instance that is cached externally.
*
* @param entityName the name of the entity * @param entityName the name of the entity
* @param id the instance identifier * @param id the instance identifier
*
* @return a fully initialized entity * @return a fully initialized entity
* *
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback. * @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.

View File

@ -23,12 +23,13 @@
*/ */
package org.hibernate; package org.hibernate;
import org.hibernate.internal.util.xml.XmlDocument;
import org.hibernate.jaxb.spi.Origin; import org.hibernate.jaxb.spi.Origin;
/** /**
* Thrown when a mapping is found to be invalid. * Thrown when a mapping is found to be invalid.
* Similar to MappingException, but this contains more info about the path and type of mapping (e.g. file, resource or url) *
* Similar to MappingException, but this contains more info about the path and type of
* mapping (e.g. file, resource or url)
* *
* @author Max Rydahl Andersen * @author Max Rydahl Andersen
* @author Steve Ebersole * @author Steve Ebersole
@ -37,45 +38,105 @@ public class InvalidMappingException extends MappingException {
private final String path; private final String path;
private final String type; private final String type;
/**
* Constructs an InvalidMappingException using the given information.
*
* @param customMessage The custom message explaining the exception condition
* @param type The type of invalid mapping document
* @param path The path (type specific) of the invalid mapping document
* @param cause The underlying cause
*/
public InvalidMappingException(String customMessage, String type, String path, Throwable cause) { public InvalidMappingException(String customMessage, String type, String path, Throwable cause) {
super(customMessage, cause); super( customMessage, cause );
this.type=type; this.type = type;
this.path=path; this.path = path;
} }
/**
* Constructs an InvalidMappingException using the given information.
*
* @param customMessage The custom message explaining the exception condition
* @param type The type of invalid mapping document
* @param path The path (type specific) of the invalid mapping document
*/
public InvalidMappingException(String customMessage, String type, String path) { public InvalidMappingException(String customMessage, String type, String path) {
super(customMessage); super(customMessage);
this.type=type; this.type=type;
this.path=path; this.path=path;
} }
// /**
// * Constructs an InvalidMappingException using the given information.
// *
// * @param customMessage The custom message explaining the exception condition
// * @param xmlDocument The document that was invalid
// * @param cause The underlying cause
// */
// public InvalidMappingException(String customMessage, XmlDocument xmlDocument, Throwable cause) { // public InvalidMappingException(String customMessage, XmlDocument xmlDocument, Throwable cause) {
// this( customMessage, xmlDocument.getOrigin().getType(), xmlDocument.getOrigin().getName(), cause ); // this( customMessage, xmlDocument.getOrigin().getType(), xmlDocument.getOrigin().getName(), cause );
// } // }
// //
// /**
// * Constructs an InvalidMappingException using the given information.
// *
// * @param customMessage The custom message explaining the exception condition
// * @param xmlDocument The document that was invalid
// */
// public InvalidMappingException(String customMessage, XmlDocument xmlDocument) { // public InvalidMappingException(String customMessage, XmlDocument xmlDocument) {
// this( customMessage, xmlDocument.getOrigin().getType(), xmlDocument.getOrigin().getName() ); // this( customMessage, xmlDocument.getOrigin().getType(), xmlDocument.getOrigin().getName() );
// }
//
// public InvalidMappingException(String customMessage, Origin origin) {
// this( customMessage, origin.getType().toString(), origin.getName() );
// }
//
// public InvalidMappingException(String type, String path) {
// this("Could not parse mapping document from " + type + (path==null?"":" " + path), type, path);
// } // }
/**
* Constructs an InvalidMappingException using the given information.
*
* @param customMessage The custom message explaining the exception condition
* @param origin The origin of the invalid mapping document
*/
public InvalidMappingException(String customMessage, Origin origin) {
this( customMessage, origin.getType().toString(), origin.getName() );
}
/**
* Constructs an InvalidMappingException using the given information and a standard message.
*
* @param type The type of invalid mapping document
* @param path The path (type specific) of the invalid mapping document
*/
public InvalidMappingException(String type, String path) {
this("Could not parse mapping document from " + type + (path==null?"":" " + path), type, path);
}
/**
* Constructs an InvalidMappingException using the given information and a standard message.
*
* @param type The type of invalid mapping document
* @param path The path (type specific) of the invalid mapping document
* @param cause The underlying cause
*/
public InvalidMappingException(String type, String path, Throwable cause) { public InvalidMappingException(String type, String path, Throwable cause) {
this("Could not parse mapping document from " + type + (path==null?"":" " + path), type, path, cause); this("Could not parse mapping document from " + type + (path==null?"":" " + path), type, path, cause);
} }
public InvalidMappingException(String message, Origin origin, Exception cause) { /**
this( message, origin.getType().name(), origin.getName(), cause ); * Constructs an InvalidMappingException using the given information.
*
* @param customMessage The custom message explaining the exception condition
* @param origin The origin of the invalid mapping document
* @param cause The underlying cause
*/
public InvalidMappingException(String customMessage, Origin origin, Exception cause) {
this( customMessage, origin.getType().name(), origin.getName(), cause );
} }
public InvalidMappingException(String message, Origin origin) { // /**
this( message, origin, null ); // * Constructs an InvalidMappingException using the given information.
} // *
// * @param customMessage The custom message explaining the exception condition
// * @param origin The origin of the invalid mapping document
// */
// public InvalidMappingException(String customMessage, Origin origin) {
// this( customMessage, origin, null );
// }
public String getType() { public String getType() {
return type; return type;

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,63 +20,80 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
import java.sql.SQLException; import java.sql.SQLException;
/** /**
* Wraps an <tt>SQLException</tt>. Indicates that an exception * Wraps a {@link SQLException}. Indicates that an exception occurred during a JDBC call.
* occurred during a JDBC call. *
* @author Gavin King
* *
* @see java.sql.SQLException * @see java.sql.SQLException
* @author Gavin King
*/ */
public class JDBCException extends HibernateException { public class JDBCException extends HibernateException {
private final SQLException sqlException;
private final String sql;
private SQLException sqle; /**
private String sql; * Constructs a JDBCException using the given information.
*
public JDBCException(String string, SQLException root) { * @param message The message explaining the exception condition
super(string, root); * @param cause The underlying cause
sqle=root; */
public JDBCException(String message, SQLException cause) {
this( message, cause, null );
} }
public JDBCException(String string, SQLException root, String sql) { /**
this(string, root); * Constructs a JDBCException using the given information.
*
* @param message The message explaining the exception condition
* @param cause The underlying cause
* @param sql The sql being executed when the exception occurred
*/
public JDBCException(String message, SQLException cause, String sql) {
super( message, cause );
this.sqlException = cause;
this.sql = sql; this.sql = sql;
} }
/** /**
* Get the SQLState of the underlying <tt>SQLException</tt>. * Get the X/Open or ANSI SQL SQLState error code from the underlying {@link SQLException}.
* @see java.sql.SQLException *
* @return String * @return The X/Open or ANSI SQL SQLState error code; may return null.
*
* @see java.sql.SQLException#getSQLState()
*/ */
public String getSQLState() { public String getSQLState() {
return sqle.getSQLState(); return sqlException.getSQLState();
} }
/** /**
* Get the <tt>errorCode</tt> of the underlying <tt>SQLException</tt>. * Get the vendor specific error code from the underlying {@link SQLException}.
* @see java.sql.SQLException *
* @return int the error code * @return The vendor specific error code
*
* @see java.sql.SQLException#getErrorCode()
*/ */
public int getErrorCode() { public int getErrorCode() {
return sqle.getErrorCode(); return sqlException.getErrorCode();
} }
/** /**
* Get the underlying <tt>SQLException</tt>. * Get the underlying {@link SQLException}.
* @return SQLException *
* @return The SQLException
*/ */
public SQLException getSQLException() { public SQLException getSQLException() {
return sqle; return sqlException;
} }
/** /**
* Get the actual SQL statement that caused the exception * Get the actual SQL statement being executed when the exception occurred.
* (may be null) *
* @return The SQL statement; may return null.
*/ */
public String getSQL() { public String getSQL() {
return sql; return sql;

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,17 +20,17 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
/** /**
* Indicates access to unfetched data outside of a session context. * Indicates an attempt to access not-yet-fetched data outside of a session context.
* For example, when an uninitialized proxy or collection is accessed *
* after the session was closed. * For example, when an uninitialized proxy or collection is accessed after the session was closed.
* *
* @see Hibernate#initialize(java.lang.Object) * @see Hibernate#initialize(java.lang.Object)
* @see Hibernate#isInitialized(java.lang.Object) * @see Hibernate#isInitialized(java.lang.Object)
@ -38,11 +38,19 @@ import org.hibernate.internal.CoreMessageLogger;
*/ */
public class LazyInitializationException extends HibernateException { public class LazyInitializationException extends HibernateException {
private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, LazyInitializationException.class.getName() ); private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class,
LazyInitializationException.class.getName()
);
public LazyInitializationException(String msg) { /**
super( msg ); * Constructs a LazyInitializationException using the given message.
LOG.trace( msg, this ); *
* @param message A message explaining the exception condition
*/
public LazyInitializationException(String message) {
super( message );
LOG.trace( message, this );
} }
} }

View File

@ -30,7 +30,7 @@ import java.sql.Clob;
import java.sql.NClob; import java.sql.NClob;
/** /**
* A {@link Session session's} helper for creating LOB data * A {@link Session session's} helper for creating LOB data.
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
@ -56,7 +56,7 @@ public interface LobHelper {
public Blob createBlob(InputStream stream, long length); public Blob createBlob(InputStream stream, long length);
/** /**
* Create a new {@link java.sql.Clob} from content * Create a new {@link java.sql.Clob} from content.
* *
* @param string The string data * @param string The string data
* *

View File

@ -36,18 +36,17 @@ import java.util.Map;
*/ */
public class LockOptions implements Serializable { public class LockOptions implements Serializable {
/** /**
* NONE represents LockMode.NONE (timeout + scope do not apply) * Represents LockMode.NONE (timeout + scope do not apply).
*/ */
public static final LockOptions NONE = new LockOptions(LockMode.NONE); public static final LockOptions NONE = new LockOptions(LockMode.NONE);
/** /**
* READ represents LockMode.READ (timeout + scope do not apply) * Represents LockMode.READ (timeout + scope do not apply).
*/ */
public static final LockOptions READ = new LockOptions(LockMode.READ); public static final LockOptions READ = new LockOptions(LockMode.READ);
/** /**
* UPGRADE represents LockMode.UPGRADE (will wait forever for lock and * Represents LockMode.UPGRADE (will wait forever for lock and scope of false meaning only entity is locked).
* scope of false meaning only entity is locked)
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static final LockOptions UPGRADE = new LockOptions(LockMode.UPGRADE); public static final LockOptions UPGRADE = new LockOptions(LockMode.UPGRADE);
@ -73,12 +72,19 @@ public class LockOptions implements Serializable {
private LockMode lockMode = LockMode.NONE; private LockMode lockMode = LockMode.NONE;
private int timeout = WAIT_FOREVER; private int timeout = WAIT_FOREVER;
//initialize lazily as LockOptions is frequently created without needing this private Map<String,LockMode> aliasSpecificLockModes;
private Map<String,LockMode> aliasSpecificLockModes = null;
/**
* Constructs a LockOptions with all default options.
*/
public LockOptions() { public LockOptions() {
} }
/**
* Constructs a LockOptions with the given lock mode.
*
* @param lockMode The lock mode to use
*/
public LockOptions( LockMode lockMode) { public LockOptions( LockMode lockMode) {
this.lockMode = lockMode; this.lockMode = lockMode;
} }
@ -109,7 +115,6 @@ public class LockOptions implements Serializable {
return this; return this;
} }
/** /**
* Specify the {@link LockMode} to be used for a specific query alias. * Specify the {@link LockMode} to be used for a specific query alias.
* *
@ -168,6 +173,11 @@ public class LockOptions implements Serializable {
return lockMode == null ? LockMode.NONE : lockMode; return lockMode == null ? LockMode.NONE : lockMode;
} }
/**
* Does this LockOptions object define alias-specific lock modes?
*
* @return {@code true} if this LockOptions object define alias-specific lock modes; {@code false} otherwise.
*/
public boolean hasAliasSpecificLockModes() { public boolean hasAliasSpecificLockModes() {
return aliasSpecificLockModes != null return aliasSpecificLockModes != null
&& ! aliasSpecificLockModes.isEmpty(); && ! aliasSpecificLockModes.isEmpty();
@ -186,7 +196,7 @@ public class LockOptions implements Serializable {
} }
/** /**
* Iterator for accessing Alias (key) and LockMode (value) as Map.Entry * Iterator for accessing Alias (key) and LockMode (value) as Map.Entry.
* *
* @return Iterator for accessing the Map.Entry's * @return Iterator for accessing the Map.Entry's
*/ */
@ -198,7 +208,7 @@ public class LockOptions implements Serializable {
} }
/** /**
* Currently needed for follow-on locking * Currently needed for follow-on locking.
* *
* @return The greatest of all requested lock modes. * @return The greatest of all requested lock modes.
*/ */
@ -251,7 +261,7 @@ public class LockOptions implements Serializable {
return this; return this;
} }
private boolean scope=false; private boolean scope;
/** /**
* Retrieve the current lock scope setting. * Retrieve the current lock scope setting.
@ -265,7 +275,7 @@ public class LockOptions implements Serializable {
} }
/** /**
* Set the cope. * Set the scope.
* *
* @param scope The new scope setting * @param scope The new scope setting
* *
@ -276,6 +286,11 @@ public class LockOptions implements Serializable {
return this; return this;
} }
/**
* Make a copy.
*
* @return The copy
*/
public LockOptions makeCopy() { public LockOptions makeCopy() {
final LockOptions copy = new LockOptions(); final LockOptions copy = new LockOptions();
copy( this, copy ); copy( this, copy );
@ -283,7 +298,7 @@ public class LockOptions implements Serializable {
} }
/** /**
* Perform a shallow copy * Perform a shallow copy.
* *
* @param source Source for the copy (copied from) * @param source Source for the copy (copied from)
* @param destination Destination for the copy (copied to) * @param destination Destination for the copy (copied to)

View File

@ -1,7 +1,7 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as * Copyright (c) 2008, 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc. * distributed under license by Red Hat Inc.
@ -24,23 +24,38 @@
package org.hibernate; package org.hibernate;
/** /**
* An exception that usually occurs at configuration time, rather * An exception that occurs while reading mapping sources (xml/annotations),usually as a result of something
* than runtime, as a result of something screwy in the O-R mappings. * screwy in the O-R mappings.
* *
* @author Gavin King * @author Gavin King
*/ */
public class MappingException extends HibernateException { public class MappingException extends HibernateException {
/**
public MappingException(String msg, Throwable root) { * Constructs a MappingException using the given information.
super( msg, root ); *
* @param message A message explaining the exception condition
* @param cause The underlying cause
*/
public MappingException(String message, Throwable cause) {
super( message, cause );
} }
public MappingException(Throwable root) { /**
super(root); * Constructs a MappingException using the given information.
*
* @param cause The underlying cause
*/
public MappingException(Throwable cause) {
super(cause);
} }
public MappingException(String s) { /**
super(s); * Constructs a MappingException using the given information.
*
* @param message A message explaining the exception condition
*/
public MappingException(String message) {
super(message);
} }
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,10 +20,8 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
/** /**
* Thrown when a resource for a mapping could not be found. * Thrown when a resource for a mapping could not be found.
@ -31,26 +29,53 @@ package org.hibernate;
* @author Max Rydahl Andersen * @author Max Rydahl Andersen
*/ */
public class MappingNotFoundException extends MappingException { public class MappingNotFoundException extends MappingException {
private final String path; private final String path;
private final String type; private final String type;
/**
* Constructs a MappingNotFoundException using the given information.
*
* @param customMessage A message explaining the exception condition
* @param type The type of mapping that could not be found
* @param path The path (type specific) of the mapping that could not be found
* @param cause The underlying cause
*/
public MappingNotFoundException(String customMessage, String type, String path, Throwable cause) { public MappingNotFoundException(String customMessage, String type, String path, Throwable cause) {
super(customMessage, cause); super(customMessage, cause);
this.type=type; this.type=type;
this.path=path; this.path=path;
} }
/**
* Constructs a MappingNotFoundException using the given information.
*
* @param customMessage A message explaining the exception condition
* @param type The type of mapping that could not be found
* @param path The path (type specific) of the mapping that could not be found
*/
public MappingNotFoundException(String customMessage, String type, String path) { public MappingNotFoundException(String customMessage, String type, String path) {
super(customMessage); super(customMessage);
this.type=type; this.type=type;
this.path=path; this.path=path;
} }
/**
* Constructs a MappingNotFoundException using the given information, using a standard message.
*
* @param type The type of mapping that could not be found
* @param path The path (type specific) of the mapping that could not be found
*/
public MappingNotFoundException(String type, String path) { public MappingNotFoundException(String type, String path) {
this(type + ": " + path + " not found", type, path); this(type + ": " + path + " not found", type, path);
} }
/**
* Constructs a MappingNotFoundException using the given information, using a standard message.
*
* @param type The type of mapping that could not be found
* @param path The path (type specific) of the mapping that could not be found
* @param cause The underlying cause
*/
public MappingNotFoundException(String type, String path, Throwable cause) { public MappingNotFoundException(String type, String path, Throwable cause) {
this(type + ": " + path + " not found", type, path, cause); this(type + ": " + path + " not found", type, path, cause);
} }

View File

@ -49,7 +49,7 @@ public enum MultiTenancyStrategy {
*/ */
DATABASE, DATABASE,
/** /**
* No multi-tenancy * No multi-tenancy.
*/ */
NONE; NONE;
@ -58,10 +58,24 @@ public enum MultiTenancyStrategy {
MultiTenancyStrategy.class.getName() MultiTenancyStrategy.class.getName()
); );
/**
* Does this strategy indicate a requirement for the specialized
* {@link org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider}, rather than the
* traditional {@link org.hibernate.engine.jdbc.connections.spi.ConnectionProvider}?
*
* @return {@code true} indicates a MultiTenantConnectionProvider is required; {@code false} indicates it is not.
*/
public boolean requiresMultiTenantConnectionProvider() { public boolean requiresMultiTenantConnectionProvider() {
return this == DATABASE || this == SCHEMA; return this == DATABASE || this == SCHEMA;
} }
/**
* Extract the MultiTenancyStrategy from the setting map.
*
* @param properties The map of settings.
*
* @return The selected strategy. {@link #NONE} is always the default.
*/
public static MultiTenancyStrategy determineMultiTenancyStrategy(Map properties) { public static MultiTenancyStrategy determineMultiTenancyStrategy(Map properties) {
final Object strategy = properties.get( Environment.MULTI_TENANT ); final Object strategy = properties.get( Environment.MULTI_TENANT );
if ( strategy == null ) { if ( strategy == null ) {

View File

@ -24,7 +24,7 @@
package org.hibernate; package org.hibernate;
/** /**
* Loads an entity by its natural identifier * Loads an entity by its natural identifier.
* *
* @author Eric Dalquist * @author Eric Dalquist
* @author Steve Ebersole * @author Steve Ebersole

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,19 +20,17 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
import java.io.Serializable; import java.io.Serializable;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
/** /**
* This exception is thrown when an operation would * This exception is thrown when an operation would break session-scoped identity. This occurs if the
* break session-scoped identity. This occurs if the * user tries to associate two different instances of the same Java class with a particular identifier,
* user tries to associate two different instances of * in the scope of a single Session.
* the same Java class with a particular identifier,
* in the scope of a single <tt>Session</tt>.
* *
* @author Gavin King * @author Gavin King
*/ */
@ -40,27 +38,43 @@ public class NonUniqueObjectException extends HibernateException {
private final Serializable identifier; private final Serializable identifier;
private final String entityName; private final String entityName;
public NonUniqueObjectException(String message, Serializable id, String clazz) { /**
super(message); * Constructs a NonUniqueObjectException using the given information.
this.entityName = clazz; *
this.identifier = id; * @param message A message explaining the exception condition
* @param entityId The identifier of the entity
* @param entityName The name of the entity
*/
public NonUniqueObjectException(String message, Serializable entityId, String entityName) {
super( message );
this.entityName = entityName;
this.identifier = entityId;
} }
public NonUniqueObjectException(Serializable id, String clazz) { /**
this("a different object with the same identifier value was already associated with the session", id, clazz); * Constructs a NonUniqueObjectException using the given information, using a standard message.
} *
* @param entityId The identifier of the entity
public Serializable getIdentifier() { * @param entityName The name of the entity
return identifier; */
} public NonUniqueObjectException(Serializable entityId, String entityName) {
this(
public String getMessage() { "A different object with the same identifier value was already associated with the session",
return super.getMessage() + ": " + entityId,
MessageHelper.infoString(entityName, identifier); entityName
);
} }
public String getEntityName() { public String getEntityName() {
return entityName; return entityName;
} }
public Serializable getIdentifier() {
return identifier;
}
@Override
public String getMessage() {
return super.getMessage() + " : " + MessageHelper.infoString( entityName, identifier );
}
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,20 +20,22 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
/** /**
* Thrown when the application calls <tt>Query.uniqueResult()</tt> and * Thrown when the application calls <tt>Query.uniqueResult()</tt> and
* the query returned more than one result. Unlike all other Hibernate * the query returned more than one result. Unlike all other Hibernate
* exceptions, this one is recoverable! * exceptions, this one is recoverable!
* *
* @author Gavin King * @author Gavin King
*/ */
public class NonUniqueResultException extends HibernateException { public class NonUniqueResultException extends HibernateException {
/**
* Constructs a NonUniqueResultException.
*
* @param resultCount The number of actual results.
*/
public NonUniqueResultException(int resultCount) { public NonUniqueResultException(int resultCount) {
super( "query did not return a unique result: " + resultCount ); super( "query did not return a unique result: " + resultCount );
} }

View File

@ -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; package org.hibernate;
/** /**
@ -21,21 +44,37 @@ public enum NullPrecedence {
*/ */
LAST; LAST;
public static NullPrecedence parse(String type) { /**
if ( "none".equalsIgnoreCase( type ) ) { * Interprets a string representation of a NullPrecedence, returning {@code null} by default. For
* alternative default handling, see {@link #parse(String, NullPrecedence)}
*
* @param name The String representation to interpret
*
* @return The recognized NullPrecedence, or {@code null}
*/
public static NullPrecedence parse(String name) {
if ( "none".equalsIgnoreCase( name ) ) {
return NullPrecedence.NONE; return NullPrecedence.NONE;
} }
else if ( "first".equalsIgnoreCase( type ) ) { else if ( "first".equalsIgnoreCase( name ) ) {
return NullPrecedence.FIRST; return NullPrecedence.FIRST;
} }
else if ( "last".equalsIgnoreCase( type ) ) { else if ( "last".equalsIgnoreCase( name ) ) {
return NullPrecedence.LAST; return NullPrecedence.LAST;
} }
return null; return null;
} }
public static NullPrecedence parse(String type, NullPrecedence defaultValue) { /**
final NullPrecedence value = parse( type ); * Interprets a string representation of a NullPrecedence, returning the specified default if not recognized.
*
* @param name The String representation to interpret
* @param defaultValue The default value to use
*
* @return The recognized NullPrecedence, or {@code defaultValue}.
*/
public static NullPrecedence parse(String name, NullPrecedence defaultValue) {
final NullPrecedence value = parse( name );
return value != null ? value : defaultValue; return value != null ? value : defaultValue;
} }
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,21 +20,26 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
import java.io.Serializable; import java.io.Serializable;
/** /**
* Thrown when the user tries to do something illegal with a deleted * Thrown when the user tries to do something illegal with a deleted object.
* object.
* *
* @author Gavin King * @author Gavin King
*/ */
public class ObjectDeletedException extends UnresolvableObjectException { public class ObjectDeletedException extends UnresolvableObjectException {
/**
public ObjectDeletedException(String message, Serializable identifier, String clazz) { * Constructs an ObjectDeletedException using the given information.
super(message, identifier, clazz); *
* @param message A message explaining the exception condition
* @param identifier The identifier of the entity
* @param entityName The name of the entity
*/
public ObjectDeletedException(String message, Serializable identifier, String entityName) {
super( message, identifier, entityName );
} }
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,9 +20,9 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
import java.io.Serializable; import java.io.Serializable;
/** /**
@ -39,8 +39,13 @@ import java.io.Serializable;
* @author Gavin King * @author Gavin King
*/ */
public class ObjectNotFoundException extends UnresolvableObjectException { public class ObjectNotFoundException extends UnresolvableObjectException {
/**
public ObjectNotFoundException(Serializable identifier, String clazz) { * Constructs a ObjectNotFoundException using the given information.
super(identifier, clazz); *
* @param identifier The identifier of the entity
* @param entityName The name of the entity
*/
public ObjectNotFoundException(Serializable identifier, String entityName) {
super(identifier, entityName);
} }
} }

View File

@ -1,7 +1,7 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* Copyright (c) 2009-2011, Red Hat Inc. or third-party contributors as * Copyright (c) 2009, 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc. * distributed under license by Red Hat Inc.
@ -32,8 +32,15 @@ import org.hibernate.dialect.lock.OptimisticEntityLockException;
* *
* @deprecated Use {@link org.hibernate.dialect.lock.OptimisticEntityLockException} instead * @deprecated Use {@link org.hibernate.dialect.lock.OptimisticEntityLockException} instead
*/ */
@Deprecated
public class OptimisticLockException extends OptimisticEntityLockException { public class OptimisticLockException extends OptimisticEntityLockException {
/**
* Constructs a OptimisticLockException using the specified information.
*
* @param entity The entity instance that could not be locked
* @param message A message explaining the exception condition
*/
public OptimisticLockException(Object entity, String message) { public OptimisticLockException(Object entity, String message) {
super( entity, message ); super( entity, message );
} }
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,11 +20,9 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
/** /**
* Thrown when the user passes a persistent instance to a <tt>Session</tt> * Thrown when the user passes a persistent instance to a <tt>Session</tt>
* method that expects a transient instance. * method that expects a transient instance.
@ -32,8 +30,12 @@ package org.hibernate;
* @author Gavin King * @author Gavin King
*/ */
public class PersistentObjectException extends HibernateException { public class PersistentObjectException extends HibernateException {
/**
public PersistentObjectException(String s) { * Constructs a PersistentObjectException using the given message.
super(s); *
* @param message A message explaining the exception condition
*/
public PersistentObjectException(String message) {
super( message );
} }
} }

View File

@ -31,7 +31,14 @@ import java.sql.SQLException;
* @author Scott Marlow * @author Scott Marlow
*/ */
public class PessimisticLockException extends JDBCException { public class PessimisticLockException extends JDBCException {
public PessimisticLockException(String s, SQLException se, String sql) { /**
super( s, se, sql ); * Constructs a PessimisticLockException using the specified information.
*
* @param message A message explaining the exception condition
* @param sqlException The underlying SQL exception
* @param sql The sql that led to the exception (may be null, though usually should not be)
*/
public PessimisticLockException(String message, SQLException sqlException, String sql) {
super( message, sqlException, sql );
} }
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,7 +20,6 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
@ -39,13 +38,26 @@ import org.hibernate.internal.util.StringHelper;
* @author Gavin King * @author Gavin King
*/ */
public class PropertyAccessException extends HibernateException { public class PropertyAccessException extends HibernateException {
private final Class persistentClass; private final Class persistentClass;
private final String propertyName; private final String propertyName;
private final boolean wasSetter; private final boolean wasSetter;
public PropertyAccessException(Throwable root, String s, boolean wasSetter, Class persistentClass, String propertyName) { /**
super(s, root); * Constructs a PropertyAccessException using the specified information.
*
* @param cause The underlying cause
* @param message A message explaining the exception condition
* @param wasSetter Was the attempting to access the setter the cause of the exception?
* @param persistentClass The class which is supposed to contain the property in question
* @param propertyName The name of the property.
*/
public PropertyAccessException(
Throwable cause,
String message,
boolean wasSetter,
Class persistentClass,
String propertyName) {
super(message, cause);
this.persistentClass = persistentClass; this.persistentClass = persistentClass;
this.wasSetter = wasSetter; this.wasSetter = wasSetter;
this.propertyName = propertyName; this.propertyName = propertyName;

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,11 +20,9 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
/** /**
* Indicates that an expected getter or setter method could not be * Indicates that an expected getter or setter method could not be
* found on a class. * found on a class.
@ -32,9 +30,12 @@ package org.hibernate;
* @author Gavin King * @author Gavin King
*/ */
public class PropertyNotFoundException extends MappingException { public class PropertyNotFoundException extends MappingException {
/**
public PropertyNotFoundException(String s) { * Constructs a PropertyNotFoundException given the specified message.
super(s); *
* @param message A message explaining the exception condition
*/
public PropertyNotFoundException(String message) {
super(message);
} }
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,7 +20,6 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
@ -36,12 +35,18 @@ import org.hibernate.internal.util.StringHelper;
* @author Gavin King * @author Gavin King
*/ */
public class PropertyValueException extends HibernateException { public class PropertyValueException extends HibernateException {
private final String entityName; private final String entityName;
private final String propertyName; private final String propertyName;
public PropertyValueException(String s, String entityName, String propertyName) { /**
super(s); * Constructs a PropertyValueException using the specified information.
*
* @param message A message explaining the exception condition
* @param entityName The name of the entity, containing the property
* @param propertyName The name of the property being accessed.
*/
public PropertyValueException(String message, String entityName, String propertyName) {
super(message);
this.entityName = entityName; this.entityName = entityName;
this.propertyName = propertyName; this.propertyName = propertyName;
} }
@ -56,25 +61,6 @@ public class PropertyValueException extends HibernateException {
@Override @Override
public String getMessage() { public String getMessage() {
return super.getMessage() + ": " + return super.getMessage() + " : " + StringHelper.qualify( entityName, propertyName );
StringHelper.qualify(entityName, propertyName);
}
/**
* Return a well formed property path.
* Basicaly, it will return parent.child
*
* @param parent parent in path
* @param child child in path
* @return parent-child path
*/
public static String buildPropertyPath(String parent, String child) {
return new StringBuilder(parent).append('.').append(child).toString();
} }
} }

View File

@ -77,6 +77,7 @@ import org.hibernate.type.Type;
* *
* @author Gavin King * @author Gavin King
*/ */
@SuppressWarnings("UnusedDeclaration")
public interface Query extends BasicQueryContract { public interface Query extends BasicQueryContract {
/** /**
* Get the query string. * Get the query string.
@ -99,6 +100,8 @@ public interface Query extends BasicQueryContract {
* *
* @param maxResults the maximum number of rows * @param maxResults the maximum number of rows
* *
* @return {@code this}, for method chaining
*
* @see #getMaxResults() * @see #getMaxResults()
*/ */
public Query setMaxResults(int maxResults); public Query setMaxResults(int maxResults);
@ -117,6 +120,8 @@ public interface Query extends BasicQueryContract {
* *
* @param firstResult a row number, numbered from <tt>0</tt> * @param firstResult a row number, numbered from <tt>0</tt>
* *
* @return {@code this}, for method chaining
*
* @see #getFirstResult() * @see #getFirstResult()
*/ */
public Query setFirstResult(int firstResult); public Query setFirstResult(int firstResult);
@ -159,6 +164,10 @@ public interface Query extends BasicQueryContract {
* </ol> * </ol>
* For alias-specific locking, use {@link #setLockMode(String, LockMode)}. * For alias-specific locking, use {@link #setLockMode(String, LockMode)}.
* *
* @param lockOptions The lock options to apply to the query.
*
* @return {@code this}, for method chaining
*
* @see #getLockOptions() * @see #getLockOptions()
*/ */
public Query setLockOptions(LockOptions lockOptions); public Query setLockOptions(LockOptions lockOptions);
@ -173,7 +182,10 @@ public interface Query extends BasicQueryContract {
* speaking, for maximum portability, this method should only be used to mark that the rows corresponding to * speaking, for maximum portability, this method should only be used to mark that the rows corresponding to
* the given alias should be included in pessimistic locking ({@link LockMode#PESSIMISTIC_WRITE}). * the given alias should be included in pessimistic locking ({@link LockMode#PESSIMISTIC_WRITE}).
* *
* @param alias a query alias, or <tt>this</tt> for a collection filter * @param alias a query alias, or {@code "this"} for a collection filter
* @param lockMode The lock mode to apply.
*
* @return {@code this}, for method chaining
* *
* @see #getLockOptions() * @see #getLockOptions()
*/ */
@ -194,21 +206,25 @@ public interface Query extends BasicQueryContract {
* *
* @param comment The human-readable comment * @param comment The human-readable comment
* *
* @return {@code this}, for method chaining
*
* @see #getComment() * @see #getComment()
*/ */
public Query setComment(String comment); public Query setComment(String comment);
/** /**
* Return the HQL select clause aliases (if any) * Return the HQL select clause aliases, if any.
*
* @return an array of aliases as strings * @return an array of aliases as strings
*/ */
public String[] getReturnAliases() throws HibernateException; public String[] getReturnAliases();
/** /**
* Return the names of all named parameters of the query. * Return the names of all named parameters of the query.
*
* @return the parameter names, in no particular order * @return the parameter names, in no particular order
*/ */
public String[] getNamedParameters() throws HibernateException; public String[] getNamedParameters();
/** /**
* Return the query results as an <tt>Iterator</tt>. If the query * Return the query results as an <tt>Iterator</tt>. If the query
@ -219,9 +235,8 @@ public interface Query extends BasicQueryContract {
* SQL query returns identifiers only.<br> * SQL query returns identifiers only.<br>
* *
* @return the result iterator * @return the result iterator
* @throws HibernateException
*/ */
public Iterator iterate() throws HibernateException; public Iterator iterate();
/** /**
* Return the query results as <tt>ScrollableResults</tt>. The * Return the query results as <tt>ScrollableResults</tt>. The
@ -229,22 +244,24 @@ public interface Query extends BasicQueryContract {
* support for scrollable <tt>ResultSet</tt>s.<br> * support for scrollable <tt>ResultSet</tt>s.<br>
* *
* @see ScrollableResults * @see ScrollableResults
*
* @return the result iterator * @return the result iterator
* @throws HibernateException
*/ */
public ScrollableResults scroll() throws HibernateException; public ScrollableResults scroll();
/** /**
* Return the query results as <tt>ScrollableResults</tt>. The * Return the query results as ScrollableResults. The scrollability of the returned results
* scrollability of the returned results depends upon JDBC driver * depends upon JDBC driver support for scrollable ResultSets.
* support for scrollable <tt>ResultSet</tt>s.<br> *
* @param scrollMode The scroll mode
*
* @return the result iterator
* *
* @see ScrollableResults * @see ScrollableResults
* @see ScrollMode * @see ScrollMode
* @return the result iterator *
* @throws HibernateException
*/ */
public ScrollableResults scroll(ScrollMode scrollMode) throws HibernateException; public ScrollableResults scroll(ScrollMode scrollMode);
/** /**
* Return the query results as a <tt>List</tt>. If the query contains * Return the query results as a <tt>List</tt>. If the query contains
@ -252,44 +269,48 @@ public interface Query extends BasicQueryContract {
* of <tt>Object[]</tt>. * of <tt>Object[]</tt>.
* *
* @return the result list * @return the result list
* @throws HibernateException
*/ */
public List list() throws HibernateException; public List list();
/** /**
* Convenience method to return a single instance that matches * Convenience method to return a single instance that matches
* the query, or null if the query returns no results. * the query, or null if the query returns no results.
* *
* @return the single result or <tt>null</tt> * @return the single result or <tt>null</tt>
*
* @throws NonUniqueResultException if there is more than one matching result * @throws NonUniqueResultException if there is more than one matching result
*/ */
public Object uniqueResult() throws HibernateException; public Object uniqueResult();
/** /**
* Execute the update or delete statement. * Execute the update or delete statement.
* </p> *
* The semantics are compliant with the ejb3 Query.executeUpdate() * The semantics are compliant with the ejb3 Query.executeUpdate() method.
* method.
* *
* @return The number of entities updated or deleted. * @return The number of entities updated or deleted.
* @throws HibernateException
*/ */
public int executeUpdate() throws HibernateException; public int executeUpdate();
/** /**
* Bind a value to a JDBC-style query parameter. * Bind a value to a JDBC-style query parameter.
*
* @param position the position of the parameter in the query * @param position the position of the parameter in the query
* string, numbered from <tt>0</tt>. * string, numbered from <tt>0</tt>.
* @param val the possibly-null parameter value * @param val the possibly-null parameter value
* @param type the Hibernate type * @param type the Hibernate type
*
* @return {@code this}, for method chaining
*/ */
public Query setParameter(int position, Object val, Type type); public Query setParameter(int position, Object val, Type type);
/** /**
* Bind a value to a named query parameter. * Bind a value to a named query parameter.
*
* @param name the name of the parameter * @param name the name of the parameter
* @param val the possibly-null parameter value * @param val the possibly-null parameter value
* @param type the Hibernate type * @param type the Hibernate type
*
* @return {@code this}, for method chaining
*/ */
public Query setParameter(String name, Object val, Type type); public Query setParameter(String name, Object val, Type type);
@ -297,162 +318,535 @@ public interface Query extends BasicQueryContract {
* Bind a value to a JDBC-style query parameter. The Hibernate type of the parameter is * Bind a value to a JDBC-style query parameter. The Hibernate type of the parameter is
* first detected via the usage/position in the query and if not sufficient secondly * first detected via the usage/position in the query and if not sufficient secondly
* guessed from the class of the given object. * guessed from the class of the given object.
*
* @param position the position of the parameter in the query * @param position the position of the parameter in the query
* string, numbered from <tt>0</tt>. * string, numbered from <tt>0</tt>.
* @param val the non-null parameter value * @param val the non-null parameter value
* @throws org.hibernate.HibernateException if no type could be determined *
* @return {@code this}, for method chaining
*/ */
public Query setParameter(int position, Object val) throws HibernateException; public Query setParameter(int position, Object val);
/** /**
* Bind a value to a named query parameter. The Hibernate type of the parameter is * Bind a value to a named query parameter. The Hibernate type of the parameter is
* first detected via the usage/position in the query and if not sufficient secondly * first detected via the usage/position in the query and if not sufficient secondly
* guessed from the class of the given object. * guessed from the class of the given object.
*
* @param name the name of the parameter * @param name the name of the parameter
* @param val the non-null parameter value * @param val the non-null parameter value
* @throws org.hibernate.HibernateException if no type could be determined *
* @return {@code this}, for method chaining
*/ */
public Query setParameter(String name, Object val) throws HibernateException; public Query setParameter(String name, Object val);
/** /**
* Bind values and types to positional parameters. * Bind values and types to positional parameters. Allows binding more than one at a time; no real performance
* impact.
*
* The number of elements in each array should match. That is, element number-0 in types array corresponds to
* element-0 in the values array, etc,
*
* @param types The types
* @param values The values
*
* @return {@code this}, for method chaining
*/ */
public Query setParameters(Object[] values, Type[] types) throws HibernateException; public Query setParameters(Object[] values, Type[] types);
/** /**
* Bind multiple values to a named query parameter. This is useful for binding * Bind multiple values to a named query parameter. This is useful for binding
* a list of values to an expression such as <tt>foo.bar in (:value_list)</tt>. * a list of values to an expression such as <tt>foo.bar in (:value_list)</tt>.
*
* @param name the name of the parameter * @param name the name of the parameter
* @param vals a collection of values to list * @param values a collection of values to list
* @param type the Hibernate type of the values * @param type the Hibernate type of the values
*
* @return {@code this}, for method chaining
*/ */
public Query setParameterList(String name, Collection vals, Type type) throws HibernateException; public Query setParameterList(String name, Collection values, Type type);
/** /**
* Bind multiple values to a named query parameter. The Hibernate type of the parameter is * Bind multiple values to a named query parameter. The Hibernate type of the parameter is
* first detected via the usage/position in the query and if not sufficient secondly * first detected via the usage/position in the query and if not sufficient secondly
* guessed from the class of the first object in the collection. This is useful for binding a list of values * guessed from the class of the first object in the collection. This is useful for binding a list of values
* to an expression such as <tt>foo.bar in (:value_list)</tt>. * to an expression such as <tt>foo.bar in (:value_list)</tt>.
*
* @param name the name of the parameter * @param name the name of the parameter
* @param vals a collection of values to list * @param values a collection of values to list
*
* @return {@code this}, for method chaining
*/ */
public Query setParameterList(String name, Collection vals) throws HibernateException; public Query setParameterList(String name, Collection values);
/** /**
* Bind multiple values to a named query parameter. This is useful for binding * Bind multiple values to a named query parameter. This is useful for binding
* a list of values to an expression such as <tt>foo.bar in (:value_list)</tt>. * a list of values to an expression such as <tt>foo.bar in (:value_list)</tt>.
*
* @param name the name of the parameter * @param name the name of the parameter
* @param vals a collection of values to list * @param values a collection of values to list
* @param type the Hibernate type of the values * @param type the Hibernate type of the values
*
* @return {@code this}, for method chaining
*/ */
public Query setParameterList(String name, Object[] vals, Type type) throws HibernateException; public Query setParameterList(String name, Object[] values, Type type);
/** /**
* Bind multiple values to a named query parameter. The Hibernate type of the parameter is * Bind multiple values to a named query parameter. The Hibernate type of the parameter is
* first detected via the usage/position in the query and if not sufficient secondly * first detected via the usage/position in the query and if not sufficient secondly
* guessed from the class of the first object in the array. This is useful for binding a list of values * guessed from the class of the first object in the array. This is useful for binding a list of values
* to an expression such as <tt>foo.bar in (:value_list)</tt>. * to an expression such as <tt>foo.bar in (:value_list)</tt>.
*
* @param name the name of the parameter * @param name the name of the parameter
* @param vals a collection of values to list * @param values a collection of values to list
*
* @return {@code this}, for method chaining
*/ */
public Query setParameterList(String name, Object[] vals) throws HibernateException; public Query setParameterList(String name, Object[] values);
/** /**
* Bind the property values of the given bean to named parameters of the query, * Bind the property values of the given bean to named parameters of the query,
* matching property names with parameter names and mapping property types to * matching property names with parameter names and mapping property types to
* Hibernate types using hueristics. * Hibernate types using heuristics.
*
* @param bean any JavaBean or POJO * @param bean any JavaBean or POJO
*
* @return {@code this}, for method chaining
*/ */
public Query setProperties(Object bean) throws HibernateException; public Query setProperties(Object bean);
/** /**
* Bind the values of the given Map for each named parameters of the query, * Bind the values of the given Map for each named parameters of the query,
* matching key names with parameter names and mapping value types to * matching key names with parameter names and mapping value types to
* Hibernate types using hueristics. * Hibernate types using heuristics.
*
* @param bean a java.util.Map * @param bean a java.util.Map
*
* @return {@code this}, for method chaining
*/ */
public Query setProperties(Map bean) throws HibernateException; public Query setProperties(Map bean);
/**
* Bind a positional String-valued parameter.
*
* @param position The parameter position
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setString(int position, String val); public Query setString(int position, String val);
/**
* Bind a positional char-valued parameter.
*
* @param position The parameter position
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setCharacter(int position, char val); public Query setCharacter(int position, char val);
/**
* Bind a positional boolean-valued parameter.
*
* @param position The parameter position
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setBoolean(int position, boolean val); public Query setBoolean(int position, boolean val);
/**
* Bind a positional byte-valued parameter.
*
* @param position The parameter position
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setByte(int position, byte val); public Query setByte(int position, byte val);
/**
* Bind a positional short-valued parameter.
*
* @param position The parameter position
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setShort(int position, short val); public Query setShort(int position, short val);
/**
* Bind a positional int-valued parameter.
*
* @param position The parameter position
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setInteger(int position, int val); public Query setInteger(int position, int val);
/**
* Bind a positional long-valued parameter.
*
* @param position The parameter position
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setLong(int position, long val); public Query setLong(int position, long val);
/**
* Bind a positional float-valued parameter.
*
* @param position The parameter position
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setFloat(int position, float val); public Query setFloat(int position, float val);
/**
* Bind a positional double-valued parameter.
*
* @param position The parameter position
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setDouble(int position, double val); public Query setDouble(int position, double val);
/**
* Bind a positional binary-valued parameter.
*
* @param position The parameter position
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setBinary(int position, byte[] val); public Query setBinary(int position, byte[] val);
/**
* Bind a positional String-valued parameter using streaming.
*
* @param position The parameter position
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setText(int position, String val); public Query setText(int position, String val);
/**
* Bind a positional binary-valued parameter using serialization.
*
* @param position The parameter position
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setSerializable(int position, Serializable val); public Query setSerializable(int position, Serializable val);
/**
* Bind a positional Locale-valued parameter.
*
* @param position The parameter position
* @param locale The bind value
*
* @return {@code this}, for method chaining
*/
public Query setLocale(int position, Locale locale); public Query setLocale(int position, Locale locale);
/**
* Bind a positional BigDecimal-valued parameter.
*
* @param position The parameter position
* @param number The bind value
*
* @return {@code this}, for method chaining
*/
public Query setBigDecimal(int position, BigDecimal number); public Query setBigDecimal(int position, BigDecimal number);
/**
* Bind a positional BigDecimal-valued parameter.
*
* @param position The parameter position
* @param number The bind value
*
* @return {@code this}, for method chaining
*/
public Query setBigInteger(int position, BigInteger number); public Query setBigInteger(int position, BigInteger number);
/**
* Bind a positional Date-valued parameter using just the Date portion.
*
* @param position The parameter position
* @param date The bind value
*
* @return {@code this}, for method chaining
*/
public Query setDate(int position, Date date); public Query setDate(int position, Date date);
/**
* Bind a positional Date-valued parameter using just the Time portion.
*
* @param position The parameter position
* @param date The bind value
*
* @return {@code this}, for method chaining
*/
public Query setTime(int position, Date date); public Query setTime(int position, Date date);
/**
* Bind a positional Date-valued parameter using the full Timestamp.
*
* @param position The parameter position
* @param date The bind value
*
* @return {@code this}, for method chaining
*/
public Query setTimestamp(int position, Date date); public Query setTimestamp(int position, Date date);
/**
* Bind a positional Calendar-valued parameter using the full Timestamp portion.
*
* @param position The parameter position
* @param calendar The bind value
*
* @return {@code this}, for method chaining
*/
public Query setCalendar(int position, Calendar calendar); public Query setCalendar(int position, Calendar calendar);
/**
* Bind a positional Calendar-valued parameter using just the Date portion.
*
* @param position The parameter position
* @param calendar The bind value
*
* @return {@code this}, for method chaining
*/
public Query setCalendarDate(int position, Calendar calendar); public Query setCalendarDate(int position, Calendar calendar);
/**
* Bind a named String-valued parameter.
*
* @param name The parameter name
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setString(String name, String val); public Query setString(String name, String val);
/**
* Bind a named char-valued parameter.
*
* @param name The parameter name
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setCharacter(String name, char val); public Query setCharacter(String name, char val);
/**
* Bind a named boolean-valued parameter.
*
* @param name The parameter name
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setBoolean(String name, boolean val); public Query setBoolean(String name, boolean val);
/**
* Bind a named byte-valued parameter.
*
* @param name The parameter name
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setByte(String name, byte val); public Query setByte(String name, byte val);
/**
* Bind a named short-valued parameter.
*
* @param name The parameter name
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setShort(String name, short val); public Query setShort(String name, short val);
/**
* Bind a named int-valued parameter.
*
* @param name The parameter name
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setInteger(String name, int val); public Query setInteger(String name, int val);
/**
* Bind a named long-valued parameter.
*
* @param name The parameter name
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setLong(String name, long val); public Query setLong(String name, long val);
/**
* Bind a named float-valued parameter.
*
* @param name The parameter name
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setFloat(String name, float val); public Query setFloat(String name, float val);
/**
* Bind a named double-valued parameter.
*
* @param name The parameter name
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setDouble(String name, double val); public Query setDouble(String name, double val);
/**
* Bind a named binary-valued parameter.
*
* @param name The parameter name
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setBinary(String name, byte[] val); public Query setBinary(String name, byte[] val);
/**
* Bind a named String-valued parameter using streaming.
*
* @param name The parameter name
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setText(String name, String val); public Query setText(String name, String val);
/**
* Bind a named binary-valued parameter using serialization.
*
* @param name The parameter name
* @param val The bind value
*
* @return {@code this}, for method chaining
*/
public Query setSerializable(String name, Serializable val); public Query setSerializable(String name, Serializable val);
/**
* Bind a named Locale-valued parameter.
*
* @param name The parameter name
* @param locale The bind value
*
* @return {@code this}, for method chaining
*/
public Query setLocale(String name, Locale locale); public Query setLocale(String name, Locale locale);
/**
* Bind a named BigDecimal-valued parameter.
*
* @param name The parameter name
* @param number The bind value
*
* @return {@code this}, for method chaining
*/
public Query setBigDecimal(String name, BigDecimal number); public Query setBigDecimal(String name, BigDecimal number);
/**
* Bind a named BigInteger-valued parameter.
*
* @param name The parameter name
* @param number The bind value
*
* @return {@code this}, for method chaining
*/
public Query setBigInteger(String name, BigInteger number); public Query setBigInteger(String name, BigInteger number);
/** /**
* Bind the date (time is truncated) of a given Date object to a named query parameter. * Bind the date (time is truncated) of a given Date object to a named query parameter.
* *
* @param name The name of the parameter * @param name The name of the parameter
* @param date The date object * @param date The date object
*/ *
* @return {@code this}, for method chaining
*/
public Query setDate(String name, Date date); public Query setDate(String name, Date date);
/** /**
* Bind the time (date is truncated) of a given Date object to a named query parameter. * Bind the time (date is truncated) of a given Date object to a named query parameter.
* *
* @param name The name of the parameter * @param name The name of the parameter
* @param date The date object * @param date The date object
*/ *
* @return {@code this}, for method chaining
*/
public Query setTime(String name, Date date); public Query setTime(String name, Date date);
/** /**
* Bind the date and the time of a given Date object to a named query parameter. * Bind the date and the time of a given Date object to a named query parameter.
* *
* @param name The name of the parameter * @param name The name of the parameter
* @param date The date object * @param date The date object
*/ *
* @return {@code this}, for method chaining
*/
public Query setTimestamp(String name, Date date); public Query setTimestamp(String name, Date date);
/**
* Bind a named Calendar-valued parameter using the full Timestamp.
*
* @param name The parameter name
* @param calendar The bind value
*
* @return {@code this}, for method chaining
*/
public Query setCalendar(String name, Calendar calendar); public Query setCalendar(String name, Calendar calendar);
/**
* Bind a named Calendar-valued parameter using just the Date portion.
*
* @param name The parameter name
* @param calendar The bind value
*
* @return {@code this}, for method chaining
*/
public Query setCalendarDate(String name, Calendar calendar); public Query setCalendarDate(String name, Calendar calendar);
/** /**
* Bind an instance of a mapped persistent class to a JDBC-style query parameter. * Bind an instance of a mapped persistent class to a JDBC-style query parameter.
* Use {@link #setParameter(int, Object)} for null values.
*
* @param position the position of the parameter in the query * @param position the position of the parameter in the query
* string, numbered from <tt>0</tt>. * string, numbered from <tt>0</tt>.
* @param val a non-null instance of a persistent class * @param val a non-null instance of a persistent class
*
* @return {@code this}, for method chaining
*/ */
public Query setEntity(int position, Object val); // use setParameter for null values public Query setEntity(int position, Object val);
/** /**
* Bind an instance of a mapped persistent class to a named query parameter. * Bind an instance of a mapped persistent class to a named query parameter. Use
* {@link #setParameter(String, Object)} for null values.
*
* @param name the name of the parameter * @param name the name of the parameter
* @param val a non-null instance of a persistent class * @param val a non-null instance of a persistent class
*
* @return {@code this}, for method chaining
*/ */
public Query setEntity(String name, Object val); // use setParameter for null values public Query setEntity(String name, Object val);
/** /**
@ -460,7 +854,7 @@ public interface Query extends BasicQueryContract {
* "shape" of the query result. * "shape" of the query result.
* *
* @param transformer The transformer to apply * @param transformer The transformer to apply
* @return this (for method chaining) * @return this (for method chaining)
*/ */
public Query setResultTransformer(ResultTransformer transformer); public Query setResultTransformer(ResultTransformer transformer);

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,53 +20,91 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
import org.jboss.logging.Logger;
/** /**
* A problem occurred translating a Hibernate query to SQL * A problem occurred translating a Hibernate query to SQL due to invalid query syntax, etc.
* due to invalid query syntax, etc.
*/ */
public class QueryException extends HibernateException { public class QueryException extends HibernateException {
private static final Logger log = Logger.getLogger( QueryException.class );
private String queryString; private String queryString;
/**
* Constructs a QueryException using the specified exception message.
*
* @param message A message explaining the exception condition
*/
public QueryException(String message) { public QueryException(String message) {
super(message); super(message);
} }
public QueryException(String message, Throwable e) {
super(message, e); /**
* Constructs a QueryException using the specified exception message and cause.
*
* @param message A message explaining the exception condition
* @param cause The underlying cause
*/
public QueryException(String message, Throwable cause) {
super(message, cause);
} }
/**
* 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
*/
public QueryException(String message, String queryString) { public QueryException(String message, String queryString) {
super(message); super(message);
this.queryString = queryString; this.queryString = queryString;
} }
public QueryException(Exception e) { /**
super(e); * Constructs a QueryException using the specified cause.
*
* @param cause The underlying cause
*/
public QueryException(Exception cause) {
super(cause);
} }
/**
* Retrieve the query being evaluated when the exception occurred. May be null, but generally should not.
*
* @return The query string
*/
public String getQueryString() { public String getQueryString() {
return queryString; 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) { 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; this.queryString = queryString;
} }
@Override
public String getMessage() { public String getMessage() {
String msg = super.getMessage(); String msg = super.getMessage();
if ( queryString!=null ) msg += " [" + queryString + ']'; if ( queryString!=null ) {
msg += " [" + queryString + ']';
}
return msg; return msg;
} }
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,31 +20,21 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
/** /**
* Parameter invalid or not found in the query * Parameter invalid or not found in the query.
* *
* @author Emmanuel Bernard * @author Emmanuel Bernard
*/ */
public class QueryParameterException extends QueryException { public class QueryParameterException extends QueryException {
/**
public QueryParameterException(Exception e) { * Constructs a QueryParameterException using the supplied exception message.
super( e ); *
} * @param message The message explaining the exception condition
*/
public QueryParameterException(String message) { public QueryParameterException(String message) {
super( message ); super( message );
} }
public QueryParameterException(String message, Throwable e) {
super( message, e );
}
public QueryParameterException(String message, String queryString) {
super( message, queryString );
}
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as * Copyright (c) 2009, 2013, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,26 +20,26 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
import java.sql.SQLException; import java.sql.SQLException;
/** /**
*
* Thrown when a database query timeout occurs. * Thrown when a database query timeout occurs.
* *
* @author Scott Marlow * @author Scott Marlow
*/ */
public class QueryTimeoutException extends JDBCException { public class QueryTimeoutException extends JDBCException {
/**
public QueryTimeoutException( String s, JDBCException je, String sql ) { * Constructs a QueryTimeoutException using the supplied information.
super(s, je.getSQLException(), sql); *
} * @param message The message explaining the exception condition
* @param sqlException The underlying SQLException
public QueryTimeoutException( String s, SQLException se, String sql ) { * @param sql The sql being executed when the exception occurred.
super(s, se, sql); */
public QueryTimeoutException(String message, SQLException sqlException, String sql) {
super(message, sqlException, sql);
} }
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,7 +20,6 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
@ -37,6 +36,7 @@ public enum ReplicationMode {
* Throw an exception when a row already exists. * Throw an exception when a row already exists.
*/ */
EXCEPTION { EXCEPTION {
@Override
public boolean shouldOverwriteCurrentVersion(Object entity, Object currentVersion, Object newVersion, VersionType versionType) { public boolean shouldOverwriteCurrentVersion(Object entity, Object currentVersion, Object newVersion, VersionType versionType) {
throw new AssertionFailure( "should not be called" ); throw new AssertionFailure( "should not be called" );
} }
@ -45,6 +45,7 @@ public enum ReplicationMode {
* Ignore replicated entities when a row already exists. * Ignore replicated entities when a row already exists.
*/ */
IGNORE { IGNORE {
@Override
public boolean shouldOverwriteCurrentVersion(Object entity, Object currentVersion, Object newVersion, VersionType versionType) { public boolean shouldOverwriteCurrentVersion(Object entity, Object currentVersion, Object newVersion, VersionType versionType) {
return false; return false;
} }
@ -53,6 +54,7 @@ public enum ReplicationMode {
* Overwrite existing rows when a row already exists. * Overwrite existing rows when a row already exists.
*/ */
OVERWRITE { OVERWRITE {
@Override
public boolean shouldOverwriteCurrentVersion(Object entity, Object currentVersion, Object newVersion, VersionType versionType) { public boolean shouldOverwriteCurrentVersion(Object entity, Object currentVersion, Object newVersion, VersionType versionType) {
return true; return true;
} }
@ -61,17 +63,26 @@ public enum ReplicationMode {
* When a row already exists, choose the latest version. * When a row already exists, choose the latest version.
*/ */
LATEST_VERSION { LATEST_VERSION {
@Override
@SuppressWarnings("unchecked")
public boolean shouldOverwriteCurrentVersion(Object entity, Object currentVersion, Object newVersion, VersionType versionType) { public boolean shouldOverwriteCurrentVersion(Object entity, Object currentVersion, Object newVersion, VersionType versionType) {
if ( versionType == null ) { // always overwrite non-versioned data (because we don't know which is newer)
return true; //always overwrite nonversioned data return versionType == null || versionType.getComparator().compare( currentVersion, newVersion ) <= 0;
}
return versionType.getComparator().compare( currentVersion, newVersion ) <= 0;
} }
}; };
/**
* Determine whether the mode dictates that the data being replicated should overwrite the data found.
*
* @param entity The entity being replicated
* @param currentVersion The version currently on the target database table.
* @param newVersion The replicating version
* @param versionType The version type
*
* @return {@code true} indicates the data should be overwritten; {@code false} indicates it should not.
*/
public abstract boolean shouldOverwriteCurrentVersion(Object entity, Object currentVersion, Object newVersion, VersionType versionType); public abstract boolean shouldOverwriteCurrentVersion(Object entity, Object currentVersion, Object newVersion, VersionType versionType);
} }

View File

@ -29,11 +29,12 @@ package org.hibernate;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class ResourceClosedException extends HibernateException { public class ResourceClosedException extends HibernateException {
public ResourceClosedException(String s) { /**
super( s ); * Constructs a ResourceClosedException using the supplied message.
} *
* @param message The message explaining the exception condition
public ResourceClosedException(String string, Throwable root) { */
super( string, root ); public ResourceClosedException(String message) {
super( message );
} }
} }

View File

@ -28,20 +28,33 @@ import org.hibernate.engine.query.spi.sql.NativeSQLQueryReturn;
import org.hibernate.type.Type; import org.hibernate.type.Type;
/** /**
* Represents a "native sql" query and allows the user to define certain aspects about its execution, such as:<ul> * Represents a "native sql" query.
* <li>result-set value mapping (see below)</li>
* <li>
* Tables used via {@link #addSynchronizedQuerySpace}, {@link #addSynchronizedEntityName} and
* {@link #addSynchronizedEntityClass}. This allows Hibernate to properly know how to deal with auto-flush checking
* as well as cached query results if the results of the query are being cached.
* </li>
* </ul>
* <p/>
* In terms of result-set mapping, there are 3 approaches to defining:<ul>
* <li>If this represents a named sql query, the mapping could be associated with the query as part of its metadata</li>
* <li>A pre-defined (defined in metadata and named) mapping can be associated with {@link #setResultSetMapping}</li>
* <li>Defined locally per the various {@link #addEntity}, {@link #addRoot}, {@link #addJoin}, {@link #addFetch} and {@link #addScalar} methods</li>
* *
* Allows the user to define certain aspects about its execution, such as:<ul>
* <li>
* result-set value mapping (see below)
* </li>
* <li>
* Tables used via {@link #addSynchronizedQuerySpace}, {@link #addSynchronizedEntityName} and
* {@link #addSynchronizedEntityClass}. This allows Hibernate to know how to properly deal with
* auto-flush checking as well as cached query results if the results of the query are being
* cached.
* </li>
* </ul>
*
* In terms of result-set mapping, there are 3 approaches to defining:<ul>
* <li>
* If this represents a named sql query, the mapping could be associated with the query as part
* of its metadata
* </li>
* <li>
* A pre-defined (defined in metadata and named) mapping can be associated with
* {@link #setResultSetMapping}
* </li>
* <li>
* Defined locally per the various {@link #addEntity}, {@link #addRoot}, {@link #addJoin},
* {@link #addFetch} and {@link #addScalar} methods
* </li>
* </ul> * </ul>
* *
* @author Gavin King * @author Gavin King
@ -74,6 +87,11 @@ public interface SQLQuery extends Query, SynchronizeableQuery {
*/ */
public boolean isCallable(); public boolean isCallable();
/**
* Retrieve the returns associated with this query.
*
* @return The return descriptors
*/
public List<NativeSQLQueryReturn> getQueryReturns(); public List<NativeSQLQueryReturn> getQueryReturns();
/** /**
@ -100,7 +118,7 @@ public interface SQLQuery extends Query, SynchronizeableQuery {
public SQLQuery addScalar(String columnAlias, Type type); public SQLQuery addScalar(String columnAlias, Type type);
/** /**
* Add a new root return mapping, returning a {@link RootReturn} to allow further definition * Add a new root return mapping, returning a {@link RootReturn} to allow further definition.
* *
* @param tableAlias The SQL table alias to map to this entity * @param tableAlias The SQL table alias to map to this entity
* @param entityName The name of the entity. * @param entityName The name of the entity.
@ -112,7 +130,7 @@ public interface SQLQuery extends Query, SynchronizeableQuery {
public RootReturn addRoot(String tableAlias, String entityName); public RootReturn addRoot(String tableAlias, String entityName);
/** /**
* Add a new root return mapping, returning a {@link RootReturn} to allow further definition * Add a new root return mapping, returning a {@link RootReturn} to allow further definition.
* *
* @param tableAlias The SQL table alias to map to this entity * @param tableAlias The SQL table alias to map to this entity
* @param entityType The java type of the entity. * @param entityType The java type of the entity.
@ -136,7 +154,7 @@ public interface SQLQuery extends Query, SynchronizeableQuery {
public SQLQuery addEntity(String entityName); public SQLQuery addEntity(String entityName);
/** /**
* Declare a "root" entity * Declare a "root" entity.
* *
* @param tableAlias The SQL table alias * @param tableAlias The SQL table alias
* @param entityName The entity name * @param entityName The entity name
@ -146,7 +164,7 @@ public interface SQLQuery extends Query, SynchronizeableQuery {
public SQLQuery addEntity(String tableAlias, String entityName); public SQLQuery addEntity(String tableAlias, String entityName);
/** /**
* Declare a "root" entity, specifying a lock mode * Declare a "root" entity, specifying a lock mode.
* *
* @param tableAlias The SQL table alias * @param tableAlias The SQL table alias
* @param entityName The entity name * @param entityName The entity name
@ -167,7 +185,7 @@ public interface SQLQuery extends Query, SynchronizeableQuery {
public SQLQuery addEntity(Class entityType); public SQLQuery addEntity(Class entityType);
/** /**
* Declare a "root" entity * Declare a "root" entity.
* *
* @param tableAlias The SQL table alias * @param tableAlias The SQL table alias
* @param entityType The java type of the entity to add as a root * @param entityType The java type of the entity to add as a root
@ -177,7 +195,7 @@ public interface SQLQuery extends Query, SynchronizeableQuery {
public SQLQuery addEntity(String tableAlias, Class entityType); public SQLQuery addEntity(String tableAlias, Class entityType);
/** /**
* Declare a "root" entity, specifying a lock mode * Declare a "root" entity, specifying a lock mode.
* *
* @param tableAlias The SQL table alias * @param tableAlias The SQL table alias
* @param entityName The entity name * @param entityName The entity name
@ -226,7 +244,7 @@ public interface SQLQuery extends Query, SynchronizeableQuery {
public SQLQuery addJoin(String tableAlias, String ownerTableAlias, String joinPropertyName); public SQLQuery addJoin(String tableAlias, String ownerTableAlias, String joinPropertyName);
/** /**
* Declare a join fetch result, specifying a lock mode * Declare a join fetch result, specifying a lock mode.
* *
* @param tableAlias The SQL table alias for the data to be mapped to this fetch * @param tableAlias The SQL table alias for the data to be mapped to this fetch
* @param path The association path ([owner-alias].[property-name]). * @param path The association path ([owner-alias].[property-name]).
@ -252,11 +270,11 @@ public interface SQLQuery extends Query, SynchronizeableQuery {
} }
/** /**
* Allows access to further control how root returns are mapped back from result sets * Allows access to further control how root returns are mapped back from result sets.
*/ */
public static interface RootReturn { public static interface RootReturn {
/** /**
* Set the lock mode for this return * Set the lock mode for this return.
* *
* @param lockMode The new lock mode. * @param lockMode The new lock mode.
* *
@ -265,7 +283,7 @@ public interface SQLQuery extends Query, SynchronizeableQuery {
public RootReturn setLockMode(LockMode lockMode); public RootReturn setLockMode(LockMode lockMode);
/** /**
* Name the column alias that identifies the entity's discriminator * Name the column alias that identifies the entity's discriminator.
* *
* @param columnAlias The discriminator column alias * @param columnAlias The discriminator column alias
* *
@ -274,7 +292,7 @@ public interface SQLQuery extends Query, SynchronizeableQuery {
public RootReturn setDiscriminatorAlias(String columnAlias); public RootReturn setDiscriminatorAlias(String columnAlias);
/** /**
* Add a simple property-to-one-column mapping * Add a simple property-to-one-column mapping.
* *
* @param propertyName The name of the property. * @param propertyName The name of the property.
* @param columnAlias The name of the column * @param columnAlias The name of the column
@ -294,11 +312,11 @@ public interface SQLQuery extends Query, SynchronizeableQuery {
} }
/** /**
* Allows access to further control how join fetch returns are mapped back from result sets * Allows access to further control how join fetch returns are mapped back from result sets.
*/ */
public static interface FetchReturn { public static interface FetchReturn {
/** /**
* Set the lock mode for this return * Set the lock mode for this return.
* *
* @param lockMode The new lock mode. * @param lockMode The new lock mode.
* *
@ -307,7 +325,7 @@ public interface SQLQuery extends Query, SynchronizeableQuery {
public FetchReturn setLockMode(LockMode lockMode); public FetchReturn setLockMode(LockMode lockMode);
/** /**
* Add a simple property-to-one-column mapping * Add a simple property-to-one-column mapping.
* *
* @param propertyName The name of the property. * @param propertyName The name of the property.
* @param columnAlias The name of the column * @param columnAlias The name of the column

View File

@ -27,58 +27,60 @@ package org.hibernate;
import java.sql.ResultSet; import java.sql.ResultSet;
/** /**
* Specifies the type of JDBC scrollable result set to use * Specifies the type of JDBC scrollable result set to use underneath a {@link ScrollableResults}.
* underneath a <tt>ScrollableResults</tt>
* *
* @author Gavin King * @author Gavin King
* @see Query#scroll(ScrollMode)
* @see ScrollableResults
*/ */
public enum ScrollMode { public enum ScrollMode {
/** /**
* Requests a scrollable result that is only scrollable forwards.
*
* @see java.sql.ResultSet#TYPE_FORWARD_ONLY * @see java.sql.ResultSet#TYPE_FORWARD_ONLY
*/ */
FORWARD_ONLY( ResultSet.TYPE_FORWARD_ONLY ), FORWARD_ONLY( ResultSet.TYPE_FORWARD_ONLY ),
/** /**
* Requests a scrollable result which is sensitive to changes in the underlying data.
*
* @see java.sql.ResultSet#TYPE_SCROLL_SENSITIVE * @see java.sql.ResultSet#TYPE_SCROLL_SENSITIVE
*/ */
SCROLL_SENSITIVE( SCROLL_SENSITIVE( ResultSet.TYPE_SCROLL_SENSITIVE ),
ResultSet.TYPE_SCROLL_SENSITIVE
),
/** /**
* Requests a scrollable result which is insensitive to changes in the underlying data.
*
* Note that since the Hibernate session acts as a cache, you * Note that since the Hibernate session acts as a cache, you
* might need to expicitly evict objects, if you need to see * might need to explicitly evict objects, if you need to see
* changes made by other transactions. * changes made by other transactions.
* *
* @see java.sql.ResultSet#TYPE_SCROLL_INSENSITIVE * @see java.sql.ResultSet#TYPE_SCROLL_INSENSITIVE
*/ */
SCROLL_INSENSITIVE( SCROLL_INSENSITIVE( ResultSet.TYPE_SCROLL_INSENSITIVE );
ResultSet.TYPE_SCROLL_INSENSITIVE
);
private final int resultSetType; private final int resultSetType;
private ScrollMode(int level) { private ScrollMode(int level) {
this.resultSetType = level; this.resultSetType = level;
} }
/** /**
* Get the corresponding JDBC scroll type code constant value.
*
* @return the JDBC result set type code * @return the JDBC result set type code
*/ */
public int toResultSetType() { public int toResultSetType() {
return resultSetType; return resultSetType;
} }
/**
* Determine if {@code this} mode is "less than" the provided mode.
*
* @param other The provided mode
*
* @return {@code true} if this mode is less than the other.
*/
public boolean lessThan(ScrollMode other) { public boolean lessThan(ScrollMode other) {
return this.resultSetType < other.resultSetType; return this.resultSetType < other.resultSetType;
} }
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as * Copyright (c) 2013, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,7 +20,6 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
import java.math.BigDecimal; import java.math.BigDecimal;
@ -44,179 +43,335 @@ import org.hibernate.type.Type;
* Contrary to JDBC, columns of results are numbered from zero. * Contrary to JDBC, columns of results are numbered from zero.
* *
* @see Query#scroll() * @see Query#scroll()
*
* @author Gavin King * @author Gavin King
*/ */
public interface ScrollableResults { public interface ScrollableResults {
/** /**
* Advance to the next result * Advance to the next result.
* @return <tt>true</tt> if there is another result *
* @return {@code true} if there is another result
*/ */
public boolean next() throws HibernateException; public boolean next();
/** /**
* Retreat to the previous result * Retreat to the previous result.
* @return <tt>true</tt> if there is a previous result *
* @return {@code true} if there is a previous result
*/ */
public boolean previous() throws HibernateException; public boolean previous();
/** /**
* Scroll an arbitrary number of locations * Scroll the specified number of positions from the current position.
* @param i a positive (forward) or negative (backward) number of rows *
* @return <tt>true</tt> if there is a result at the new location * @param positions a positive (forward) or negative (backward) number of rows
*
* @return {@code true} if there is a result at the new location
*/ */
public boolean scroll(int i) throws HibernateException; public boolean scroll(int positions);
/** /**
* Go to the last result * Go to the last result.
* @return <tt>true</tt> if there are any results *
* @return {@code true} if there are any results
*/ */
public boolean last() throws HibernateException; public boolean last();
/** /**
* Go to the first result * Go to the first result.
* @return <tt>true</tt> if there are any results *
* @return {@code true} if there are any results
*/ */
public boolean first() throws HibernateException; public boolean first();
/** /**
* Go to a location just before first result (this is the initial location) * Go to a location just before first result, This is the location of the cursor on a newly returned
* scrollable result.
*/ */
public void beforeFirst() throws HibernateException; public void beforeFirst();
/** /**
* Go to a location just after the last result * Go to a location just after the last result.
*/ */
public void afterLast() throws HibernateException; public void afterLast();
/** /**
* Is this the first result? * Is this the first result?
* *
* @return <tt>true</tt> if this is the first row of results * @return {@code true} if this is the first row of results, otherwise {@code false}
* @throws HibernateException
*/ */
public boolean isFirst() throws HibernateException; public boolean isFirst();
/** /**
* Is this the last result? * Is this the last result?
* *
* @return <tt>true</tt> if this is the last row of results * @return {@code true} if this is the last row of results.
* @throws HibernateException
*/ */
public boolean isLast() throws HibernateException; public boolean isLast();
/**
* Get the current position in the results. The first position is number 0 (unlike JDBC).
*
* @return The current position number, numbered from 0; -1 indicates that there is no current row
*/
public int getRowNumber();
/**
* Set the current position in the result set. Can be numbered from the first position (positive number) or
* the last row (negative number).
*
* @param rowNumber the row number. A positive number indicates a value numbered from the first row; a
* negative number indicates a value numbered from the last row.
*
* @return true if there is a row at that row number
*/
public boolean setRowNumber(int rowNumber);
/** /**
* Release resources immediately. * Release resources immediately.
*/ */
public void close() throws HibernateException; public void close();
/** /**
* Get the current row of results * Get the current row of results.
* @return an object or array *
* @return The array of results
*/ */
public Object[] get() throws HibernateException; public Object[] get();
/** /**
* Get the <tt>i</tt>th object in the current row of results, without * Get the <tt>i</tt>th object in the current row of results, without
* initializing any other results in the row. This method may be used * initializing any other results in the row. This method may be used
* safely, regardless of the type of the column (ie. even for scalar * safely, regardless of the type of the column (ie. even for scalar
* results). * results).
*
* @param i the column, numbered from zero * @param i the column, numbered from zero
* @return an object of any Hibernate type or <tt>null</tt> *
* @return The requested result object; may return {@code null}
*
* @throws IndexOutOfBoundsException If i is an invalid index.
*/ */
public Object get(int i) throws HibernateException; public Object get(int i);
/** /**
* Get the type of the <tt>i</tt>th column of results * Get the type of the <tt>i</tt>th column of results.
*
* @param i the column, numbered from zero * @param i the column, numbered from zero
*
* @return the Hibernate type * @return the Hibernate type
*
* @throws IndexOutOfBoundsException If i is an invalid index.
*/ */
public Type getType(int i); public Type getType(int i);
/** /**
* Convenience method to read an <tt>integer</tt> * Convenience method to read an integer.
*
* @param col The column, numbered from zero
*
* @return The column value as an integer
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public Integer getInteger(int col) throws HibernateException; public Integer getInteger(int col);
/** /**
* Convenience method to read a <tt>long</tt> * Convenience method to read a long.
*
* @param col The column, numbered from zero
*
* @return The column value as a long
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public Long getLong(int col) throws HibernateException; public Long getLong(int col);
/** /**
* Convenience method to read a <tt>float</tt> * Convenience method to read a float.
*
* @param col The column, numbered from zero
*
* @return The column value as a float
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public Float getFloat(int col) throws HibernateException; public Float getFloat(int col);
/** /**
* Convenience method to read a <tt>boolean</tt> * Convenience method to read a boolean.
*
* @param col The column, numbered from zero
*
* @return The column value as a boolean
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public Boolean getBoolean(int col) throws HibernateException; public Boolean getBoolean(int col);
/** /**
* Convenience method to read a <tt>double</tt> * Convenience method to read a double.
*
* @param col The column, numbered from zero
*
* @return The column value as a double
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public Double getDouble(int col) throws HibernateException; public Double getDouble(int col);
/** /**
* Convenience method to read a <tt>short</tt> * Convenience method to read a short.
*
* @param col The column, numbered from zero
*
* @return The column value as a short
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public Short getShort(int col) throws HibernateException; public Short getShort(int col);
/** /**
* Convenience method to read a <tt>byte</tt> * Convenience method to read a byte.
*
* @param col The column, numbered from zero
*
* @return The column value as a byte
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public Byte getByte(int col) throws HibernateException; public Byte getByte(int col);
/** /**
* Convenience method to read a <tt>character</tt> * Convenience method to read a char.
*
* @param col The column, numbered from zero
*
* @return The column value as a char
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public Character getCharacter(int col) throws HibernateException; public Character getCharacter(int col);
/** /**
* Convenience method to read a <tt>binary</tt> * Convenience method to read a binary (byte[]).
*
* @param col The column, numbered from zero
*
* @return The column value as a binary (byte[])
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public byte[] getBinary(int col) throws HibernateException; public byte[] getBinary(int col);
/** /**
* Convenience method to read <tt>text</tt> * Convenience method to read a String using streaming.
*
* @param col The column, numbered from zero
*
* @return The column value as a String
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public String getText(int col) throws HibernateException; public String getText(int col);
/** /**
* Convenience method to read a <tt>blob</tt> * Convenience method to read a blob.
*
* @param col The column, numbered from zero
*
* @return The column value as a Blob
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public Blob getBlob(int col) throws HibernateException; public Blob getBlob(int col);
/** /**
* Convenience method to read a <tt>clob</tt> * Convenience method to read a clob.
*
* @param col The column, numbered from zero
*
* @return The column value as a Clob
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public Clob getClob(int col) throws HibernateException; public Clob getClob(int col);
/** /**
* Convenience method to read a <tt>string</tt> * Convenience method to read a string.
*
* @param col The column, numbered from zero
*
* @return The column value as a String
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public String getString(int col) throws HibernateException; public String getString(int col);
/** /**
* Convenience method to read a <tt>big_decimal</tt> * Convenience method to read a BigDecimal.
*
* @param col The column, numbered from zero
*
* @return The column value as a BigDecimal
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public BigDecimal getBigDecimal(int col) throws HibernateException; public BigDecimal getBigDecimal(int col);
/** /**
* Convenience method to read a <tt>big_integer</tt> * Convenience method to read a BigInteger.
*
* @param col The column, numbered from zero
*
* @return The column value as a BigInteger
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public BigInteger getBigInteger(int col) throws HibernateException; public BigInteger getBigInteger(int col);
/** /**
* Convenience method to read a <tt>date</tt>, <tt>time</tt> or <tt>timestamp</tt> * Convenience method to read a Date.
*
* @param col The column, numbered from zero
*
* @return The column value as a Date
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public Date getDate(int col) throws HibernateException; public Date getDate(int col);
/** /**
* Convenience method to read a <tt>locale</tt> * Convenience method to read a Locale.
*
* @param col The column, numbered from zero
*
* @return The column value as a Locale
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public Locale getLocale(int col) throws HibernateException; public Locale getLocale(int col);
/** /**
* Convenience method to read a <tt>calendar</tt> or <tt>calendar_date</tt> * Convenience method to read a Calendar.
*
* @param col The column, numbered from zero
*
* @return The column value as a Calendar
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
public Calendar getCalendar(int col) throws HibernateException; public Calendar getCalendar(int col);
/** /**
* Convenience method to read a <tt>currency</tt> * Convenience method to read a TimeZone.
*
* @param col The column, numbered from zero
*
* @return The column value as a TimeZone
*
* @throws IndexOutOfBoundsException If col is an invalid index.
*/ */
//public Currency getCurrency(int col) throws HibernateException; public TimeZone getTimeZone(int col);
/**
* Convenience method to read a <tt>timezone</tt>
*/
public TimeZone getTimeZone(int col) throws HibernateException;
/**
* Get the current location in the result set. The first
* row is number <tt>0</tt>, contrary to JDBC.
* @return the row number, numbered from <tt>0</tt>, or <tt>-1</tt> if
* there is no current row
*/
public int getRowNumber() throws HibernateException;
/**
* Set the current location in the result set, numbered from either the
* first row (row number <tt>0</tt>), or the last row (row
* number <tt>-1</tt>).
* @param rowNumber the row number, numbered from the last row, in the
* case of a negative row number
* @return true if there is a row at that row number
*/
public boolean setRowNumber(int rowNumber) throws HibernateException;
} }

View File

@ -565,6 +565,7 @@ public interface Session extends SharedSessionContract {
* with a session (<tt>LockMode.NONE</tt>). This operation cascades to associated * with a session (<tt>LockMode.NONE</tt>). This operation cascades to associated
* instances if the association is mapped with <tt>cascade="lock"</tt>. * instances if the association is mapped with <tt>cascade="lock"</tt>.
* *
* @param entityName The name of the entity
* @param object a persistent or transient instance * @param object a persistent or transient instance
* @param lockMode the lock level * @param lockMode the lock level
* *
@ -771,7 +772,7 @@ public interface Session extends SharedSessionContract {
public Object get(String entityName, Serializable id, LockOptions lockOptions); public Object get(String entityName, Serializable id, LockOptions lockOptions);
/** /**
* Return the entity name for a persistent entity * Return the entity name for a persistent entity.
* *
* @param object a persistent entity * @param object a persistent entity
* *
@ -932,6 +933,7 @@ public interface Session extends SharedSessionContract {
* execution returns the result of the {@link ReturningWork#execute} call. * execution returns the result of the {@link ReturningWork#execute} call.
* *
* @param work The work to be performed. * @param work The work to be performed.
* @param <T> The type of the result returned from the work
* *
* @return the result from calling {@link ReturningWork#execute}. * @return the result from calling {@link ReturningWork#execute}.
* *
@ -1020,7 +1022,15 @@ public interface Session extends SharedSessionContract {
* Contains locking details (LockMode, Timeout and Scope). * Contains locking details (LockMode, Timeout and Scope).
*/ */
public interface LockRequest { public interface LockRequest {
/**
* Constant usable as a time out value that indicates no wait semantics should be used in
* attempting to acquire locks.
*/
static final int PESSIMISTIC_NO_WAIT = 0; static final int PESSIMISTIC_NO_WAIT = 0;
/**
* Constant usable as a time out value that indicates that attempting to acquire locks should be allowed to
* wait forever (apply no timeout).
*/
static final int PESSIMISTIC_WAIT_FOREVER = -1; static final int PESSIMISTIC_WAIT_FOREVER = -1;
/** /**
@ -1073,8 +1083,19 @@ public interface Session extends SharedSessionContract {
*/ */
LockRequest setScope(boolean scope); LockRequest setScope(boolean scope);
void lock(String entityName, Object object) throws HibernateException; /**
* Perform the requested locking.
*
* @param entityName The name of the entity to lock
* @param object The instance of the entity to lock
*/
void lock(String entityName, Object object);
public void lock(Object object) throws HibernateException; /**
* Perform the requested locking.
*
* @param object The instance of the entity to lock
*/
void lock(Object object);
} }
} }

View File

@ -39,7 +39,7 @@ public interface SessionBuilder {
public Session openSession(); public Session openSession();
/** /**
* Adds a specific interceptor to the session options * Adds a specific interceptor to the session options.
* *
* @param interceptor The interceptor to use. * @param interceptor The interceptor to use.
* *
@ -61,7 +61,7 @@ public interface SessionBuilder {
public SessionBuilder noInterceptor(); public SessionBuilder noInterceptor();
/** /**
* Adds a specific connection to the session options * Adds a specific connection to the session options.
* *
* @param connection The connection to use. * @param connection The connection to use.
* *
@ -70,7 +70,7 @@ public interface SessionBuilder {
public SessionBuilder connection(Connection connection); public SessionBuilder connection(Connection connection);
/** /**
* Use a specific connection release mode for these session options * Use a specific connection release mode for these session options.
* *
* @param connectionReleaseMode The connection release mode to use. * @param connectionReleaseMode The connection release mode to use.
* *
@ -79,7 +79,7 @@ public interface SessionBuilder {
public SessionBuilder connectionReleaseMode(ConnectionReleaseMode connectionReleaseMode); public SessionBuilder connectionReleaseMode(ConnectionReleaseMode connectionReleaseMode);
/** /**
* Should the session built automatically join in any ongoing JTA transactions * Should the session built automatically join in any ongoing JTA transactions.
* *
* @param autoJoinTransactions Should JTA transactions be automatically joined * @param autoJoinTransactions Should JTA transactions be automatically joined
* *
@ -88,7 +88,7 @@ public interface SessionBuilder {
public SessionBuilder autoJoinTransactions(boolean autoJoinTransactions); public SessionBuilder autoJoinTransactions(boolean autoJoinTransactions);
/** /**
* Should the session be automatically closed after transaction completion * Should the session be automatically closed after transaction completion.
* *
* @param autoClose Should the session be automatically closed * @param autoClose Should the session be automatically closed
* *

View File

@ -54,14 +54,33 @@ import org.hibernate.stat.Statistics;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public interface SessionFactory extends Referenceable, Serializable { public interface SessionFactory extends Referenceable, Serializable {
/**
* Aggregator of special options used to build the SessionFactory.
*/
public interface SessionFactoryOptions { public interface SessionFactoryOptions {
/**
* The service registry to use in building the factory.
*
* @return The service registry to use.
*/
public StandardServiceRegistry getServiceRegistry(); public StandardServiceRegistry getServiceRegistry();
/**
* Get the interceptor to use by default for all sessions opened from this factory.
*
* @return The interceptor to use factory wide. May be {@code null}
*/
public Interceptor getInterceptor(); public Interceptor getInterceptor();
public CustomEntityDirtinessStrategy getCustomEntityDirtinessStrategy(); public CustomEntityDirtinessStrategy getCustomEntityDirtinessStrategy();
public CurrentTenantIdentifierResolver getCurrentTenantIdentifierResolver(); public CurrentTenantIdentifierResolver getCurrentTenantIdentifierResolver();
public SessionFactoryObserver[] getSessionFactoryObservers(); public SessionFactoryObserver[] getSessionFactoryObservers();
public EntityNameResolver[] getEntityNameResolvers(); public EntityNameResolver[] getEntityNameResolvers();
/**
* Get the delegate for handling entity-not-found exception conditions.
*
* @return The specific EntityNotFoundDelegate to use, May be {@code null}
*/
public EntityNotFoundDelegate getEntityNotFoundDelegate(); public EntityNotFoundDelegate getEntityNotFoundDelegate();
} }
@ -181,7 +200,7 @@ public interface SessionFactory extends Referenceable, Serializable {
public Map<String,ClassMetadata> getAllClassMetadata(); public Map<String,ClassMetadata> getAllClassMetadata();
/** /**
* Get the {@link CollectionMetadata} for all mapped collections * Get the {@link CollectionMetadata} for all mapped collections.
* *
* @return a map from <tt>String</tt> to <tt>CollectionMetadata</tt> * @return a map from <tt>String</tt> to <tt>CollectionMetadata</tt>
* *
@ -381,7 +400,7 @@ public interface SessionFactory extends Referenceable, Serializable {
public boolean containsFetchProfileDefinition(String name); public boolean containsFetchProfileDefinition(String name);
/** /**
* Retrieve this factory's {@link TypeHelper} * Retrieve this factory's {@link TypeHelper}.
* *
* @return The factory's {@link TypeHelper} * @return The factory's {@link TypeHelper}
*/ */

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,9 +20,9 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
import java.io.Serializable; import java.io.Serializable;
/** /**

View File

@ -26,41 +26,41 @@ package org.hibernate;
import java.sql.Connection; import java.sql.Connection;
/** /**
* Specialized {@link SessionBuilder} with access to stuff from another session * Specialized {@link SessionBuilder} with access to stuff from another session.
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public interface SharedSessionBuilder extends SessionBuilder { public interface SharedSessionBuilder extends SessionBuilder {
/** /**
* Signifies the interceptor from the original session should be used to create the new session * Signifies the interceptor from the original session should be used to create the new session.
* *
* @return {@code this}, for method chaining * @return {@code this}, for method chaining
*/ */
public SharedSessionBuilder interceptor(); public SharedSessionBuilder interceptor();
/** /**
* Signifies that the connection from the original session should be used to create the new session * Signifies that the connection from the original session should be used to create the new session.
* *
* @return {@code this}, for method chaining * @return {@code this}, for method chaining
*/ */
public SharedSessionBuilder connection(); public SharedSessionBuilder connection();
/** /**
* Signifies that the connection release mode from the original session should be used to create the new session * Signifies that the connection release mode from the original session should be used to create the new session.
* *
* @return {@code this}, for method chaining * @return {@code this}, for method chaining
*/ */
public SharedSessionBuilder connectionReleaseMode(); public SharedSessionBuilder connectionReleaseMode();
/** /**
* Signifies that the autoJoinTransaction flag from the original session should be used to create the new session * Signifies that the autoJoinTransaction flag from the original session should be used to create the new session.
* *
* @return {@code this}, for method chaining * @return {@code this}, for method chaining
*/ */
public SharedSessionBuilder autoJoinTransactions(); public SharedSessionBuilder autoJoinTransactions();
/** /**
* Signifies that the autoClose flag from the original session should be used to create the new session * Signifies that the autoClose flag from the original session should be used to create the new session.
* *
* @return {@code this}, for method chaining * @return {@code this}, for method chaining
* *
@ -71,14 +71,14 @@ public interface SharedSessionBuilder extends SessionBuilder {
public SharedSessionBuilder autoClose(); public SharedSessionBuilder autoClose();
/** /**
* Signifies that the flushBeforeCompletion flag from the original session should be used to create the new session * Signifies that the flushBeforeCompletion flag from the original session should be used to create the new session.
* *
* @return {@code this}, for method chaining * @return {@code this}, for method chaining
*/ */
public SharedSessionBuilder flushBeforeCompletion(); public SharedSessionBuilder flushBeforeCompletion();
/** /**
* Signifies that the transaction context from the original session should be used to create the new session * Signifies that the transaction context from the original session should be used to create the new session.
* *
* @return {@code this}, for method chaining * @return {@code this}, for method chaining
*/ */

View File

@ -28,7 +28,7 @@ import java.io.Serializable;
import org.hibernate.procedure.ProcedureCall; import org.hibernate.procedure.ProcedureCall;
/** /**
* Contract methods shared between {@link Session} and {@link StatelessSession} * Contract methods shared between {@link Session} and {@link StatelessSession}.
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
@ -107,7 +107,7 @@ public interface SharedSessionContract extends Serializable {
public ProcedureCall createStoredProcedureCall(String procedureName, Class... resultClasses); public ProcedureCall createStoredProcedureCall(String procedureName, Class... resultClasses);
/** /**
* Creates a call to a stored procedure with specific result set entity mappings * Creates a call to a stored procedure with specific result set entity mappings.
* *
* @param procedureName The name of the procedure. * @param procedureName The name of the procedure.
* @param resultSetMappings The explicit result set mapping(s) to use for mapping the results * @param resultSetMappings The explicit result set mapping(s) to use for mapping the results
@ -117,7 +117,7 @@ public interface SharedSessionContract extends Serializable {
public ProcedureCall createStoredProcedureCall(String procedureName, String... resultSetMappings); public ProcedureCall createStoredProcedureCall(String procedureName, String... resultSetMappings);
/** /**
* Create {@link Criteria} instance for the given class (entity or subclasses/implementors) * Create {@link Criteria} instance for the given class (entity or subclasses/implementors).
* *
* @param persistentClass The class, which is an entity, or has entity subclasses/implementors * @param persistentClass The class, which is an entity, or has entity subclasses/implementors
* *

View File

@ -24,7 +24,7 @@
package org.hibernate; package org.hibernate;
/** /**
* Loads an entity by its natural identifier * Loads an entity by its natural identifier.
* *
* @author Eric Dalquist * @author Eric Dalquist
* @author Steve Ebersole * @author Steve Ebersole

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,17 +20,16 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
import java.io.Serializable; import java.io.Serializable;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
/** /**
* A <tt>StaleStateException</tt> that carries information * A specialized StaleStateException that carries information about the particular entity
* about a particular entity instance that was the source * instance that was the source of the failure.
* of the failure.
* *
* @author Gavin King * @author Gavin King
*/ */
@ -38,9 +37,15 @@ public class StaleObjectStateException extends StaleStateException {
private final String entityName; private final String entityName;
private final Serializable identifier; private final Serializable identifier;
public StaleObjectStateException(String persistentClass, Serializable identifier) { /**
* Constructs a StaleObjectStateException using the supplied information.
*
* @param entityName The name of the entity
* @param identifier The identifier of the entity
*/
public StaleObjectStateException(String entityName, Serializable identifier) {
super("Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)"); super("Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)");
this.entityName = persistentClass; this.entityName = entityName;
this.identifier = identifier; this.identifier = identifier;
} }
@ -53,8 +58,7 @@ public class StaleObjectStateException extends StaleStateException {
} }
public String getMessage() { public String getMessage() {
return super.getMessage() + ": " + return super.getMessage() + " : " + MessageHelper.infoString( entityName, identifier );
MessageHelper.infoString(entityName, identifier);
} }
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,26 +20,26 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
/** /**
* Thrown when a version number or timestamp check failed, indicating that the * Thrown when a version number or timestamp check failed, indicating that the Session contained
* <tt>Session</tt> contained stale data (when using long transactions * stale data (when using long transactions with versioning). Also occurs if we try delete or update
* with versioning). Also occurs if we try delete or update a row that does * a row that does not exist.
* not exist.<br> *
* <br> * Note that this exception often indicates that the user failed to specify the correct
* Note that this exception often indicates that the user failed to specify the * {@code unsaved-value} strategy for an entity
* correct <tt>unsaved-value</tt> strategy for a class!
* *
* @see StaleObjectStateException
* @author Gavin King * @author Gavin King
*/ */
public class StaleStateException extends HibernateException { public class StaleStateException extends HibernateException {
/**
public StaleStateException(String s) { * Constructs a StaleStateException using the supplied message.
super(s); *
* @param message The message explaining the exception condition
*/
public StaleStateException(String message) {
super(message);
} }
} }

View File

@ -52,6 +52,8 @@ public interface StatelessSession extends SharedSessionContract {
* Insert a row. * Insert a row.
* *
* @param entity a new transient instance * @param entity a new transient instance
*
* @return The identifier of the inserted entity
*/ */
public Serializable insert(Object entity); public Serializable insert(Object entity);
@ -60,6 +62,7 @@ public interface StatelessSession extends SharedSessionContract {
* *
* @param entityName The entityName for the entity to be inserted * @param entityName The entityName for the entity to be inserted
* @param entity a new transient instance * @param entity a new transient instance
*
* @return the identifier of the instance * @return the identifier of the instance
*/ */
public Serializable insert(String entityName, Object entity); public Serializable insert(String entityName, Object entity);
@ -97,6 +100,9 @@ public interface StatelessSession extends SharedSessionContract {
/** /**
* Retrieve a row. * Retrieve a row.
* *
* @param entityName The name of the entity to retrieve
* @param id The id of the entity to retrieve
*
* @return a detached entity instance * @return a detached entity instance
*/ */
public Object get(String entityName, Serializable id); public Object get(String entityName, Serializable id);
@ -104,6 +110,9 @@ public interface StatelessSession extends SharedSessionContract {
/** /**
* Retrieve a row. * Retrieve a row.
* *
* @param entityClass The class of the entity to retrieve
* @param id The id of the entity to retrieve
*
* @return a detached entity instance * @return a detached entity instance
*/ */
public Object get(Class entityClass, Serializable id); public Object get(Class entityClass, Serializable id);
@ -111,6 +120,10 @@ public interface StatelessSession extends SharedSessionContract {
/** /**
* Retrieve a row, obtaining the specified lock mode. * Retrieve a row, obtaining the specified lock mode.
* *
* @param entityName The name of the entity to retrieve
* @param id The id of the entity to retrieve
* @param lockMode The lock mode to apply to the entity
*
* @return a detached entity instance * @return a detached entity instance
*/ */
public Object get(String entityName, Serializable id, LockMode lockMode); public Object get(String entityName, Serializable id, LockMode lockMode);
@ -118,6 +131,10 @@ public interface StatelessSession extends SharedSessionContract {
/** /**
* Retrieve a row, obtaining the specified lock mode. * Retrieve a row, obtaining the specified lock mode.
* *
* @param entityClass The class of the entity to retrieve
* @param id The id of the entity to retrieve
* @param lockMode The lock mode to apply to the entity
*
* @return a detached entity instance * @return a detached entity instance
*/ */
public Object get(Class entityClass, Serializable id, LockMode lockMode); public Object get(Class entityClass, Serializable id, LockMode lockMode);
@ -164,6 +181,8 @@ public interface StatelessSession extends SharedSessionContract {
* application should not close the connection. * application should not close the connection.
* *
* @deprecated just missed when deprecating same method from {@link Session} * @deprecated just missed when deprecating same method from {@link Session}
*
* @return The connection associated with this stateless session
*/ */
@Deprecated @Deprecated
public Connection connection(); public Connection connection();

View File

@ -39,7 +39,7 @@ public interface StatelessSessionBuilder {
public StatelessSession openStatelessSession(); public StatelessSession openStatelessSession();
/** /**
* Adds a specific connection to the session options * Adds a specific connection to the session options.
* *
* @param connection The connection to use. * @param connection The connection to use.
* *

View File

@ -26,26 +26,30 @@ package org.hibernate;
import java.util.Collection; import java.util.Collection;
/** /**
* A unifying interface for queries which can define tables (query spaces) to synchronize on.
*
* These query spaces affect the process of auto-flushing by determining which entities will be
* processed by auto-flush based on the table to which those entities are mapped and which are
* determined to have pending state changes.
*
* In a similar manner, these query spaces also affect how query result caching can recognize invalidated results.
*
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public interface SynchronizeableQuery { public interface SynchronizeableQuery {
/** /**
* Obtain the list of query spaces (table names) the query is synchronized on. These spaces affect the process * Obtain the list of query spaces the query is synchronized on.
* of auto-flushing by determining which entities will be processed by auto-flush based on the table to
* which those entities are mapped and which are determined to have pending state changes.
* *
* @return The list of query spaces upon which the query is synchronized. * @return The list of query spaces upon which the query is synchronized.
*/ */
public Collection<String> getSynchronizedQuerySpaces(); public Collection<String> getSynchronizedQuerySpaces();
/** /**
* Adds a query space (table name) for (a) auto-flush checking and (b) query result cache invalidation checking * Adds a query space.
* *
* @param querySpace The query space to be auto-flushed for this query. * @param querySpace The query space to be auto-flushed for this query.
* *
* @return this, for method chaining * @return {@code this}, for method chaining
*
* @see #getSynchronizedQuerySpaces()
*/ */
public SynchronizeableQuery addSynchronizedQuerySpace(String querySpace); public SynchronizeableQuery addSynchronizedQuerySpace(String querySpace);
@ -55,11 +59,9 @@ public interface SynchronizeableQuery {
* *
* @param entityName The name of the entity upon whose defined query spaces we should additionally synchronize. * @param entityName The name of the entity upon whose defined query spaces we should additionally synchronize.
* *
* @return this, for method chaining * @return {@code this}, for method chaining
* *
* @throws MappingException Indicates the given name could not be resolved as an entity * @throws MappingException Indicates the given name could not be resolved as an entity
*
* @see #getSynchronizedQuerySpaces()
*/ */
public SynchronizeableQuery addSynchronizedEntityName(String entityName) throws MappingException; public SynchronizeableQuery addSynchronizedEntityName(String entityName) throws MappingException;
@ -69,11 +71,9 @@ public interface SynchronizeableQuery {
* *
* @param entityClass The class of the entity upon whose defined query spaces we should additionally synchronize. * @param entityClass The class of the entity upon whose defined query spaces we should additionally synchronize.
* *
* @return this, for method chaining * @return {@code this}, for method chaining
* *
* @throws MappingException Indicates the given class could not be resolved as an entity * @throws MappingException Indicates the given class could not be resolved as an entity
*
* @see #getSynchronizedQuerySpaces()
*/ */
public SynchronizeableQuery addSynchronizedEntityClass(Class entityClass) throws MappingException; public SynchronizeableQuery addSynchronizedEntityClass(Class entityClass) throws MappingException;
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,25 +20,31 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
/** /**
* Indicates that a transaction could not be begun, committed * Indicates that a transaction could not be begun, committed
* or rolled back. * or rolled back.
* *
* @see Transaction
* @author Anton van Straaten * @author Anton van Straaten
*/ */
public class TransactionException extends HibernateException { public class TransactionException extends HibernateException {
/**
public TransactionException(String message, Throwable root) { * Constructs a TransactionException using the specified information.
super(message,root); *
* @param message The message explaining the exception condition
* @param cause The underlying cause
*/
public TransactionException(String message, Throwable cause) {
super(message,cause);
} }
/**
* Constructs a TransactionException using the specified information.
*
* @param message The message explaining the exception condition
*/
public TransactionException(String message) { public TransactionException(String message) {
super(message); super(message);
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,22 +20,22 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
/** /**
* Thrown when the user passes a transient instance to a <tt>Session</tt> * Thrown when the user passes a transient instance to a Session method that expects a persistent instance.
* method that expects a persistent instance.
* *
* @author Gavin King * @author Gavin King
*/ */
public class TransientObjectException extends HibernateException { public class TransientObjectException extends HibernateException {
/**
public TransientObjectException(String s) { * Constructs a TransientObjectException using the supplied message.
super(s); *
* @param message The message explaining the exception condition
*/
public TransientObjectException(String message) {
super(message);
} }
} }

View File

@ -82,18 +82,9 @@ public class TransientPropertyValueException extends TransientObjectException {
return propertyName; return propertyName;
} }
/**
* Return the exception message.
* @return the exception message.
*/
@Override @Override
public String getMessage() { public String getMessage() {
return new StringBuilder( super.getMessage() ) return super.getMessage() + " : "
.append( ": " ) + StringHelper.qualify( propertyOwnerEntityName, propertyName ) + " -> " + transientEntityName;
.append( StringHelper.qualify( propertyOwnerEntityName, propertyName ) )
.append( " -> " )
.append( transientEntityName )
.toString();
} }
} }

View File

@ -107,5 +107,13 @@ public interface TypeHelper {
*/ */
public Type custom(Class userTypeClass, Properties properties); public Type custom(Class userTypeClass, Properties properties);
/**
* Retrieve the type representing an ANY mapping.
*
* @param metaType The meta type for the ANY
* @param identifierType The identifier type for the ANY
*
* @return The type, or null
*/
public Type any(Type metaType, Type identifierType); public Type any(Type metaType, Type identifierType);
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,26 +20,21 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
/** /**
* Used when a user provided type does not match the expected one * Used when a user provided type does not match the expected one.
* *
* @author Emmanuel Bernard * @author Emmanuel Bernard
*/ */
public class TypeMismatchException extends HibernateException { public class TypeMismatchException extends HibernateException {
public TypeMismatchException(Throwable root) { /**
super( root ); * Constructs a TypeMismatchException using the supplied message.
} *
* @param message The message explaining the exception condition
public TypeMismatchException(String s) { */
super( s ); public TypeMismatchException(String message) {
} super( message );
public TypeMismatchException(String string, Throwable root) {
super( string, root );
} }
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as * Copyright (c) 2013, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,11 +20,9 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
/** /**
* Used to indicate a request against an unknown profile name. * Used to indicate a request against an unknown profile name.
* *
@ -33,6 +31,11 @@ package org.hibernate;
public class UnknownProfileException extends HibernateException { public class UnknownProfileException extends HibernateException {
private final String name; private final String name;
/**
* Constructs an UnknownProfileException for the given name.
*
* @param name The profile name that was unknown.
*/
public UnknownProfileException(String name) { public UnknownProfileException(String name) {
super( "Unknow fetch profile [" + name + "]" ); super( "Unknow fetch profile [" + name + "]" );
this.name = name; this.name = name;

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * Hibernate, Relational Persistence for Idiomatic Java
* *
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as * Copyright (c) 2013, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,9 +20,9 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
import java.io.Serializable; import java.io.Serializable;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
@ -34,34 +34,53 @@ import org.hibernate.pretty.MessageHelper;
* @author Gavin King * @author Gavin King
*/ */
public class UnresolvableObjectException extends HibernateException { public class UnresolvableObjectException extends HibernateException {
private final Serializable identifier; private final Serializable identifier;
private final String entityName; private final String entityName;
public UnresolvableObjectException(Serializable identifier, String clazz) { /**
this("No row with the given identifier exists", identifier, clazz); * Constructs an UnresolvableObjectException using the specified information.
*
* @param identifier The identifier of the entity which could not be resolved
* @param entityName The name of the entity which could not be resolved
*/
public UnresolvableObjectException(Serializable identifier, String entityName) {
this( "No row with the given identifier exists", identifier, entityName );
} }
UnresolvableObjectException(String message, Serializable identifier, String clazz) {
protected UnresolvableObjectException(String message, Serializable identifier, String clazz) {
super(message); super(message);
this.identifier = identifier; this.identifier = identifier;
this.entityName = clazz; this.entityName = clazz;
} }
public Serializable getIdentifier() {
return identifier; /**
* Factory method for building and throwing an UnresolvableObjectException if the entity is null.
*
* @param entity The entity to check for nullness
* @param identifier The identifier of the entity
* @param entityName The name of the entity
*
* @throws UnresolvableObjectException Thrown if entity is null
*/
public static void throwIfNull(Object entity, Serializable identifier, String entityName)
throws UnresolvableObjectException {
if ( entity == null ) {
throw new UnresolvableObjectException( identifier, entityName );
}
} }
public String getMessage() { public Serializable getIdentifier() {
return super.getMessage() + ": " + return identifier;
MessageHelper.infoString(entityName, identifier);
} }
public String getEntityName() { public String getEntityName() {
return entityName; return entityName;
} }
public static void throwIfNull(Object o, Serializable id, String clazz) @Override
throws UnresolvableObjectException { public String getMessage() {
if (o==null) throw new UnresolvableObjectException(id, clazz); return super.getMessage() + ": " +
MessageHelper.infoString(entityName, identifier);
} }
} }

View File

@ -33,14 +33,33 @@ import org.hibernate.internal.CoreMessageLogger;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class Version { public class Version {
private Version() {
}
/**
* Access to the Hibernate version.
*
* IMPL NOTE : Real value is injected by the build.
*
* @return The Hibernate version
*/
public static String getVersionString() { public static String getVersionString() {
return "[WORKING]"; return "[WORKING]";
} }
/**
* Logs the Hibernate version (using {@link #getVersionString()}) to the logging system.
*/
public static void logVersion() { public static void logVersion() {
Logger.getMessageLogger( CoreMessageLogger.class, Version.class.getName() ).version( getVersionString() ); Logger.getMessageLogger( CoreMessageLogger.class, Version.class.getName() ).version( getVersionString() );
} }
/**
* Prints the Hibernate version (using {@link #getVersionString()}) to SYSOUT. Defined as the main-class in
* the hibernate-core jar
*
* @param args n/a
*/
public static void main(String[] args) { public static void main(String[] args) {
System.out.println( "Hibernate Core {" + getVersionString() + "}" ); System.out.println( "Hibernate Core {" + getVersionString() + "}" );
} }

View File

@ -1,10 +1,10 @@
/* /*
* Hibernate, Relational Persistence for Idiomatic Java * 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 * indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are * 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, * 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 * copy, or redistribute it subject to the terms and conditions of the GNU
@ -20,50 +20,47 @@
* Free Software Foundation, Inc. * Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor * 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*
*/ */
package org.hibernate; package org.hibernate;
import java.io.Serializable; import java.io.Serializable;
/** /**
* Thrown when <tt>Session.load()</tt> selects a row with * Thrown when loading an entity (by identifier) results in a value that cannot be treated as the subclass
* the given primary key (identifier value) but the row's * type requested by the caller.
* discriminator value specifies a subclass that is not
* assignable to the class requested by the user.
* *
* @author Gavin King * @author Gavin King
*/ */
public class WrongClassException extends HibernateException { public class WrongClassException extends HibernateException {
private final Serializable identifier; private final Serializable identifier;
private final String entityName; private final String entityName;
public WrongClassException(String msg, Serializable identifier, String clazz) { /**
super(msg); * Constructs a WrongClassException using the supplied information.
*
* @param message A message explaining the exception condition
* @param identifier The identifier of the entity
* @param entityName The entity-type requested
*/
public WrongClassException(String message, Serializable identifier, String entityName) {
super(
String.format(
"Object [id=%s] was not of the specified subclass [%s] : %s",
identifier,
entityName,
message
)
);
this.identifier = identifier; this.identifier = identifier;
this.entityName = clazz; this.entityName = entityName;
}
public Serializable getIdentifier() {
return identifier;
}
public String getMessage() {
return "Object with id: " +
identifier +
" was not of the specified subclass: " +
entityName +
" (" + super.getMessage() + ")" ;
} }
public String getEntityName() { public String getEntityName() {
return entityName; return entityName;
} }
public Serializable getIdentifier() {
return identifier;
}
} }

View File

@ -204,11 +204,13 @@ public class UnresolvedEntityInsertActions {
if ( entityEntry.getStatus() != Status.MANAGED && entityEntry.getStatus() != Status.READ_ONLY ) { if ( entityEntry.getStatus() != Status.MANAGED && entityEntry.getStatus() != Status.READ_ONLY ) {
throw new IllegalArgumentException( "EntityEntry did not have status MANAGED or READ_ONLY: " + entityEntry ); throw new IllegalArgumentException( "EntityEntry did not have status MANAGED or READ_ONLY: " + entityEntry );
} }
final boolean traceEnabled = LOG.isTraceEnabled();
// Find out if there are any unresolved insertions that are waiting for the // Find out if there are any unresolved insertions that are waiting for the
// specified entity to be resolved. // specified entity to be resolved.
Set<AbstractEntityInsertAction> dependentActions = dependentActionsByTransientEntity.remove( managedEntity ); Set<AbstractEntityInsertAction> dependentActions = dependentActionsByTransientEntity.remove( managedEntity );
if ( dependentActions == null ) { if ( dependentActions == null ) {
if ( LOG.isTraceEnabled() ) { if ( traceEnabled ) {
LOG.tracev( LOG.tracev(
"No unresolved entity inserts that depended on [{0}]", "No unresolved entity inserts that depended on [{0}]",
MessageHelper.infoString( entityEntry.getEntityName(), entityEntry.getId() ) MessageHelper.infoString( entityEntry.getEntityName(), entityEntry.getId() )
@ -217,7 +219,7 @@ public class UnresolvedEntityInsertActions {
return Collections.emptySet(); //NOTE EARLY EXIT! return Collections.emptySet(); //NOTE EARLY EXIT!
} }
Set<AbstractEntityInsertAction> resolvedActions = new IdentitySet( ); Set<AbstractEntityInsertAction> resolvedActions = new IdentitySet( );
if ( LOG.isTraceEnabled() ) { if ( traceEnabled ) {
LOG.tracev( LOG.tracev(
"Unresolved inserts before resolving [{0}]: [{1}]", "Unresolved inserts before resolving [{0}]: [{1}]",
MessageHelper.infoString( entityEntry.getEntityName(), entityEntry.getId() ), MessageHelper.infoString( entityEntry.getEntityName(), entityEntry.getId() ),
@ -225,7 +227,7 @@ public class UnresolvedEntityInsertActions {
); );
} }
for ( AbstractEntityInsertAction dependentAction : dependentActions ) { for ( AbstractEntityInsertAction dependentAction : dependentActions ) {
if ( LOG.isTraceEnabled() ) { if ( traceEnabled ) {
LOG.tracev( LOG.tracev(
"Resolving insert [{0}] dependency on [{1}]", "Resolving insert [{0}] dependency on [{1}]",
MessageHelper.infoString( dependentAction.getEntityName(), dependentAction.getId() ), MessageHelper.infoString( dependentAction.getEntityName(), dependentAction.getId() ),
@ -235,7 +237,7 @@ public class UnresolvedEntityInsertActions {
NonNullableTransientDependencies dependencies = dependenciesByAction.get( dependentAction ); NonNullableTransientDependencies dependencies = dependenciesByAction.get( dependentAction );
dependencies.resolveNonNullableTransientEntity( managedEntity ); dependencies.resolveNonNullableTransientEntity( managedEntity );
if ( dependencies.isEmpty() ) { if ( dependencies.isEmpty() ) {
if ( LOG.isTraceEnabled() ) { if ( traceEnabled ) {
LOG.tracev( LOG.tracev(
"Resolving insert [{0}] (only depended on [{1}])", "Resolving insert [{0}] (only depended on [{1}])",
dependentAction, dependentAction,
@ -247,7 +249,7 @@ public class UnresolvedEntityInsertActions {
resolvedActions.add( dependentAction ); resolvedActions.add( dependentAction );
} }
} }
if ( LOG.isTraceEnabled() ) { if ( traceEnabled ) {
LOG.tracev( LOG.tracev(
"Unresolved inserts after resolving [{0}]: [{1}]", "Unresolved inserts after resolving [{0}]: [{1}]",
MessageHelper.infoString( entityEntry.getEntityName(), entityEntry.getId() ), MessageHelper.infoString( entityEntry.getEntityName(), entityEntry.getId() ),

View File

@ -28,9 +28,8 @@ import java.io.Serializable;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
/** /**
* An operation which may be scheduled for later execution. * An operation which may be scheduled for later execution. Usually, the operation is a database
* Usually, the operation is a database insert/update/delete, * insert/update/delete, together with required second-level cache management.
* together with required second-level cache management.
* *
* @author Gavin King * @author Gavin King
* @author Steve Ebersole * @author Steve Ebersole
@ -51,7 +50,7 @@ public interface Executable {
public void beforeExecutions() throws HibernateException; public void beforeExecutions() throws HibernateException;
/** /**
* Execute this action * Execute this action.
* *
* @throws HibernateException Indicates a problem during execution. * @throws HibernateException Indicates a problem during execution.
*/ */

View File

@ -0,0 +1,5 @@
/**
* Defines SPI hooks into the {@link org.hibernate.engine.spi.ActionQueue}. Mainly for registering custom
* {@link AfterTransactionCompletionProcess} and {@link BeforeTransactionCompletionProcess} hooks.
*/
package org.hibernate.action.spi;

View File

@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*/ */
package org.hibernate.annotations; package org.hibernate.annotations;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
@ -31,9 +32,8 @@ import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.RetentionPolicy.RUNTIME;
/** /**
* Property Access type * Property Access type. Prefer the standard {@link javax.persistence.Access} annotation; however,
* * {@code @Access} is limited to field/property access definitions.
* Prefer the standard {@link javax.persistence.Access} annotation
* *
* @author Emmanuel Bernard * @author Emmanuel Bernard
* *
@ -44,5 +44,8 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME) @Retention(RUNTIME)
@Deprecated @Deprecated
public @interface AccessType { public @interface AccessType {
/**
* The access strategy name.
*/
String value(); String value();
} }

View File

@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*/ */
package org.hibernate.annotations; package org.hibernate.annotations;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.FIELD;
@ -42,8 +43,8 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention( RUNTIME ) @Retention( RUNTIME )
public @interface AnyMetaDef { public @interface AnyMetaDef {
/** /**
* If defined, assign a global meta definition name to be used in an @Any or @ManyToAny annotation * If defined, assign a global meta definition name to be used in an @Any or @ManyToAny annotation. If
* If not defined, the metadata applies to the current property or field * not defined, the metadata applies to the current property or field.
*/ */
String name() default ""; String name() default "";

View File

@ -38,5 +38,8 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@java.lang.annotation.Target( { PACKAGE, TYPE } ) @java.lang.annotation.Target( { PACKAGE, TYPE } )
@Retention( RUNTIME ) @Retention( RUNTIME )
public @interface AnyMetaDefs { public @interface AnyMetaDefs {
/**
* The collective set of any meta-defs.
*/
AnyMetaDef[] value(); AnyMetaDef[] value();
} }

View File

@ -55,7 +55,7 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface AttributeAccessor { public @interface AttributeAccessor {
/** /**
* Names the {@link org.hibernate.property.PropertyAccessor} strategy * Names the {@link org.hibernate.property.PropertyAccessor} strategy.
*/ */
String value(); String value();
} }

View File

@ -56,7 +56,7 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface BatchSize { public @interface BatchSize {
/** /**
* Strictly positive integer * Strictly positive integer.
*/ */
int size(); int size();
} }

View File

@ -32,7 +32,7 @@ import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.RetentionPolicy.RUNTIME;
/** /**
* Add caching strategy to a root entity or a collection * Add caching strategy to a root entity or a collection.
* *
* @author Emmanuel Bernard * @author Emmanuel Bernard
*/ */

View File

@ -26,15 +26,38 @@ package org.hibernate.annotations;
import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.AccessType;
/** /**
* Cache concurrency strategy * Cache concurrency strategy.
* *
* @author Emmanuel Bernard * @author Emmanuel Bernard
*/ */
public enum CacheConcurrencyStrategy { public enum CacheConcurrencyStrategy {
/**
* Indicates no concurrency strategy should be applied.
*/
NONE( null ), NONE( null ),
/**
* Indicates that read-only strategy should be applied.
*
* @see AccessType#READ_ONLY
*/
READ_ONLY( AccessType.READ_ONLY ), READ_ONLY( AccessType.READ_ONLY ),
/**
* Indicates that the non-strict read-write strategy should be applied.
*
* @see AccessType#NONSTRICT_READ_WRITE
*/
NONSTRICT_READ_WRITE( AccessType.NONSTRICT_READ_WRITE ), NONSTRICT_READ_WRITE( AccessType.NONSTRICT_READ_WRITE ),
/**
* Indicates that the read-write strategy should be applied.
*
* @see AccessType#READ_WRITE
*/
READ_WRITE( AccessType.READ_WRITE ), READ_WRITE( AccessType.READ_WRITE ),
/**
* Indicates that the transaction strategy should be applied.
*
* @see AccessType#TRANSACTIONAL
*/
TRANSACTIONAL( AccessType.TRANSACTIONAL ); TRANSACTIONAL( AccessType.TRANSACTIONAL );
private final AccessType accessType; private final AccessType accessType;
@ -43,13 +66,26 @@ public enum CacheConcurrencyStrategy {
this.accessType = accessType; this.accessType = accessType;
} }
private boolean isMatch(String name) { /**
return ( accessType != null && accessType.getExternalName().equalsIgnoreCase( name ) ) * Get the AccessType corresponding to this concurrency strategy.
|| name().equalsIgnoreCase( name ); *
* @return The corresponding concurrency strategy. Note that this will return {@code null} for
* {@link #NONE}
*/
public AccessType toAccessType() {
return accessType;
} }
/**
* Conversion from {@link AccessType} to {@link CacheConcurrencyStrategy}.
*
* @param accessType The access type to convert
*
* @return The corresponding enum value. {@link #NONE} is returned by default if unable to
* recognize {@code accessType} or if {@code accessType} is {@code null}.
*/
public static CacheConcurrencyStrategy fromAccessType(AccessType accessType) { public static CacheConcurrencyStrategy fromAccessType(AccessType accessType) {
if (null == accessType) { if ( null == accessType ) {
return NONE; return NONE;
} }
@ -72,6 +108,13 @@ public enum CacheConcurrencyStrategy {
} }
} }
/**
* Parse an external representation of a CacheConcurrencyStrategy value.
*
* @param name The external representation
*
* @return The corresponding enum value, or {@code null} if not match was found.
*/
public static CacheConcurrencyStrategy parse(String name) { public static CacheConcurrencyStrategy parse(String name) {
if ( READ_ONLY.isMatch( name ) ) { if ( READ_ONLY.isMatch( name ) ) {
return READ_ONLY; return READ_ONLY;
@ -93,7 +136,8 @@ public enum CacheConcurrencyStrategy {
} }
} }
public AccessType toAccessType() { private boolean isMatch(String name) {
return accessType; return ( accessType != null && accessType.getExternalName().equalsIgnoreCase( name ) )
|| name().equalsIgnoreCase( name );
} }
} }

View File

@ -23,6 +23,7 @@
*/ */
package org.hibernate.annotations; package org.hibernate.annotations;
import org.hibernate.CacheMode;
/** /**
* Enumeration for the different interaction modes between the session and * Enumeration for the different interaction modes between the session and
@ -31,11 +32,83 @@ package org.hibernate.annotations;
* @author Emmanuel Bernard * @author Emmanuel Bernard
* @author Carlos Gonzalez-Cadenas * @author Carlos Gonzalez-Cadenas
*/ */
public enum CacheModeType { public enum CacheModeType {
GET, /**
IGNORE, * Corresponds to {@link CacheMode#GET}.
NORMAL, *
PUT, * @see CacheMode#GET
REFRESH */
} GET( CacheMode.GET ),
/**
* Corresponds to {@link CacheMode#IGNORE}.
*
* @see CacheMode#IGNORE
*/
IGNORE( CacheMode.IGNORE ),
/**
* Corresponds to {@link CacheMode#NORMAL}.
*
* @see CacheMode#NORMAL
*/
NORMAL( CacheMode.NORMAL ),
/**
* Corresponds to {@link CacheMode#PUT}.
*
* @see CacheMode#PUT
*/
PUT( CacheMode.PUT ),
/**
* Corresponds to {@link CacheMode#REFRESH}.
*
* @see CacheMode#REFRESH
*/
REFRESH( CacheMode.REFRESH );
private final CacheMode cacheMode;
private CacheModeType(CacheMode cacheMode) {
this.cacheMode = cacheMode;
}
public CacheMode getCacheMode() {
return cacheMode;
}
/**
* Conversion from {@link CacheMode} to {@link CacheModeType}.
*
* @param cacheMode The cache mode to convert
*
* @return The corresponding enum value. Will be {@code null} if the given {@code accessType} is {@code null}.
*/
public static CacheModeType fromCacheMode(CacheMode cacheMode) {
if ( null == cacheMode ) {
return null;
}
switch ( cacheMode ) {
case NORMAL: {
return NORMAL;
}
case GET: {
return GET;
}
case PUT: {
return PUT;
}
case REFRESH: {
return REFRESH;
}
case IGNORE: {
return IGNORE;
}
default: {
throw new IllegalArgumentException( "Unrecognized CacheMode : " + cacheMode );
}
}
}
}

View File

@ -40,5 +40,8 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({METHOD, FIELD}) @Target({METHOD, FIELD})
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface Cascade { public @interface Cascade {
/**
* The cascade value.
*/
CascadeType[] value(); CascadeType[] value();
} }

View File

@ -23,25 +23,62 @@
*/ */
package org.hibernate.annotations; package org.hibernate.annotations;
/** /**
* Cascade types (can override default JPA cascades * Cascade types (can override default JPA cascades).
*/ */
public enum CascadeType { public enum CascadeType {
/**
* Includes all types listed here.
*/
ALL, ALL,
/**
* Corresponds to {@link javax.persistence.CascadeType#PERSIST}.
*/
PERSIST, PERSIST,
/**
* Corresponds to {@link javax.persistence.CascadeType#MERGE}.
*/
MERGE, MERGE,
/**
* Corresponds to {@link javax.persistence.CascadeType#REMOVE}.
*/
REMOVE, REMOVE,
/**
* Corresponds to {@link javax.persistence.CascadeType#REFRESH}.
*/
REFRESH, REFRESH,
/**
* Corresponds to the Hibernate native DELETE action.
*/
DELETE, DELETE,
/**
* Corresponds to the Hibernate native SAVE_UPDATE (direct reattachment) action.
*/
SAVE_UPDATE, SAVE_UPDATE,
/**
* Corresponds to the Hibernate native REPLICATE action.
*/
REPLICATE, REPLICATE,
/** @deprecated use @OneToOne(orphanRemoval=true) or @OneToMany(orphanRemoval=true) */ /**
* Hibernate originally handled orphan removal as a specialized cascade.
*
* @deprecated use @OneToOne(orphanRemoval=true) or @OneToMany(orphanRemoval=true)
*/
@Deprecated @Deprecated
DELETE_ORPHAN, DELETE_ORPHAN,
/**
* Corresponds to the Hibernate native LOCK action.
*/
LOCK, LOCK,
/** @deprecated use javax.persistence.CascadeType.DETACH */ /**
* JPA originally planned on calling DETACH EVICT.
*
* @deprecated use javax.persistence.CascadeType.DETACH
*/
@Deprecated @Deprecated
EVICT, EVICT,
/**
* Corresponds to {@link javax.persistence.CascadeType#REFRESH}.
*/
DETACH DETACH
} }

View File

@ -32,12 +32,15 @@ import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.RetentionPolicy.RUNTIME;
/** /**
* Arbitrary SQL CHECK constraints which can be defined at the class, property or collection level * Arbitrary SQL CHECK constraints which can be defined at the class, property or collection level.
* *
* @author Emmanuel Bernard * @author Emmanuel Bernard
*/ */
@Target({ TYPE, METHOD, FIELD }) @Target({ TYPE, METHOD, FIELD })
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface Check { public @interface Check {
/**
* The check constraints string.
*/
String constraints(); String constraints();
} }

View File

@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*/ */
package org.hibernate.annotations; package org.hibernate.annotations;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import javax.persistence.Column; import javax.persistence.Column;
@ -31,7 +32,8 @@ import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.RetentionPolicy.RUNTIME;
/** /**
* Describe an identifier column for a bag (ie an idbag) * Describe an identifier column for a bag (ie an idbag).
*
* EXPERIMENTAL: the structure of this annotation might slightly change (generator() mix strategy and generator * EXPERIMENTAL: the structure of this annotation might slightly change (generator() mix strategy and generator
* *
* @author Emmanuel Bernard * @author Emmanuel Bernard
@ -39,10 +41,18 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({METHOD, FIELD}) @Target({METHOD, FIELD})
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface CollectionId { public @interface CollectionId {
/** Collection id column(s) */ /**
* Collection id column(s).
*/
Column[] columns(); Column[] columns();
/** id type, type.type() must be set */
/**
* id type, type.type() must be set.
*/
Type type(); Type type();
/** generator name: 'identity' or a defined generator name */
/**
* The generator name. For example 'identity' or a defined generator name
*/
String generator(); String generator();
} }

View File

@ -42,11 +42,11 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface CollectionType { public @interface CollectionType {
/** /**
* Names the type (either {@link org.hibernate.type.CollectionType} or * Names the type.
* {@link org.hibernate.usertype.UserCollectionType} implementation class. Could also name a *
* custom type defined via a {@link TypeDef @TypeDef} * Could name the implementation class (an implementation of {@link org.hibernate.type.CollectionType} or
* * {@link org.hibernate.usertype.UserCollectionType}). Could also name a custom type defined via a
* @return The implementation class to use. * {@link TypeDef @TypeDef}
*/ */
String type(); String type();
@ -54,8 +54,6 @@ public @interface CollectionType {
* Specifies configuration information for the type. Note that if the named type is a * Specifies configuration information for the type. Note that if the named type is a
* {@link org.hibernate.usertype.UserCollectionType}, it must also implement * {@link org.hibernate.usertype.UserCollectionType}, it must also implement
* {@link org.hibernate.usertype.ParameterizedType} in order to receive these values. * {@link org.hibernate.usertype.ParameterizedType} in order to receive these values.
*
* @return The configuration parameters.
*/ */
Parameter[] parameters() default {}; Parameter[] parameters() default {};
} }

View File

@ -43,20 +43,20 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface ColumnTransformer { public @interface ColumnTransformer {
/** /**
* (Logical) column name for which the expression is used * (Logical) column name for which the expression is used.
* *
* This can be left out if the property is bound to a single column * This can be left out if the property is bound to a single column
*/ */
String forColumn() default ""; String forColumn() default "";
/** /**
* Custom SQL expression used to read from the column * Custom SQL expression used to read from the column.
*/ */
String read() default ""; String read() default "";
/** /**
* Custom SQL expression used to write to the column. * Custom SQL expression used to write to the column. The write expression must contain exactly
* The write expression must contain exactly one '?' placeholder for the value. * one '?' placeholder for the value.
*/ */
String write() default ""; String write() default "";
} }

View File

@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*/ */
package org.hibernate.annotations; package org.hibernate.annotations;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.FIELD;
@ -37,5 +38,8 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@java.lang.annotation.Target({FIELD,METHOD}) @java.lang.annotation.Target({FIELD,METHOD})
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface ColumnTransformers { public @interface ColumnTransformers {
/**
* The aggregated transformers.
*/
ColumnTransformer[] value(); ColumnTransformer[] value();
} }

View File

@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*/ */
package org.hibernate.annotations; package org.hibernate.annotations;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import javax.persistence.Column; import javax.persistence.Column;
@ -38,5 +39,8 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({METHOD, FIELD}) @Target({METHOD, FIELD})
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface Columns { public @interface Columns {
/**
* The aggregated columns.
*/
Column[] columns(); Column[] columns();
} }

View File

@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*/ */
package org.hibernate.annotations; package org.hibernate.annotations;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
@ -42,5 +43,8 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({TYPE}) @Target({TYPE})
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface DiscriminatorFormula { public @interface DiscriminatorFormula {
/**
* The formula string.
*/
String value(); String value();
} }

View File

@ -38,18 +38,15 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME) @Retention(RUNTIME)
public @interface DiscriminatorOptions { public @interface DiscriminatorOptions {
/** /**
* "Forces" Hibernate to specify the allowed discriminator values, even when retrieving all instances of the root class. * "Forces" Hibernate to specify the allowed discriminator values, even when retrieving all instances of
* * the root class. {@code true} indicates that the discriminator value should be forced; Default is
* @return {@code true} in case the discriminator value should be forces, {@code false} otherwise. Default is {@code false}. * {@code false}.
*/ */
boolean force() default false; boolean force() default false;
/** /**
* Set this to {@code false}, if your discriminator column is also part of a mapped composite identifier. * Set this to {@code false} if your discriminator column is also part of a mapped composite identifier.
* It tells Hibernate not to include the column in SQL INSERTs. * It tells Hibernate not to include the column in SQL INSERTs. Default is {@code true}.
*
* @return {@code true} in case the discriminator value should be included in inserts, {@code false} otherwise.
* Default is {@code true}.
*/ */
boolean insert() default true; boolean insert() default true;
} }

View File

@ -38,5 +38,9 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target( TYPE ) @Target( TYPE )
@Retention( RUNTIME ) @Retention( RUNTIME )
public @interface DynamicInsert { public @interface DynamicInsert {
/**
* Should dynamic insertion be used for this entity? {@code true} says dynamic insertion will be used.
* Default is {@code true} (since generally this annotation is not used unless the user wants dynamic insertion).
*/
boolean value() default true; boolean value() default true;
} }

View File

@ -42,5 +42,10 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target( TYPE ) @Target( TYPE )
@Retention( RUNTIME ) @Retention( RUNTIME )
public @interface DynamicUpdate { public @interface DynamicUpdate {
/**
* Should dynamic update generation be used for this entity? {@code true} says the update sql will be dynamic
* generated. Default is {@code true} (since generally this annotation is not used unless the user wants dynamic
* generation).
*/
boolean value() default true; boolean value() default true;
} }

View File

@ -0,0 +1,86 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, 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.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Extends {@link javax.persistence.Entity} with Hibernate features.
*
* @author Emmanuel Bernard
*
* @deprecated See individual attributes for intended replacements. To be removed in 4.1
*/
@Target(TYPE)
@Retention(RUNTIME)
@Deprecated
public @interface Entity {
/**
* Is this entity mutable (read only) or not.
*
* @deprecated use {@link org.hibernate.annotations.Immutable}
*/
@Deprecated
boolean mutable() default true;
/**
* Needed column only in SQL on insert.
* @deprecated use {@link DynamicInsert} instead
*/
@Deprecated
boolean dynamicInsert() default false;
/**
* Needed column only in SQL on update.
* @deprecated Use {@link DynamicUpdate} instead
*/
@Deprecated
boolean dynamicUpdate() default false;
/**
* Do a select to retrieve the entity before any potential update.
* @deprecated Use {@link SelectBeforeUpdate} instead
*/
@Deprecated
boolean selectBeforeUpdate() default false;
/**
* polymorphism strategy for this entity.
* @deprecated use {@link Polymorphism} instead
*/
@Deprecated
PolymorphismType polymorphism() default PolymorphismType.IMPLICIT;
/**
* optimistic locking strategy.
* @deprecated use {@link OptimisticLocking} instead.
*/
@Deprecated
OptimisticLockType optimisticLock() default OptimisticLockType.VERSION;
/**
* persister of this entity, default is hibernate internal one.
* @deprecated use {@link Persister} instead
*/
@Deprecated
String persister() default "";
}

Some files were not shown because too many files have changed in this diff Show More