copy test from hem to core

This commit is contained in:
Andrea Boriero 2016-05-04 21:19:34 +01:00 committed by Steve Ebersole
parent 5e30247c6f
commit 37fc401da8
531 changed files with 42555 additions and 284 deletions

View File

@ -1,3 +1,5 @@
import org.apache.tools.ant.filters.ReplaceTokens
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
@ -10,6 +12,15 @@ apply plugin: 'hibernate-matrix-testing'
apply plugin: 'version-injection'
apply plugin: 'org.hibernate.build.gradle.xjc'
configurations {
hibernateJpaModelGenTool {
description = "Dependencies for running the Hibernate JPA Metamodel Generator AnnotationProcessor tool"
}
tests {
description = 'Configuration for the produced test jar'
}
}
dependencies {
compile( libraries.jpa )
compile( libraries.javassist )
@ -33,24 +44,34 @@ dependencies {
provided( "javax.enterprise:cdi-api:1.1-PFD" )
testCompile( project(':hibernate-testing') )
testCompile( libraries.shrinkwrap_api )
testCompile( libraries.shrinkwrap )
testCompile( libraries.validation )
testCompile( libraries.jandex )
testCompile( libraries.classmate )
testCompile( libraries.mockito )
testCompile( 'joda-time:joda-time:2.3' )
testCompile( "org.jboss.weld:weld-core:2.0.0.Beta6" )
testCompile( "org.jboss.weld.arquillian.container:arquillian-weld-ee-embedded-1.1:1.1.2.Final" )
compile( "javax.enterprise:cdi-api:1.1-PFD" ) {
// we need to force it to make sure we influence the one coming from arquillian
force=true
}
testCompile( libraries.validator ) {
// for test runtime
transitive = true
}
testRuntime( libraries.expression_language_api )
testRuntime( libraries.expression_language_impl )
// for testing stored procedure support
testCompile( libraries.derby )
testRuntime( "org.jboss.spec.javax.ejb:jboss-ejb-api_3.2_spec:1.0.0.Alpha2" )
testRuntime( libraries.expression_language_api )
testRuntime( libraries.expression_language_impl )
testRuntime( 'jaxen:jaxen:1.1' )
testRuntime( libraries.javassist )
testCompile( project( ':hibernate-jpamodelgen' ) )
}
mavenPom {
@ -90,7 +111,10 @@ jar {
'javax.naming.spi;resolution:=optional',
'org.apache.tools.ant;resolution:=optional',
'org.apache.tools.ant.taskdefs;resolution:=optional',
'org.apache.tools.ant.types;resolution:=optional'
'org.apache.tools.ant.types;resolution:=optional',
'!javax.enterprise*',
'javax.enterprise.context.spi;resolution:=optional',
'javax.enterprise.inject.spi;resolution:=optional'
// // TODO: Uncomment once EntityManagerFactoryBuilderImpl no longer
// // uses ClassLoaderServiceImpl.
@ -141,8 +165,25 @@ xjc {
tasks.compile.dependsOn generateGrammarSource
tasks."matrix_mariadb" {
beforeTest { descriptor ->
println "Starting test: " + descriptor
task copyBundleResources (type: Copy) {
ext.bundlesTargetDir = file( "${buildDir}/bundles" )
from file('src/test/bundles')
into bundlesTargetDir
ext.bundleTokens = dbBundle[db]
ext.bundleTokens["buildDirName"] = buildDir.absolutePath
filter( ReplaceTokens, tokens: bundleTokens);
doFirst {
bundlesTargetDir.mkdirs()
}
}
processTestResources.dependsOn copyBundleResources
task testJar(type: Jar, dependsOn: testClasses) {
classifier = 'test'
from sourceSets.test.output
}
artifacts {
tests testJar
}

View File

@ -275,7 +275,7 @@ public final class SessionFactoryImpl implements SessionFactoryImplementor {
integrator.integrate( metadata, this, this.serviceRegistry );
integratorObserver.integrators.add( integrator );
}
try {
//Generators:
this.identifierGenerators = new HashMap<>();
@ -316,11 +316,11 @@ public final class SessionFactoryImpl implements SessionFactoryImplementor {
//checking for named queries
if ( settings.isNamedQueryStartupCheckingEnabled() ) {
final Map<String,HibernateException> errors = checkNamedQueries();
if ( ! errors.isEmpty() ) {
final Map<String, HibernateException> errors = checkNamedQueries();
if ( !errors.isEmpty() ) {
StringBuilder failingQueries = new StringBuilder( "Errors in named queries: " );
String sep = "";
for ( Map.Entry<String,HibernateException> entry : errors.entrySet() ) {
for ( Map.Entry<String, HibernateException> entry : errors.entrySet() ) {
LOG.namedQueryError( entry.getKey(), entry.getValue() );
failingQueries.append( sep ).append( entry.getKey() );
sep = ", ";
@ -357,7 +357,7 @@ public final class SessionFactoryImpl implements SessionFactoryImplementor {
// then construct the fetch instance...
fetchProfile.addFetch( new Association( owner, mappingFetch.getAssociation() ), fetchStyle );
( (Loadable) owner ).registerAffectingFetchProfile( fetchProfile.getName() );
((Loadable) owner).registerAffectingFetchProfile( fetchProfile.getName() );
}
fetchProfiles.put( fetchProfile.getName(), fetchProfile );
}
@ -372,6 +372,14 @@ public final class SessionFactoryImpl implements SessionFactoryImplementor {
serviceRegistry.getService( JndiService.class )
);
}
catch (Exception e) {
for ( Integrator integrator : serviceRegistry.getService( IntegratorService.class ).getIntegrators() ) {
integrator.disintegrate( this, serviceRegistry );
integratorObserver.integrators.remove( integrator );
}
throw e;
}
}
private void applyCfgXmlValues(LoadedConfig aggregatedConfig, SessionFactoryServiceRegistry serviceRegistry) {
final JaccService jaccService = serviceRegistry.getService( JaccService.class );

View File

@ -14,6 +14,7 @@ import org.hibernate.boot.Metadata;
import org.hibernate.boot.internal.MetadataImpl;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.spi.CascadeStyle;
import org.hibernate.engine.spi.CascadeStyles;
import org.hibernate.engine.spi.CascadingAction;
import org.hibernate.engine.spi.CascadingActions;
@ -57,6 +58,7 @@ public class JpaIntegrator implements Integrator {
private ListenerFactory jpaListenerFactory;
private CallbackBuilder callbackBuilder;
private CallbackRegistryImpl callbackRegistry;
private CascadeStyle oldPersistCascadeStyle;
private static final DuplicationStrategy JPA_DUPLICATION_STRATEGY = new JPADuplicationStrategy();
@ -73,6 +75,12 @@ public class JpaIntegrator implements Integrator {
SessionFactoryServiceRegistry serviceRegistry) {
// first, register the JPA-specific persist cascade style
try {
oldPersistCascadeStyle = CascadeStyles.getCascadeStyle( "persist" );
}
catch (Exception e) {
}
CascadeStyles.registerCascadeStyle(
"persist",
new PersistCascadeStyle()
@ -146,6 +154,17 @@ public class JpaIntegrator implements Integrator {
@Override
public void disintegrate(SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
if ( oldPersistCascadeStyle == null ) {
CascadeStyles.registerCascadeStyle(
"persist",
null
);
}
CascadeStyles.registerCascadeStyle(
"persist",
(CascadeStyles.BaseCascadeStyle) oldPersistCascadeStyle
);
if ( callbackRegistry != null ) {
callbackRegistry.release();
}

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!-- example of reference to a cfg.xml file -->
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="cfgxmlpar" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.ejb.cfgfile" value="/org/hibernate/jpa/test/pack/cfgxmlpar/hibernate.cfg.xml"/>
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,35 @@
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.url">jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.region_prefix">hibernate.test</property>
<property name="hibernate.jdbc.use_streams_for_binary">true</property>
<property name="hibernate.jdbc.batch_size">0</property>
<property name="hibernate.max_fetch_depth">3</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<property name="hibernate.generate_statistics">true</property>
<property name="test-assertable-setting">value</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.testing.cache.CachingRegionFactory</property>
<mapping class="org.hibernate.jpa.test.Item"/>
<mapping class="org.hibernate.jpa.test.Cat"/>
<mapping class="org.hibernate.jpa.test.Kitten"/>
<mapping class="org.hibernate.jpa.test.Distributor"/>
<class-cache class="org.hibernate.jpa.test.Item" usage="read-write"/>
<collection-cache collection="org.hibernate.jpa.test.Item.distributors" usage="read-write" region="RegionName"/>
<event type="pre-insert"/>
</session-factory>
</hibernate-configuration>

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
version="2.0"
>
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="org.hibernate.jpa.test.pack.defaultpar.IncrementListener">
<pre-persist method-name="increment"/>
</entity-listener>
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
<package>org.hibernate.jpa.test.pack.defaultpar</package>
<entity class="Lighter" access="FIELD" metadata-complete="true">
<attributes>
<id name="name">
<column name="fld_id"/>
</id>
<basic name="power"></basic>
</attributes>
</entity>
<entity class="ApplicationServer">
<entity-listeners>
<entity-listener class="OtherIncrementListener">
<pre-persist method-name="increment"/>
</entity-listener>
</entity-listeners>
</entity>
</entity-mappings>

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!-- example of a default persistence.xml -->
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="defaultpar">
<class>org.hibernate.jpa.test.pack.defaultpar.Lighter</class>
<validation-mode>CALLBACK</validation-mode>
<properties>
<property name="hibernate.dialect" value="@db.dialect@"/>
<property name="hibernate.connection.driver_class" value="@jdbc.driver@"/>
<property name="hibernate.connection.username" value="@jdbc.user@"/>
<property name="hibernate.connection.password" value="@jdbc.pass@"/>
<property name="hibernate.connection.url" value="@jdbc.url@"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.testing.cache.CachingRegionFactory" />
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,25 @@
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping
package="org.hibernate.jpa.test.pack.defaultpar"
>
<class name="Mouse">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>

View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_1_0.xsd"
version="1.0"
>
<!-- use orm_1_0 on purpose (backward compatibility test -->
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="org.hibernate.jpa.test.pack.defaultpar_1_0.IncrementListener1">
<pre-persist method-name="increment"/>
</entity-listener>
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
<package>org.hibernate.jpa.test.pack.defaultpar_1_0</package>
<entity class="org.hibernate.jpa.test.pack.defaultpar_1_0.Lighter1" access="FIELD" metadata-complete="true">
<attributes>
<id name="name">
<column name="fld_id"/>
</id>
<basic name="power"></basic>
</attributes>
</entity>
<entity class="org.hibernate.jpa.test.pack.defaultpar_1_0.ApplicationServer1">
<entity-listeners>
<entity-listener class="OtherIncrementListener1">
<pre-persist method-name="increment"/>
</entity-listener>
</entity-listeners>
</entity>
</entity-mappings>

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!-- example of a default persistence.xml -->
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="defaultpar_1_0">
<class>org.hibernate.jpa.test.pack.defaultpar.Lighter</class>
<properties>
<property name="hibernate.dialect" value="@db.dialect@"/>
<property name="hibernate.connection.driver_class" value="@jdbc.driver@"/>
<property name="hibernate.connection.username" value="@jdbc.user@"/>
<property name="hibernate.connection.password" value="@jdbc.pass@"/>
<property name="hibernate.connection.url" value="@jdbc.url@"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.testing.cache.CachingRegionFactory" />
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,25 @@
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping
package="org.hibernate.jpa.test.pack.defaultpar_1_0"
>
<class name="Mouse1">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
version="2.0"
>
<package>org.hibernate.jpa.test.xml</package>
<entity class="Light" access="FIELD" metadata-complete="true">
<attributes>
<id name="name">
<column name="fld_id"/>
</id>
<basic name="power"></basic>
</attributes>
</entity>
</entity-mappings>

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!-- example of a default persistence.xml -->
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="excludehbmpar" transaction-type="RESOURCE_LOCAL">
<mapping-file>META-INF/orm2.xml</mapping-file>
<properties>
<property name="hibernate.dialect" value="@db.dialect@"/>
<property name="hibernate.connection.driver_class" value="@jdbc.driver@"/>
<property name="hibernate.connection.username" value="@jdbc.user@"/>
<property name="hibernate.connection.password" value="@jdbc.pass@"/>
<property name="hibernate.connection.url" value="@jdbc.url@"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.testing.cache.CachingRegionFactory" />
<property name="hibernate.archive.autodetection" value="class"/>
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,25 @@
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping
package="org.hibernate.jpa.test.pack.excludehbmpar"
>
<class name="Mouse">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
version="2.0"
>
<package>org.hibernate.jpa.test.pack.various</package>
<entity class="Seat" access="PROPERTY" metadata-complete="true">
<attributes>
<id name="number">
<column name="`number`" />
</id>
</attributes>
</entity>
</entity-mappings>

View File

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL">
<jar-file>@buildDirName@/packages/externaljar.jar</jar-file>
<class>org.hibernate.jpa.test.Cat</class>
<class>org.hibernate.jpa.test.Kitten</class>
<class>org.hibernate.jpa.test.Distributor</class>
<class>org.hibernate.jpa.test.Item</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<!-- custom scanner test -->
<property name="hibernate.ejb.resource_scanner" value="org.hibernate.jpa.test.packaging.CustomScanner"/>
<property name="hibernate.dialect" value="@db.dialect@"/>
<property name="hibernate.connection.driver_class" value="@jdbc.driver@"/>
<property name="hibernate.connection.username" value="@jdbc.user@"/>
<property name="hibernate.connection.password" value="@jdbc.pass@"/>
<property name="hibernate.connection.url" value="@jdbc.url@"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.region_prefix" value="hibernate.test"/>
<property name="hibernate.jdbc.use_streams_for_binary" value="true"/>
<property name="hibernate.jdbc.batch_size" value="0"/>
<property name="hibernate.max_fetch_depth" value="3"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.generate_statistics" value="true"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.testing.cache.CachingRegionFactory" />
<property name="hibernate.physical_naming_strategy" value="org.hibernate.jpa.test.MyNamingStrategy"/>
<!-- test naming strategy and fall back to element content -->
<!-- property name="hibernate.ejb.naming_strategy">MyNamingStrategy</property -->
<!-- cache configuration -->
<property name="hibernate.ejb.classcache.org.hibernate.jpa.test.Item" value="read-write"/>
<property name="hibernate.ejb.collectioncache.org.hibernate.jpa.test.Item.distributors"
value="read-write, RegionName"/>
<!-- event overriding -->
<property name="hibernate.ejb.event.pre-insert" value="org.hibernate.jpa.test.NoOpListener"/>
<!-- remove JACC and validator -->
<!-- alternatively to <class> and <property> declarations, you can use a regular hibernate.cfg.xml file -->
<!-- property name="hibernate.ejb.cfgfile" value="/resource-path/to/hibernate.cfg.xml"/ -->
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
version="2.0"
>
<package>org.hibernate.jpa.test.pack.various</package>
<entity class="Seat" access="PROPERTY" metadata-complete="true">
<attributes>
<id name="number">
<column name="`number`" />
</id>
</attributes>
</entity>
</entity-mappings>

View File

@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL">
<jar-file>META-INF/externaljar2.jar</jar-file>
<class>org.hibernate.jpa.test.Cat</class>
<class>org.hibernate.jpa.test.Kitten</class>
<class>org.hibernate.jpa.test.Distributor</class>
<class>org.hibernate.jpa.test.Item</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<!-- custom scanner test -->
<!--<property name="hibernate.ejb.resource_scanner" value="org.hibernate.jpa.test.packaging.CustomScanner"/>-->
<property name="hibernate.dialect" value="@db.dialect@"/>
<property name="hibernate.connection.driver_class" value="@jdbc.driver@"/>
<property name="hibernate.connection.username" value="@jdbc.user@"/>
<property name="hibernate.connection.password" value="@jdbc.pass@"/>
<property name="hibernate.connection.url" value="@jdbc.url@"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.region_prefix" value="hibernate.test"/>
<property name="hibernate.jdbc.use_streams_for_binary" value="true"/>
<property name="hibernate.jdbc.batch_size" value="0"/>
<property name="hibernate.max_fetch_depth" value="3"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.generate_statistics" value="true"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.testing.cache.CachingRegionFactory" />
<property name="hibernate.physical_naming_strategy" value="org.hibernate.jpa.test.MyNamingStrategy"/>
<!-- test naming strategy and fall back to element content -->
<!-- property name="hibernate.ejb.naming_strategy">MyNamingStrategy</property -->
<!-- cache configuration -->
<property name="hibernate.ejb.classcache.org.hibernate.jpa.test.Item" value="read-write"/>
<property name="hibernate.ejb.collectioncache.org.hibernate.jpa.test.Item.distributors"
value="read-write, RegionName"/>
<!-- event overriding -->
<property name="hibernate.ejb.event.pre-insert" value="org.hibernate.jpa.test.NoOpListener"/>
<!-- remove JACC and validator -->
<!-- alternatively to <class> and <property> declarations, you can use a regular hibernate.cfg.xml file -->
<!-- property name="hibernate.ejb.cfgfile" value="/resource-path/to/hibernate.cfg.xml"/ -->
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!-- example of a default persistence.xml -->
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="explodedpar" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="@db.dialect@"/>
<property name="hibernate.connection.driver_class" value="@jdbc.driver@"/>
<property name="hibernate.connection.username" value="@jdbc.user@"/>
<property name="hibernate.connection.password" value="@jdbc.pass@"/>
<property name="hibernate.connection.url" value="@jdbc.url@"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.testing.cache.CachingRegionFactory" />
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,19 @@
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.jpa.test.pack.explodedpar">
<class name="Elephant">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
version="2.0"
>
<package>org.hibernate.jpa.test.pack.various</package>
<entity class="Airplane" metadata-complete="true" access="PROPERTY">
<attributes>
<id name="serialNumber"/>
</attributes>
</entity>
</entity-mappings>

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="overridenpar">
<jta-data-source>java:/unreachableDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="@db.dialect@"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.testing.cache.CachingRegionFactory" />
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,10 @@
#
# Hibernate, Relational Persistence for Idiomatic Java
#
# License: GNU Lesser General Public License (LGPL), version 2.1 or later.
# See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
#
hibernate.connection.driver_class @jdbc.driver@
hibernate.connection.url @jdbc.url@
hibernate.connection.username @jdbc.user@
hibernate.connection.password @jdbc.pass@

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!-- example of a default persistence.xml -->
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="space par">
<properties>
<property name="hibernate.dialect" value="@db.dialect@"/>
<property name="hibernate.connection.driver_class" value="@jdbc.driver@"/>
<property name="hibernate.connection.username" value="@jdbc.user@"/>
<property name="hibernate.connection.password" value="@jdbc.pass@"/>
<property name="hibernate.connection.url" value="@jdbc.url@"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.testing.cache.CachingRegionFactory" />
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
version="2.0"
>
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="org.hibernate.jpa.test.pack.defaultpar.IncrementListener">
<pre-persist method-name="increment"/>
</entity-listener>
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
<package>org.hibernate.jpa.test.pack.defaultpar</package>
<entity class="Lighter" access="FIELD" metadata-complete="true">
<attributes>
<id name="name">
<column name="fld_id"/>
</id>
<basic name="power"></basic>
</attributes>
</entity>
<entity class="ApplicationServer">
<entity-listeners>
<entity-listener class="OtherIncrementListener">
<pre-persist method-name="increment"/>
</entity-listener>
</entity-listeners>
</entity>
</entity-mappings>

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!-- example of a default persistence.xml -->
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="defaultpar">
<class>org.hibernate.jpa.test.pack.defaultpar.Lighter</class>
<properties>
<property name="hibernate.dialect" value="@db.dialect@"/>
<property name="hibernate.connection.driver_class" value="@jdbc.driver@"/>
<property name="hibernate.connection.username" value="@jdbc.user@"/>
<property name="hibernate.connection.password" value="@jdbc.pass@"/>
<property name="hibernate.connection.url" value="@jdbc.url@"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.cache.region.factory_class" value="org.hibernate.testing.cache.CachingRegionFactory" />
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,23 @@
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.jpa.test.pack.war">
<class name="Mouse">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>

View File

@ -0,0 +1,16 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
/**
* @author Emmanuel Bernard
*/
public class NoPackageEntity {
private Integer id;
private String name;
}

View File

@ -0,0 +1,334 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl;
import org.hibernate.bytecode.enhance.spi.EnhancementContext;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.jpa.AvailableSettings;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.After;
import org.junit.Before;
import org.jboss.logging.Logger;
/**
* A base class for all ejb tests.
*
* @author Emmanuel Bernard
* @author Hardy Ferentschik
*/
public abstract class BaseEntityManagerFunctionalTestCase extends BaseUnitTestCase {
private static final Logger log = Logger.getLogger( BaseEntityManagerFunctionalTestCase.class );
// IMPL NOTE : Here we use @Before and @After (instead of @BeforeClassOnce and @AfterClassOnce like we do in
// BaseCoreFunctionalTestCase) because the old HEM test methodology was to create an EMF for each test method.
private static final Dialect dialect = Dialect.getDialect();
private StandardServiceRegistryImpl serviceRegistry;
private SessionFactoryImplementor entityManagerFactory;
private EntityManager em;
private ArrayList<EntityManager> isolatedEms = new ArrayList<EntityManager>();
protected Dialect getDialect() {
return dialect;
}
protected SessionFactoryImplementor entityManagerFactory() {
return entityManagerFactory;
}
protected StandardServiceRegistryImpl serviceRegistry() {
return serviceRegistry;
}
@Before
@SuppressWarnings( {"UnusedDeclaration"})
public void buildEntityManagerFactory() throws Exception {
log.trace( "Building EntityManagerFactory" );
entityManagerFactory = Bootstrap.getEntityManagerFactoryBuilder(
buildPersistenceUnitDescriptor(),
buildSettings()
).build().unwrap( SessionFactoryImplementor.class );
serviceRegistry = (StandardServiceRegistryImpl) entityManagerFactory.getServiceRegistry()
.getParentServiceRegistry();
afterEntityManagerFactoryBuilt();
}
private PersistenceUnitDescriptor buildPersistenceUnitDescriptor() {
return new TestingPersistenceUnitDescriptorImpl( getClass().getSimpleName() );
}
public static class TestingPersistenceUnitDescriptorImpl implements PersistenceUnitDescriptor {
private final String name;
public TestingPersistenceUnitDescriptorImpl(String name) {
this.name = name;
}
@Override
public URL getPersistenceUnitRootUrl() {
return null;
}
@Override
public String getName() {
return name;
}
@Override
public String getProviderClassName() {
return HibernatePersistenceProvider.class.getName();
}
@Override
public boolean isUseQuotedIdentifiers() {
return false;
}
@Override
public boolean isExcludeUnlistedClasses() {
return false;
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
return null;
}
@Override
public ValidationMode getValidationMode() {
return null;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return null;
}
@Override
public List<String> getManagedClassNames() {
return null;
}
@Override
public List<String> getMappingFileNames() {
return null;
}
@Override
public List<URL> getJarFileUrls() {
return null;
}
@Override
public Object getNonJtaDataSource() {
return null;
}
@Override
public Object getJtaDataSource() {
return null;
}
@Override
public Properties getProperties() {
return null;
}
@Override
public ClassLoader getClassLoader() {
return null;
}
@Override
public ClassLoader getTempClassLoader() {
return null;
}
@Override
public void pushClassTransformer(EnhancementContext enhancementContext) {
}
}
@SuppressWarnings("unchecked")
protected Map buildSettings() {
Map settings = getConfig();
addMappings( settings );
if ( createSchema() ) {
settings.put( org.hibernate.cfg.AvailableSettings.HBM2DDL_AUTO, "create-drop" );
}
settings.put( org.hibernate.cfg.AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true" );
settings.put( org.hibernate.cfg.AvailableSettings.DIALECT, getDialect().getClass().getName() );
return settings;
}
@SuppressWarnings("unchecked")
protected void addMappings(Map settings) {
String[] mappings = getMappings();
if ( mappings != null ) {
settings.put( AvailableSettings.HBXML_FILES, StringHelper.join( ",", mappings ) );
}
}
protected static final String[] NO_MAPPINGS = new String[0];
protected String[] getMappings() {
return NO_MAPPINGS;
}
protected Map getConfig() {
Map<Object, Object> config = Environment.getProperties();
ArrayList<Class> classes = new ArrayList<Class>();
classes.addAll( Arrays.asList( getAnnotatedClasses() ) );
config.put( AvailableSettings.LOADED_CLASSES, classes );
for ( Map.Entry<Class, String> entry : getCachedClasses().entrySet() ) {
config.put( AvailableSettings.CLASS_CACHE_PREFIX + "." + entry.getKey().getName(), entry.getValue() );
}
for ( Map.Entry<String, String> entry : getCachedCollections().entrySet() ) {
config.put( AvailableSettings.COLLECTION_CACHE_PREFIX + "." + entry.getKey(), entry.getValue() );
}
if ( getEjb3DD().length > 0 ) {
ArrayList<String> dds = new ArrayList<String>();
dds.addAll( Arrays.asList( getEjb3DD() ) );
config.put( AvailableSettings.XML_FILE_NAMES, dds );
}
addConfigOptions( config );
return config;
}
protected void addConfigOptions(Map options) {
}
protected static final Class<?>[] NO_CLASSES = new Class[0];
protected Class<?>[] getAnnotatedClasses() {
return NO_CLASSES;
}
public Map<Class, String> getCachedClasses() {
return new HashMap<Class, String>();
}
public Map<String, String> getCachedCollections() {
return new HashMap<String, String>();
}
public String[] getEjb3DD() {
return new String[] { };
}
protected void afterEntityManagerFactoryBuilt() {
}
protected boolean createSchema() {
return true;
}
@After
@SuppressWarnings( {"UnusedDeclaration"})
public void releaseResources() {
try {
releaseUnclosedEntityManagers();
}
finally {
if ( entityManagerFactory != null && entityManagerFactory.isOpen()) {
entityManagerFactory.close();
}
}
// Note we don't destroy the service registry as we are not the ones creating it
}
private void releaseUnclosedEntityManagers() {
releaseUnclosedEntityManager( this.em );
for ( EntityManager isolatedEm : isolatedEms ) {
releaseUnclosedEntityManager( isolatedEm );
}
}
private void releaseUnclosedEntityManager(EntityManager em) {
if ( em == null ) {
return;
}
if ( !em.isOpen() ) {
return;
}
if ( em.getTransaction().isActive() ) {
em.getTransaction().rollback();
log.warn("You left an open transaction! Fix your test case. For now, we are closing it for you.");
}
if ( em.isOpen() ) {
// as we open an EM beforeQuery the test runs, it will still be open if the test uses a custom EM.
// or, the person may have forgotten to close. So, do not raise a "fail", but log the fact.
em.close();
log.warn("The EntityManager is not closed. Closing it.");
}
}
protected EntityManager getOrCreateEntityManager() {
if ( em == null || !em.isOpen() ) {
em = entityManagerFactory.createEntityManager();
}
return em;
}
protected EntityManager createIsolatedEntityManager() {
EntityManager isolatedEm = entityManagerFactory.createEntityManager();
isolatedEms.add( isolatedEm );
return isolatedEm;
}
protected EntityManager createIsolatedEntityManager(Map props) {
EntityManager isolatedEm = entityManagerFactory.createEntityManager(props);
isolatedEms.add( isolatedEm );
return isolatedEm;
}
protected EntityManager createEntityManager() {
return createEntityManager( Collections.emptyMap() );
}
protected EntityManager createEntityManager(Map properties) {
// always reopen a new EM and close the existing one
if ( em != null && em.isOpen() ) {
em.close();
}
em = entityManagerFactory.createEntityManager( properties );
return em;
}
}

View File

@ -0,0 +1,182 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.PostLoad;
import javax.persistence.PostPersist;
import javax.persistence.PostUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import org.jboss.logging.Logger;
/**
* @author Emmanuel Bernard
*/
@SuppressWarnings({"unchecked", "serial"})
@Entity
@EntityListeners( LastUpdateListener.class )
public class Cat implements Serializable {
private static final Logger log = Logger.getLogger( Cat.class );
private static final List ids = new ArrayList(); // used for assertions
public static int postVersion = 0; // used for assertions
private Integer id;
private String name;
private Date dateOfBirth;
private int age;
private long length;
private Date lastUpdate;
private int manualVersion = 0;
private List<Kitten> kittens;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public int getManualVersion() {
return manualVersion;
}
public void setManualVersion(int manualVersion) {
this.manualVersion = manualVersion;
}
@Transient
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Basic
@Temporal( TemporalType.TIMESTAMP )
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
@PostUpdate
private void someLateUpdateWorking() {
log.debug("PostUpdate for: " + this.toString());
postVersion++;
}
@PostLoad
public void calculateAge() {
Calendar birth = new GregorianCalendar();
birth.setTime( dateOfBirth );
Calendar now = new GregorianCalendar();
now.setTime( new Date() );
int adjust = 0;
if ( now.get( Calendar.DAY_OF_YEAR ) - birth.get( Calendar.DAY_OF_YEAR ) < 0 ) {
adjust = -1;
}
age = now.get( Calendar.YEAR ) - birth.get( Calendar.YEAR ) + adjust;
}
@PostPersist
public synchronized void addIdsToList() {
ids.add( getId() );
}
public static synchronized List getIdList() {
return Collections.unmodifiableList( ids );
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
@OneToMany(cascade = CascadeType.ALL)
public List<Kitten> getKittens() {
return kittens;
}
public void setKittens(List<Kitten> kittens) {
this.kittens = kittens;
}
/**
* Constructs a <code>String</code> with all attributes
* in name = value format.
*
* @return a <code>String</code> representation
* of this object.
*/
@Override
public String toString()
{
final String TAB = " ";
String retValue = "";
retValue = "Cat ( "
+ super.toString() + TAB
+ "id = " + this.id + TAB
+ "name = " + this.name + TAB
+ "dateOfBirth = " + this.dateOfBirth + TAB
+ "age = " + this.age + TAB
+ "length = " + this.length + TAB
+ "lastUpdate = " + this.lastUpdate + TAB
+ "manualVersion = " + this.manualVersion + TAB
+ "postVersion = " + Cat.postVersion + TAB
+ "kittens = " + this.kittens + TAB
+ " )";
return retValue;
}
}

View File

@ -0,0 +1,62 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test;
import java.io.Serializable;
import javax.persistence.Embeddable;
/**
*
*/
@Embeddable
public class CompositeId implements Serializable {
private int id1;
private int id2;
public CompositeId() {
}
public CompositeId(int id1, int id2) {
this.id1 = id1;
this.id2 = id2;
}
public int getId1() {
return id1;
}
public void setId1( int id1 ) {
this.id1 = id1;
}
public int getId2() {
return id2;
}
public void setId2( int id2 ) {
this.id2 = id2;
}
@Override
public boolean equals( Object obj ) {
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final CompositeId other = (CompositeId)obj;
if (this.id1 != other.id1) return false;
if (this.id2 != other.id2) return false;
return true;
}
@Override
public int hashCode() {
int hash = 5;
hash = 73 * hash + this.id1;
hash = 73 * hash + this.id2;
return hash;
}
}

View File

@ -0,0 +1,36 @@
package org.hibernate.jpa.test;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.hibernate.testing.DialectChecks;
import org.hibernate.testing.RequiresDialectFeature;
import org.junit.Test;
import org.hibernate.testing.TestForIssue;
import static org.junit.Assert.assertThat;
import static org.hamcrest.core.Is.is;
@TestForIssue( jiraKey = "HHH-9029")
@RequiresDialectFeature(DialectChecks.SupportsRowValueConstructorSyntaxCheck.class)
public class CompositeIdRowValueTest extends BaseEntityManagerFunctionalTestCase {
@Test
public void testTupleAfterSubQuery() {
EntityManager em = getOrCreateEntityManager();
Query q = em.createQuery("SELECT e FROM EntityWithCompositeId e "
+ "WHERE EXISTS (SELECT 1 FROM EntityWithCompositeId) "
+ "AND e.id = :id");
q.setParameter("id", new CompositeId(1, 2));
assertThat(q.getResultList().size(), is(0));
}
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] {EntityWithCompositeId.class, CompositeId.class};
}
}

View File

@ -0,0 +1,38 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
*
*/
public class CountEntityWithCompositeIdTest extends BaseEntityManagerFunctionalTestCase {
@Test
public void shouldCount() {
EntityManager em = getOrCreateEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<EntityWithCompositeId> r = cq.from(EntityWithCompositeId.class);
cq.multiselect(cb.count(r));
assertThat(em.createQuery(cq).getSingleResult().intValue(), is(0));
}
@Override
protected Class[] getAnnotatedClasses() {
return new Class[] {EntityWithCompositeId.class, CompositeId.class};
}
}

View File

@ -0,0 +1,55 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Distributor implements Serializable {
private Integer id;
private String name;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean equals(Object o) {
if ( this == o ) return true;
if ( !( o instanceof Distributor ) ) return false;
final Distributor distributor = (Distributor) o;
if ( !name.equals( distributor.name ) ) return false;
return true;
}
public int hashCode() {
return name.hashCode();
}
}

View File

@ -0,0 +1,83 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import org.hibernate.engine.transaction.internal.jta.JtaStatusHelper;
import org.hibernate.jpa.AvailableSettings;
import org.hibernate.testing.jta.TestingJtaBootstrap;
import org.hibernate.testing.jta.TestingJtaPlatformImpl;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* EntityManagerFactoryClosedTest
*
* @author Scott Marlow
*/
public class EntityManagerFactoryClosedTest extends BaseEntityManagerFunctionalTestCase {
@Override
protected void addConfigOptions(Map options) {
super.addConfigOptions( options );
TestingJtaBootstrap.prepare(options);
options.put( AvailableSettings.TRANSACTION_TYPE, "JTA" );
}
/**
* Test that using a closed EntityManagerFactory throws an IllegalStateException
* Also ensure that HHH-8586 doesn't regress.
* @throws Exception
*/
@Test
public void testWithTransactionalEnvironment() throws Exception {
assertFalse( JtaStatusHelper.isActive(TestingJtaPlatformImpl.INSTANCE.getTransactionManager()) );
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
assertTrue( JtaStatusHelper.isActive(TestingJtaPlatformImpl.INSTANCE.getTransactionManager()) );
EntityManagerFactory entityManagerFactory = entityManagerFactory();
entityManagerFactory.close(); // close the underlying entity manager factory
try {
entityManagerFactory.createEntityManager();
fail( "expected IllegalStateException when calling emf.createEntityManager with closed emf" );
} catch( IllegalStateException expected ) {
// success
}
try {
entityManagerFactory.getCriteriaBuilder();
fail( "expected IllegalStateException when calling emf.getCriteriaBuilder with closed emf" );
} catch( IllegalStateException expected ) {
// success
}
try {
entityManagerFactory.getCache();
fail( "expected IllegalStateException when calling emf.getCache with closed emf" );
} catch( IllegalStateException expected ) {
// success
}
assertFalse( entityManagerFactory.isOpen() );
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
}
}

View File

@ -0,0 +1,102 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import org.hibernate.SessionFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.hibernate.testing.TestForIssue;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
/**
* Test various unwrap scenarios for {@code EntityManagerFactory}.
*/
@TestForIssue(jiraKey = "HHH-9665")
public class EntityManagerFactoryUnwrapTest extends BaseEntityManagerFunctionalTestCase {
private EntityManagerFactory entityManagerFactory;
@Override
public Class[] getAnnotatedClasses() {
return new Class[] { };
}
@Before
public void setUp() {
entityManagerFactory = entityManagerFactory();
}
@Test
public void testEntityManagerCanBeUnwrappedToSessionFactory() {
SessionFactory sessionFactory = entityManagerFactory.unwrap( SessionFactory.class );
assertNotNull( "Unwrapping to API class SessionFactory should be ok", sessionFactory );
}
@Test
public void testEntityManagerCanBeUnwrappedToSessionFactoryImplementor() {
SessionFactoryImplementor sessionFactoryImplementor = entityManagerFactory.unwrap( SessionFactoryImplementor.class );
assertNotNull( "Unwrapping to SPI class SessionFactoryImplementor should be ok", sessionFactoryImplementor );
}
@Test
public void testEntityManagerCanBeUnwrappedToDeprecatedHibernateEntityManagerFactory() {
HibernateEntityManagerFactory hibernateEntityManagerFactory = entityManagerFactory.unwrap(
HibernateEntityManagerFactory.class
);
assertNotNull(
"Unwrapping to SPI class HibernateEntityManagerFactory should be ok",
hibernateEntityManagerFactory
);
}
@Test
public void testEntityManagerCanBeUnwrappedToHibernateEntityManagerFactory() {
org.hibernate.jpa.HibernateEntityManagerFactory hibernateEntityManagerFactory = entityManagerFactory.unwrap( org.hibernate.jpa.HibernateEntityManagerFactory.class );
assertNotNull(
"Unwrapping to SPI class HibernateEntityManagerFactory should be ok",
hibernateEntityManagerFactory
);
}
@Test
public void testEntityManagerCanBeUnwrappedToObject() {
Object object = entityManagerFactory.unwrap( Object.class );
assertNotNull( "Unwrapping to public super type Object should work", object );
}
@Test
public void testEntityManagerCanBeUnwrappedToSessionFactoryImpl() {
SessionFactoryImpl sessionFactory = entityManagerFactory.unwrap( SessionFactoryImpl.class );
assertNotNull(
"Unwrapping to SessionFactoryImpl should be ok",
sessionFactory
);
}
@Test
public void testEntityManagerCannotBeUnwrappedToUnrelatedType() {
try {
entityManagerFactory.unwrap( EntityManager.class );
fail( "It should not be possible to unwrap to unrelated type." );
}
catch ( PersistenceException e ) {
// ignore
}
}
}

View File

@ -0,0 +1,463 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.FlushModeType;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Environment;
import org.hibernate.jpa.AvailableSettings;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.hibernate.stat.Statistics;
import org.hibernate.testing.TestForIssue;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Gavin King
*/
public class EntityManagerTest extends BaseEntityManagerFunctionalTestCase {
@Override
public Class[] getAnnotatedClasses() {
return new Class[] {
Item.class,
Distributor.class,
Wallet.class
};
}
@SuppressWarnings( {"unchecked"})
protected void addConfigOptions(Map options) {
options.put( Environment.GENERATE_STATISTICS, "true" );
}
@Override
public Map<Class, String> getCachedClasses() {
Map<Class, String> result = new HashMap<Class, String>();
result.put( Item.class, "read-write" );
return result;
}
@Override
public Map<String, String> getCachedCollections() {
Map<String, String> result = new HashMap<String, String>();
result.put( Item.class.getName() + ".distributors", "read-write,"+Item.class.getName() + ".distributors" );
return result;
}
@Test
public void testEntityManager() {
Item item = new Item( "Mouse", "Micro$oft mouse" );
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( item );
assertTrue( em.contains( item ) );
em.getTransaction().commit();
assertTrue( em.contains( item ) );
em.getTransaction().begin();
Item item1 = ( Item ) em.createQuery( "select i from Item i where descr like 'M%'" ).getSingleResult();
assertNotNull( item1 );
assertSame( item, item1 );
item.setDescr( "Micro$oft wireless mouse" );
assertTrue( em.contains( item ) );
em.getTransaction().commit();
assertTrue( em.contains( item ) );
em.getTransaction().begin();
item1 = em.find( Item.class, "Mouse" );
assertSame( item, item1 );
em.getTransaction().commit();
assertTrue( em.contains( item ) );
item1 = em.find( Item.class, "Mouse" );
assertSame( item, item1 );
assertTrue( em.contains( item ) );
item1 = ( Item ) em.createQuery( "select i from Item i where descr like 'M%'" ).getSingleResult();
assertNotNull( item1 );
assertSame( item, item1 );
assertTrue( em.contains( item ) );
em.getTransaction().begin();
assertTrue( em.contains( item ) );
em.remove( item );
em.remove( item ); //Second should be no-op
em.getTransaction().commit();
em.close();
}
@Test
public void testConfiguration() throws Exception {
Item item = new Item( "Mouse", "Micro$oft mouse" );
Distributor res = new Distributor();
res.setName( "Bruce" );
item.setDistributors( new HashSet<Distributor>() );
item.getDistributors().add( res );
Statistics stats = ( ( HibernateEntityManagerFactory ) entityManagerFactory() ).getSessionFactory().getStatistics();
stats.clear();
stats.setStatisticsEnabled( true );
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( res );
em.persist( item );
assertTrue( em.contains( item ) );
em.getTransaction().commit();
em.close();
assertEquals( 1, stats.getSecondLevelCachePutCount() );
assertEquals( 0, stats.getSecondLevelCacheHitCount() );
em = getOrCreateEntityManager();
em.getTransaction().begin();
Item second = em.find( Item.class, item.getName() );
assertEquals( 1, second.getDistributors().size() );
assertEquals( 1, stats.getSecondLevelCacheHitCount() );
em.getTransaction().commit();
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
second = em.find( Item.class, item.getName() );
assertEquals( 1, second.getDistributors().size() );
assertEquals( 3, stats.getSecondLevelCacheHitCount() );
em.remove( second );
em.remove( second.getDistributors().iterator().next() );
em.getTransaction().commit();
em.close();
stats.clear();
stats.setStatisticsEnabled( false );
}
@Test
public void testContains() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Integer nonManagedObject = Integer.valueOf( 4 );
try {
em.contains( nonManagedObject );
fail( "Should have raised an exception" );
}
catch ( IllegalArgumentException iae ) {
//success
if ( em.getTransaction() != null ) {
em.getTransaction().rollback();
}
}
finally {
em.close();
}
em = getOrCreateEntityManager();
em.getTransaction().begin();
Item item = new Item();
item.setDescr( "Mine" );
item.setName( "Juggy" );
em.persist( item );
em.getTransaction().commit();
em.getTransaction().begin();
item = em.getReference( Item.class, item.getName() );
assertTrue( em.contains( item ) );
em.remove( item );
em.getTransaction().commit();
em.close();
}
@Test
public void testClear() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Wallet w = new Wallet();
w.setBrand( "Lacoste" );
w.setModel( "Minimic" );
w.setSerial( "0100202002" );
em.persist( w );
em.flush();
em.clear();
assertFalse( em.contains( w ) );
em.getTransaction().rollback();
em.close();
}
@Test
public void testFlushMode() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.setFlushMode( FlushModeType.COMMIT );
assertEquals( FlushModeType.COMMIT, em.getFlushMode() );
( (Session) em ).setFlushMode( FlushMode.ALWAYS );
assertEquals( em.getFlushMode(), FlushModeType.AUTO );
em.close();
}
@Test
public void testPersistNoneGenerator() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Wallet w = new Wallet();
w.setBrand( "Lacoste" );
w.setModel( "Minimic" );
w.setSerial( "0100202002" );
em.persist( w );
em.getTransaction().commit();
em.getTransaction().begin();
Wallet wallet = em.find( Wallet.class, w.getSerial() );
assertEquals( w.getBrand(), wallet.getBrand() );
em.remove( wallet );
em.getTransaction().commit();
em.close();
}
@Test
public void testSerializableException() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
try {
Query query = em.createQuery( "SELECT p FETCH JOIN p.distributors FROM Item p" );
query.getSingleResult();
}
catch ( IllegalArgumentException e ) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream( stream );
out.writeObject( e );
out.close();
byte[] serialized = stream.toByteArray();
stream.close();
ByteArrayInputStream byteIn = new ByteArrayInputStream( serialized );
ObjectInputStream in = new ObjectInputStream( byteIn );
IllegalArgumentException deserializedException = ( IllegalArgumentException ) in.readObject();
in.close();
byteIn.close();
assertNull( deserializedException.getCause().getCause() );
assertNull( e.getCause().getCause() );
}
em.getTransaction().rollback();
em.close();
Exception e = new HibernateException( "Exception", new NullPointerException( "NPE" ) );
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream( stream );
out.writeObject( e );
out.close();
byte[] serialized = stream.toByteArray();
stream.close();
ByteArrayInputStream byteIn = new ByteArrayInputStream( serialized );
ObjectInputStream in = new ObjectInputStream( byteIn );
HibernateException deserializedException = ( HibernateException ) in.readObject();
in.close();
byteIn.close();
assertNotNull( "Arbitrary exceptions nullified", deserializedException.getCause() );
assertNotNull( e.getCause() );
}
@Test
public void testIsOpen() throws Exception {
EntityManager em = getOrCreateEntityManager();
assertTrue( em.isOpen() );
em.getTransaction().begin();
assertTrue( em.isOpen() );
em.getTransaction().rollback();
em.close();
assertFalse( em.isOpen() );
}
@Test
@TestForIssue( jiraKey = "EJB-9" )
public void testGet() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Item item = em.getReference( Item.class, "nonexistentone" );
try {
item.getDescr();
em.getTransaction().commit();
fail( "Object with wrong id should have failed" );
}
catch ( EntityNotFoundException e ) {
//success
if ( em.getTransaction() != null ) {
em.getTransaction().rollback();
}
}
finally {
em.close();
}
}
@Test
public void testGetProperties() throws Exception {
EntityManager em = getOrCreateEntityManager();
Map<String, Object> properties = em.getProperties();
assertNotNull( properties );
try {
properties.put( "foo", "bar" );
fail();
}
catch ( UnsupportedOperationException e ) {
// success
}
assertTrue( properties.containsKey( AvailableSettings.FLUSH_MODE ) );
}
@Test
public void testSetProperty() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Wallet wallet = new Wallet();
wallet.setSerial( "000" );
em.persist( wallet );
em.getTransaction().commit();
em.clear();
assertEquals( em.getProperties().get( AvailableSettings.FLUSH_MODE ), "AUTO" );
assertNotNull(
"With default settings the entity should be persisted on commit.",
em.find( Wallet.class, wallet.getSerial() )
);
em.getTransaction().begin();
wallet = em.merge( wallet );
em.remove( wallet );
em.getTransaction().commit();
em.clear();
assertNull( "The entity should have been removed.", em.find( Wallet.class, wallet.getSerial() ) );
em.setProperty( "org.hibernate.flushMode", "MANUAL" +
"" );
em.getTransaction().begin();
wallet = new Wallet();
wallet.setSerial( "000" );
em.persist( wallet );
em.getTransaction().commit();
em.clear();
assertNull(
"With a flush mode of manual the entity should not have been persisted.",
em.find( Wallet.class, wallet.getSerial() )
);
assertEquals( "MANUAL", em.getProperties().get( AvailableSettings.FLUSH_MODE ) );
em.close();
}
@Test
public void testPersistExisting() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Wallet w = new Wallet();
w.setBrand( "Lacoste" );
w.setModel( "Minimic" );
w.setSerial( "0100202002" );
em.persist( w );
w = new Wallet();
w.setBrand( "Lacoste" );
w.setModel( "Minimic" );
w.setSerial( "0100202002" );
try {
em.persist( w );
}
catch ( EntityExistsException eee ) {
//success
if ( em.getTransaction() != null ) {
em.getTransaction().rollback();
}
em.close();
return;
}
try {
em.getTransaction().commit();
fail( "Should have raised an exception" );
}
catch ( PersistenceException pe ) {
}
finally {
em.close();
}
}
@Test
public void testFactoryClosed() throws Exception {
EntityManager em = createIsolatedEntityManager();
assertTrue( em.isOpen() );
assertTrue( em.getEntityManagerFactory().isOpen());
em.getEntityManagerFactory().close(); // closing the entity manager factory should close the EM
assertFalse(em.isOpen());
try {
em.close();
fail("closing entity manager that uses a closed session factory, must throw IllegalStateException");
}
catch( IllegalStateException expected) {
// success
}
}
@Test
public void testEntityNotFoundException() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Wallet w = new Wallet();
w.setBrand("Lacoste");
w.setModel("Minimic");
w.setSerial("0324");
em.persist(w);
Wallet wallet = em.find( Wallet.class, w.getSerial() );
em.createNativeQuery("delete from Wallet").executeUpdate();
try {
em.refresh(wallet);
} catch (EntityNotFoundException enfe) {
// success
if (em.getTransaction() != null) {
em.getTransaction().rollback();
}
em.close();
return;
}
try {
em.getTransaction().commit();
fail("Should have raised an EntityNotFoundException");
} catch (PersistenceException pe) {
} finally {
em.close();
}
}
}

View File

@ -0,0 +1,38 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test;
import java.io.Serializable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
/**
*
*/
@Entity
public class EntityWithCompositeId implements Serializable {
@EmbeddedId
private CompositeId id;
private String description;
public CompositeId getId() {
return id;
}
public void setId(CompositeId id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -0,0 +1,122 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityResult;
import javax.persistence.FieldResult;
import javax.persistence.Id;
import javax.persistence.LockModeType;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.QueryHint;
import javax.persistence.SqlResultSetMapping;
import org.hibernate.annotations.QueryHints;
/**
* @author Gavin King
*/
@Entity(name = "Item")
@SqlResultSetMapping(name = "getItem", entities =
@EntityResult(entityClass = Item.class, fields = {
@FieldResult(name = "name", column = "itemname"),
@FieldResult(name = "descr", column = "itemdescription")
})
)
@NamedNativeQueries({
@NamedNativeQuery(
name = "nativeItem1",
query = "select name as itemname, descr as itemdescription from Item",
resultSetMapping = "getItem"
),
@NamedNativeQuery(
name = "nativeItem2",
query = "select * from Item",
resultClass = Item.class
)
})
@NamedQueries({
@NamedQuery(
name = "itemJpaQueryWithLockModeAndHints",
query = "select i from Item i",
lockMode = LockModeType.PESSIMISTIC_WRITE,
hints = {
@QueryHint( name = QueryHints.TIMEOUT_JPA, value = "3000" ),
@QueryHint( name = QueryHints.CACHE_MODE, value = "ignore" ),
@QueryHint( name = QueryHints.CACHEABLE, value = "true" ),
@QueryHint( name = QueryHints.READ_ONLY, value = "true" ),
@QueryHint( name = QueryHints.COMMENT, value = "custom static comment" ),
@QueryHint( name = QueryHints.FETCH_SIZE, value = "512" ),
@QueryHint( name = QueryHints.FLUSH_MODE, value = "manual" )
}
),
@NamedQuery(name = "query-construct", query = "select new Item(i.name,i.descr) from Item i")
})
public class Item implements Serializable {
private String name;
private String descr;
private Integer intVal;
private Set<Distributor> distributors = new HashSet<Distributor>();
public Item() {
}
public Item(String name, String desc) {
this.name = name;
this.descr = desc;
}
@Column(length = 200)
public String getDescr() {
return descr;
}
public void setDescr(String desc) {
this.descr = desc;
}
@Id
@Column(length = 30)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getIntVal() {
return intVal;
}
public void setIntVal(Integer intVal) {
this.intVal = intVal;
}
@OneToMany
public Set<Distributor> getDistributors() {
return distributors;
}
public void setDistributors(Set<Distributor> distributors) {
this.distributors = distributors;
}
public void addDistributor(Distributor d) {
if ( distributors == null ) distributors = new HashSet();
distributors.add( d );
}
}

View File

@ -0,0 +1,63 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
// $Id$
package org.hibernate.jpa.test;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* @author Hardy Ferentschik
*/
@SuppressWarnings("serial")
@Entity
public class Kitten {
private Integer id;
private String name;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* Constructs a <code>String</code> with all attributes
* in name = value format.
*
* @return a <code>String</code> representation
* of this object.
*/
public String toString()
{
final String TAB = " ";
String retValue = "";
retValue = "Kitten ( "
+ super.toString() + TAB
+ "id = " + this.id + TAB
+ "name = " + this.name + TAB
+ " )";
return retValue;
}
}

View File

@ -0,0 +1,24 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test;
import java.util.Date;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
/**
* @author Emmanuel Bernard
*/
public class LastUpdateListener {
@PreUpdate
@PrePersist
public void setLastUpdate(Cat o) {
o.setLastUpdate( new Date() );
o.setManualVersion( o.getManualVersion() + 1 );
}
}

View File

@ -0,0 +1,21 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
/**
* @author Emmanuel Bernard
*/
public class MyNamingStrategy extends PhysicalNamingStrategyStandardImpl {
@Override
public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment jdbcEnvironment) {
return jdbcEnvironment.getIdentifierHelper().toIdentifier( "tbl_" + name.getText() );
}
}

View File

@ -0,0 +1,20 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test;
import org.hibernate.event.spi.PreInsertEvent;
import org.hibernate.event.spi.PreInsertEventListener;
/**
* @author Emmanuel Bernard
*/
public class NoOpListener implements PreInsertEventListener {
public boolean onPreInsert(PreInsertEvent event) {
return false;
}
}

View File

@ -0,0 +1,17 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test;
/**
* Attempts to serialize this class should cause a NotSerializableException error to be thrown.
*
* @author Scott Marlow
*/
public class NotSerializableClass {
}

View File

@ -0,0 +1,115 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.persistence.spi.PersistenceUnitTransactionType;
import javax.sql.DataSource;
import org.hibernate.bytecode.enhance.spi.EnhancementContext;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
/**
* @author Steve Ebersole
*/
public class PersistenceUnitDescriptorAdapter implements PersistenceUnitDescriptor {
private final String name = "persistenceUnitDescriptorAdapter@" + System.identityHashCode( this );
private Properties properties;
@Override
public String getName() {
return name;
}
@Override
public boolean isUseQuotedIdentifiers() {
return false;
}
@Override
public String getProviderClassName() {
return HibernatePersistenceProvider.class.getName();
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
return null;
}
@Override
public DataSource getJtaDataSource() {
return null;
}
@Override
public DataSource getNonJtaDataSource() {
return null;
}
@Override
public List<String> getMappingFileNames() {
return Collections.emptyList();
}
@Override
public List<URL> getJarFileUrls() {
return Collections.emptyList();
}
@Override
public URL getPersistenceUnitRootUrl() {
return null;
}
@Override
public List<String> getManagedClassNames() {
return Collections.emptyList();
}
@Override
public boolean isExcludeUnlistedClasses() {
return false;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return null;
}
@Override
public ValidationMode getValidationMode() {
return null;
}
@Override
public Properties getProperties() {
if ( properties == null ) {
properties = new Properties();
}
return properties;
}
@Override
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
@Override
public ClassLoader getTempClassLoader() {
return null;
}
@Override
public void pushClassTransformer(EnhancementContext enhancementContext) {
}
}

View File

@ -0,0 +1,100 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import javax.sql.DataSource;
import org.hibernate.jpa.HibernatePersistenceProvider;
/**
* Implementation of {@link PersistenceUnitInfo} for testing use.
*
* @author Steve Ebersole
*/
public class PersistenceUnitInfoAdapter implements PersistenceUnitInfo {
private final String name = "persistenceUnitInfoAdapter@" + System.identityHashCode( this );
private Properties properties;
public String getPersistenceUnitName() {
return name;
}
public String getPersistenceProviderClassName() {
return HibernatePersistenceProvider.class.getName();
}
public PersistenceUnitTransactionType getTransactionType() {
return null;
}
public DataSource getJtaDataSource() {
return null;
}
public DataSource getNonJtaDataSource() {
return null;
}
public List<String> getMappingFileNames() {
return Collections.emptyList();
}
public List<URL> getJarFileUrls() {
return Collections.emptyList();
}
public URL getPersistenceUnitRootUrl() {
return null;
}
public List<String> getManagedClassNames() {
return Collections.emptyList();
}
public boolean excludeUnlistedClasses() {
return false;
}
public SharedCacheMode getSharedCacheMode() {
return null;
}
public ValidationMode getValidationMode() {
return null;
}
public Properties getProperties() {
if ( properties == null ) {
properties = new Properties();
}
return properties;
}
public String getPersistenceXMLSchemaVersion() {
return null;
}
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
public void addTransformer(ClassTransformer transformer) {
}
public ClassLoader getNewTempClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
}

View File

@ -0,0 +1,35 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
/**
* @author Steve Ebersole
*/
public class SettingsGenerator {
public static Map generateSettings(Object... keysAndValues) {
final Map settings = new HashMap();
if ( keysAndValues != null ) {
if ( keysAndValues.length %2 != 0 ) {
Assert.fail( "Varargs to create settings should contain even number of entries" );
}
for ( int i = 0; i < keysAndValues.length; ) {
settings.put( keysAndValues[i], keysAndValues[i+1] );
i+=2;
}
}
return settings;
}
}

View File

@ -0,0 +1,49 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import static java.io.File.separatorChar;
/**
* @author Steve Ebersole
*/
public class TestHelper {
private static URL RESOLVED_TEST_ROOT_URL;
public static URL determineTestRootUrl() {
if ( RESOLVED_TEST_ROOT_URL == null ) {
RESOLVED_TEST_ROOT_URL = resolveRootUrl( TestHelper.class );
}
return RESOLVED_TEST_ROOT_URL;
}
public static URL resolveRootUrl(Class knownClass) {
final String knownClassFileName = '/' + knownClass.getName().replace( '.', separatorChar ) + ".class";
final URL knownClassFileUrl = TestHelper.class.getResource( knownClassFileName );
final String knownClassFileUrlString = knownClassFileUrl.toExternalForm();
// to start, strip off the class file name
String rootUrlString = knownClassFileUrlString.substring( 0, knownClassFileUrlString.lastIndexOf( separatorChar ) );
// then strip off each package dir
final String packageName = knownClass.getPackage().getName();
for ( String packageNamePart : packageName.split( "\\." ) ) {
rootUrlString = rootUrlString.substring( 0, rootUrlString.lastIndexOf( separatorChar ) );
}
try {
return new URL( rootUrlString );
}
catch (MalformedURLException e) {
throw new RuntimeException( "Could not convert class base url as string to URL ref", e );
}
}
}

View File

@ -0,0 +1,34 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test;
import javax.persistence.EntityManagerFactory;
import java.util.Map;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor;
/**
* @author Steve Ebersole
*/
public class TestingEntityManagerFactoryGenerator {
public static EntityManagerFactory generateEntityManagerFactory(Object... settings) {
return generateEntityManagerFactory( SettingsGenerator.generateSettings( settings ) );
}
public static EntityManagerFactory generateEntityManagerFactory(Map settings) {
return generateEntityManagerFactory( new PersistenceUnitDescriptorAdapter(), settings );
}
public static EntityManagerFactory generateEntityManagerFactory(PersistenceUnitDescriptor descriptor, Object... settings) {
return generateEntityManagerFactory( descriptor, SettingsGenerator.generateSettings( settings ) );
}
public static EntityManagerFactory generateEntityManagerFactory(PersistenceUnitDescriptor descriptor, Map settings) {
return Bootstrap.getEntityManagerFactoryBuilder( descriptor, settings ).build();
}
}

View File

@ -0,0 +1,57 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Wallet implements Serializable {
private String serial;
private String model;
private Date marketEntrance;
private String brand;
@Id
public String getSerial() {
return serial;
}
public void setSerial(String serial) {
this.serial = serial;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Date getMarketEntrance() {
return marketEntrance;
}
public void setMarketEntrance(Date marketEntrance) {
this.marketEntrance = marketEntrance;
}
}

View File

@ -0,0 +1,77 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.association;
import javax.persistence.EntityManager;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.junit.Test;
/**
* @author Emmanuel Bernard
*/
public class AssociationTest extends BaseEntityManagerFunctionalTestCase {
@Test
public void testBidirOneToOne() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
String id = "10";
Incident i = em.find( Incident.class, id );
if ( i == null ) {
i = new Incident( id );
IncidentStatus ist = new IncidentStatus( id );
i.setIncidentStatus( ist );
ist.setIncident( i );
em.persist( i );
}
em.getTransaction().commit();
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
em.remove( em.find(Incident.class, id) );
em.getTransaction().commit();
em.close();
}
@Test
public void testMergeAndBidirOneToOne() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Oven oven = new Oven();
Kitchen kitchen = new Kitchen();
em.persist( oven );
em.persist( kitchen );
kitchen.setOven( oven );
oven.setKitchen( kitchen );
em.getTransaction().commit();
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
oven = em.merge( oven );
em.getTransaction().commit();
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
em.remove( em.find( Oven.class, oven.getId() ) );
em.getTransaction().commit();
em.close();
}
@Override
public Class[] getAnnotatedClasses() {
return new Class[]{
Incident.class,
IncidentStatus.class,
Kitchen.class,
Oven.class
};
}
}

View File

@ -0,0 +1,45 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.association;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Incident {
@Id
String id;
@OneToOne(cascade = CascadeType.ALL)
IncidentStatus incidentStatus;
public Incident() {
}
public Incident(String id) {
this.id = id;
}
public IncidentStatus getIncidentStatus() {
return incidentStatus;
}
public void setIncidentStatus(IncidentStatus incidentStatus) {
this.incidentStatus = incidentStatus;
}
@Override
public String toString() {
return "Incident: " + id + " " + incidentStatus;
}
}

View File

@ -0,0 +1,44 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.association;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
/**
* @author Emmanuel Bernard
*/
@Entity
public class IncidentStatus {
@Id
String id;
@OneToOne(mappedBy = "incidentStatus")
Incident incident;
public IncidentStatus() {
}
public IncidentStatus(String id) {
this.id = id;
}
public Incident getIncident() {
return incident;
}
public void setIncident(Incident incident) {
this.incident = incident;
}
@Override
public String toString() {
return "IncidentStatus " + id;
}
}

View File

@ -0,0 +1,41 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.association;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Kitchen {
@Id @GeneratedValue
private Long id;
@OneToOne(mappedBy = "kitchen")
private Oven oven;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Oven getOven() {
return oven;
}
public void setOven(Oven oven) {
this.oven = oven;
}
}

View File

@ -0,0 +1,44 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.association;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Oven {
@Id @GeneratedValue
private Long id;
@OneToOne(fetch= FetchType.LAZY)
@JoinColumn
private Kitchen kitchen;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Kitchen getKitchen() {
return kitchen;
}
public void setKitchen(Kitchen kitchen) {
this.kitchen = kitchen;
}
}

View File

@ -0,0 +1,83 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.beanvalidation;
import java.math.BigDecimal;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.RollbackException;
import javax.validation.ConstraintViolationException;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.beanvalidation.ValidationMode;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Emmanuel Bernard
*/
public class BeanValidationTest extends BaseEntityManagerFunctionalTestCase {
@Override
protected void addMappings(Map settings) {
settings.put( AvailableSettings.JPA_VALIDATION_MODE, ValidationMode.AUTO );
}
@Test
public void testBeanValidationIntegrationOnFlush() {
CupHolder ch = new CupHolder();
ch.setRadius( new BigDecimal( "12" ) );
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
try {
em.persist( ch );
em.flush();
fail("invalid object should not be persisted");
}
catch ( ConstraintViolationException e ) {
assertEquals( 1, e.getConstraintViolations().size() );
}
assertTrue(
"A constraint violation exception should mark the transaction for rollback",
em.getTransaction().getRollbackOnly()
);
em.getTransaction().rollback();
em.close();
}
@Test
public void testBeanValidationIntegrationOnCommit() {
CupHolder ch = new CupHolder();
ch.setRadius( new BigDecimal( "9" ) );
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( ch );
em.flush();
try {
ch.setRadius( new BigDecimal( "12" ) );
em.getTransaction().commit();
fail("invalid object should not be persisted");
}
catch ( RollbackException e ) {
final Throwable cve = e.getCause();
assertTrue( cve instanceof ConstraintViolationException );
assertEquals( 1, ( (ConstraintViolationException) cve ).getConstraintViolations().size() );
}
em.close();
}
@Override
public Class[] getAnnotatedClasses() {
return new Class[] {
CupHolder.class
};
}
}

View File

@ -0,0 +1,43 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.beanvalidation;
import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
/**
* @author Emmanuel Bernard
*/
@Entity
public class CupHolder {
@Id
@GeneratedValue
//@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
private BigDecimal radius;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Max( value = 10, message = "Radius way out")
@NotNull
public BigDecimal getRadius() {
return radius;
}
public void setRadius(BigDecimal radius) {
this.radius = radius;
}
}

View File

@ -0,0 +1,71 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.beanvalidation;
import java.net.URL;
import java.util.Collections;
import javax.persistence.EntityManagerFactory;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import org.hibernate.jpa.AvailableSettings;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder;
import org.hibernate.jpa.test.jee.OrmVersionTest;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertSame;
/**
* Test injection of ValidatorFactory using WF/Hibernate 2-phase boot process
*
* @author Steve Ebersole
*/
public class ValidatorFactory2PhaseInjectionTest extends BaseUnitTestCase {
private ValidatorFactory vf;
@Before
public void before() {
vf = Validation.byDefaultProvider().configure().buildValidatorFactory();
}
@After
public void after() {
if ( vf != null ) {
vf.close();
}
}
@Test
public void testInjectionAvailabilityFromEmf() {
EntityManagerFactoryBuilder emfb = Bootstrap.getEntityManagerFactoryBuilder(
new OrmVersionTest.PersistenceUnitInfoImpl( "my-test" ) {
@Override
public URL getPersistenceUnitRootUrl() {
// just get any known url...
return HibernatePersistenceProvider.class.getResource( "/org/hibernate/jpa/persistence_1_0.xsd" );
}
},
Collections.emptyMap()
);
emfb.withValidatorFactory( vf );
EntityManagerFactory emf = emfb.build();
try {
assertSame( vf, emf.getProperties().get( AvailableSettings.VALIDATION_FACTORY ) );
}
finally {
emf.close();
}
}
}

View File

@ -0,0 +1,40 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.boot;
import javax.persistence.EntityManagerFactory;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.jpa.test.jee.OrmVersionTest;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.junit.Test;
/**
* @author Steve Ebersole
*/
public class NewBootProcessTest {
@Test
public void basicNewBootProcessTest() {
Map settings = new HashMap();
HibernatePersistenceProvider persistenceProvider = new HibernatePersistenceProvider();
final EntityManagerFactory emf = persistenceProvider.createContainerEntityManagerFactory(
new OrmVersionTest.PersistenceUnitInfoImpl( "my-test" ) {
@Override
public URL getPersistenceUnitRootUrl() {
// just get any known url...
return HibernatePersistenceProvider.class.getResource( "/org/hibernate/jpa/persistence_1_0.xsd" );
}
},
settings
);
emf.close();
}
}

View File

@ -0,0 +1,153 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cacheable.annotation;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.persistence.SharedCacheMode;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.cache.internal.NoCachingRegionFactory;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.Environment;
import org.hibernate.jpa.AvailableSettings;
import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.jpa.test.PersistenceUnitInfoAdapter;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.testing.cache.CachingRegionFactory;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/**
* this is hacky transient step until EMF building is integrated with metamodel
*
* @author Steve Ebersole
*/
public class ConfigurationTest extends BaseUnitTestCase {
private EntityManagerFactory emf;
@After
public void tearDown(){
if(emf != null){
emf.close();
}
}
@Test
public void testSharedCacheModeNone() {
MetadataImplementor metadata = buildMetadata( SharedCacheMode.NONE );
PersistentClass pc = metadata.getEntityBinding( ExplicitlyCacheableEntity.class.getName() );
assertNull( pc.getCacheConcurrencyStrategy() );
pc = metadata.getEntityBinding( ExplicitlyNonCacheableEntity.class.getName() );
assertNull( pc.getCacheConcurrencyStrategy() );
pc = metadata.getEntityBinding( NoCacheableAnnotationEntity.class.getName() );
assertNull( pc.getCacheConcurrencyStrategy() );
}
@Test
public void testSharedCacheModeUnspecified() {
MetadataImplementor metadata = buildMetadata( SharedCacheMode.UNSPECIFIED );
PersistentClass pc = metadata.getEntityBinding( ExplicitlyCacheableEntity.class.getName() );
assertNull( pc.getCacheConcurrencyStrategy() );
pc = metadata.getEntityBinding( ExplicitlyNonCacheableEntity.class.getName() );
assertNull( pc.getCacheConcurrencyStrategy() );
pc = metadata.getEntityBinding( NoCacheableAnnotationEntity.class.getName() );
assertNull( pc.getCacheConcurrencyStrategy() );
}
@Test
public void testSharedCacheModeAll() {
MetadataImplementor metadata = buildMetadata( SharedCacheMode.ALL );
PersistentClass pc = metadata.getEntityBinding( ExplicitlyCacheableEntity.class.getName() );
assertNotNull( pc.getCacheConcurrencyStrategy() );
pc = metadata.getEntityBinding( ExplicitlyNonCacheableEntity.class.getName() );
assertNotNull( pc.getCacheConcurrencyStrategy() );
pc = metadata.getEntityBinding( NoCacheableAnnotationEntity.class.getName() );
assertNotNull( pc.getCacheConcurrencyStrategy() );
}
@Test
public void testSharedCacheModeEnable() {
MetadataImplementor metadata = buildMetadata( SharedCacheMode.ENABLE_SELECTIVE );
PersistentClass pc = metadata.getEntityBinding( ExplicitlyCacheableEntity.class.getName() );
assertNotNull( pc.getCacheConcurrencyStrategy() );
pc = metadata.getEntityBinding( ExplicitlyNonCacheableEntity.class.getName() );
assertNull( pc.getCacheConcurrencyStrategy() );
pc = metadata.getEntityBinding( NoCacheableAnnotationEntity.class.getName() );
assertNull( pc.getCacheConcurrencyStrategy() );
}
@Test
public void testSharedCacheModeDisable() {
MetadataImplementor metadata = buildMetadata( SharedCacheMode.DISABLE_SELECTIVE );
PersistentClass pc = metadata.getEntityBinding( ExplicitlyCacheableEntity.class.getName() );
assertNotNull( pc.getCacheConcurrencyStrategy() );
pc = metadata.getEntityBinding( ExplicitlyNonCacheableEntity.class.getName() );
assertNull( pc.getCacheConcurrencyStrategy() );
pc = metadata.getEntityBinding( NoCacheableAnnotationEntity.class.getName() );
assertNotNull( pc.getCacheConcurrencyStrategy() );
}
@SuppressWarnings("unchecked")
private MetadataImplementor buildMetadata(SharedCacheMode mode) {
Map settings = new HashMap();
settings.put( AvailableSettings.SHARED_CACHE_MODE, mode );
settings.put( Environment.CACHE_REGION_FACTORY, CustomRegionFactory.class.getName() );
settings.put(
AvailableSettings.LOADED_CLASSES,
Arrays.asList(
ExplicitlyCacheableEntity.class,
ExplicitlyNonCacheableEntity.class,
NoCacheableAnnotationEntity.class
)
);
PersistenceUnitInfoAdapter adapter = new PersistenceUnitInfoAdapter();
final EntityManagerFactoryBuilderImpl emfb = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder(
adapter,
settings
);
emf = emfb.build();
return emfb.getMetadata();
}
public static class CustomRegionFactory extends CachingRegionFactory {
public CustomRegionFactory() {
}
@Override
public AccessType getDefaultAccessType() {
return AccessType.READ_WRITE;
}
}
}

View File

@ -0,0 +1,39 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cacheable.annotation;
import javax.persistence.Cacheable;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* TODO : javadoc
*
* @author Steve Ebersole
*/
@Entity
@Cacheable
public class ExplicitlyCacheableEntity {
private Long id;
private String name;
@Id
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,39 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cacheable.annotation;
import javax.persistence.Cacheable;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* TODO : javadoc
*
* @author Steve Ebersole
*/
@Entity
@Cacheable(false)
public class ExplicitlyNonCacheableEntity {
private Long id;
private String name;
@Id
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,37 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cacheable.annotation;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* TODO : javadoc
*
* @author Steve Ebersole
*/
@Entity
public class NoCacheableAnnotationEntity {
private Long id;
private String name;
@Id
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,62 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cacheable.api;
import javax.persistence.EntityManager;
import javax.persistence.SharedCacheMode;
import java.util.Map;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.junit.Test;
import org.hibernate.testing.cache.CachingRegionFactory;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Steve Ebersole
*/
public class JpaCacheApiUsageTest extends BaseEntityManagerFunctionalTestCase {
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class[] { Order.class };
}
@Override
@SuppressWarnings("unchecked")
protected void addConfigOptions(Map options) {
// options.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, "true" );
options.put( AvailableSettings.CACHE_REGION_FACTORY, CachingRegionFactory.class.getName() );
// options.put( AvailableSettings.DEFAULT_CACHE_CONCURRENCY_STRATEGY, "read-write" );
options.put( org.hibernate.jpa.AvailableSettings.SHARED_CACHE_MODE, SharedCacheMode.ALL );
}
@Test
public void testEviction() {
// first create an Order
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( new Order( 1, 500 ) );
em.getTransaction().commit();
em.close();
assertTrue( entityManagerFactory().getCache().contains( Order.class, 1 ) );
em = getOrCreateEntityManager();
em.getTransaction().begin();
assertTrue( entityManagerFactory().getCache().contains( Order.class, 1 ) );
em.createQuery( "delete Order" ).executeUpdate();
em.getTransaction().commit();
em.close();
assertFalse( entityManagerFactory().getCache().contains( Order.class, 1 ) );
}
}

View File

@ -0,0 +1,56 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cacheable.api;
import javax.persistence.Cacheable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author Steve Ebersole
*/
@Entity
@Cacheable( value = true )
@Table( name = "T_ORDER" )
public class Order {
private int id;
private int total;
public Order() {
}
public Order(int total) {
this.total = total;
}
public Order(int id, int total) {
this.id = id;
this.total = total;
}
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public String toString() {
return "Order id=" + getId() + ", total=" + getTotal();
}
}

View File

@ -0,0 +1,101 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cacheable.cachemodes;
import javax.persistence.CacheRetrieveMode;
import javax.persistence.CacheStoreMode;
import javax.persistence.EntityManager;
import org.hibernate.CacheMode;
import org.hibernate.Session;
import org.hibernate.jpa.AvailableSettings;
import org.hibernate.jpa.HibernateEntityManager;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author Steve Ebersole
*/
public class SharedCacheModesTest extends BaseEntityManagerFunctionalTestCase {
@Override
public Class[] getAnnotatedClasses() {
return new Class[] { SimpleEntity.class };
}
@Test
public void testEntityManagerCacheModes() {
EntityManager em;
Session session;
em = getOrCreateEntityManager();
session = ( (HibernateEntityManager) em ).getSession();
// defaults...
assertEquals( CacheStoreMode.USE, em.getProperties().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) );
assertEquals( CacheRetrieveMode.USE, em.getProperties().get( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE ) );
assertEquals( CacheMode.NORMAL, session.getCacheMode() );
// overrides...
em.setProperty( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.REFRESH );
assertEquals( CacheStoreMode.REFRESH, em.getProperties().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) );
assertEquals( CacheMode.REFRESH, session.getCacheMode() );
em.setProperty( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.BYPASS );
assertEquals( CacheStoreMode.BYPASS, em.getProperties().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) );
assertEquals( CacheMode.GET, session.getCacheMode() );
em.setProperty( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE, CacheRetrieveMode.BYPASS );
assertEquals( CacheRetrieveMode.BYPASS, em.getProperties().get( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE ) );
assertEquals( CacheMode.IGNORE, session.getCacheMode() );
em.setProperty( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.USE );
assertEquals( CacheStoreMode.USE, em.getProperties().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) );
assertEquals( CacheMode.PUT, session.getCacheMode() );
em.setProperty( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.REFRESH );
assertEquals( CacheStoreMode.REFRESH, em.getProperties().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) );
assertEquals( CacheMode.REFRESH, session.getCacheMode() );
}
@Test
public void testQueryCacheModes() {
EntityManager em = getOrCreateEntityManager();
org.hibernate.query.Query query = em.createQuery( "from SimpleEntity" ).unwrap( org.hibernate.query.Query.class );
query.setHint( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.USE );
assertEquals( CacheStoreMode.USE, query.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) );
assertEquals( CacheMode.NORMAL, query.getCacheMode() );
query.setHint( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.BYPASS );
assertEquals( CacheStoreMode.BYPASS, query.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) );
assertEquals( CacheMode.GET, query.getCacheMode() );
query.setHint( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.REFRESH );
assertEquals( CacheStoreMode.REFRESH, query.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) );
assertEquals( CacheMode.REFRESH, query.getCacheMode() );
query.setHint( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE, CacheRetrieveMode.BYPASS );
assertEquals( CacheRetrieveMode.BYPASS, query.getHints().get( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE ) );
assertEquals( CacheStoreMode.REFRESH, query.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) );
assertEquals( CacheMode.REFRESH, query.getCacheMode() );
query.setHint( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.BYPASS );
assertEquals( CacheRetrieveMode.BYPASS, query.getHints().get( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE ) );
assertEquals( CacheStoreMode.BYPASS, query.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) );
assertEquals( CacheMode.IGNORE, query.getCacheMode() );
query.setHint( AvailableSettings.SHARED_CACHE_STORE_MODE, CacheStoreMode.USE );
assertEquals( CacheRetrieveMode.BYPASS, query.getHints().get( AvailableSettings.SHARED_CACHE_RETRIEVE_MODE ) );
assertEquals( CacheStoreMode.USE, query.getHints().get( AvailableSettings.SHARED_CACHE_STORE_MODE ) );
assertEquals( CacheMode.PUT, query.getCacheMode() );
}
}

View File

@ -0,0 +1,37 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cacheable.cachemodes;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* TODO : javadoc
*
* @author Steve Ebersole
*/
@Entity
public class SimpleEntity {
private Long id;
private String name;
@Id
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,104 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.callbacks;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import org.junit.Test;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Emmanuel Bernard
*/
public class CallbackAndDirtyTest extends BaseEntityManagerFunctionalTestCase {
@Test
public void testDirtyButNotDirty() throws Exception {
EntityManager manager = getOrCreateEntityManager();
manager.getTransaction().begin();
Employee mark = new Employee();
mark.setName( "Mark" );
mark.setTitle( "internal sales" );
mark.setSex( 'M' );
mark.setAddress( "buckhead" );
mark.setZip( "30305" );
mark.setCountry( "USA" );
Customer joe = new Customer();
joe.setName( "Joe" );
joe.setSex( 'M' );
joe.setAddress( "San Francisco" );
joe.setZip( "XXXXX" );
joe.setCountry( "USA" );
joe.setComments( "Very demanding" );
joe.setSalesperson( mark );
Person yomomma = new Person();
yomomma.setName( "mum" );
yomomma.setSex( 'F' );
manager.persist( mark );
manager.persist( joe );
manager.persist( yomomma );
long[] ids = {mark.getId(), joe.getId(), yomomma.getId()};
manager.getTransaction().commit();
manager.getTransaction().begin();
assertEquals(
manager.createQuery( "select p.address, p.name from Person p order by p.name" ).getResultList().size(),
3
);
assertEquals( manager.createQuery( "select p from Person p where p.class = Customer" ).getResultList().size(), 1 );
manager.getTransaction().commit();
manager.getTransaction().begin();
List customers = manager.createQuery( "select c from Customer c left join fetch c.salesperson" ).getResultList();
for ( Iterator iter = customers.iterator(); iter.hasNext() ; ) {
Customer c = (Customer) iter.next();
assertEquals( c.getSalesperson().getName(), "Mark" );
}
assertEquals( customers.size(), 1 );
manager.getTransaction().commit();
manager.getTransaction().begin();
customers = manager.createQuery( "select c from Customer c" ).getResultList();
for ( Iterator iter = customers.iterator(); iter.hasNext() ; ) {
Customer c = (Customer) iter.next();
assertEquals( c.getSalesperson().getName(), "Mark" );
}
assertEquals( customers.size(), 1 );
manager.getTransaction().commit();
manager.getTransaction().begin();
mark = manager.find( Employee.class, Long.valueOf( ids[0] ) );
joe = manager.find( Customer.class, Long.valueOf( ids[1] ) );
yomomma = manager.find( Person.class, Long.valueOf( ids[2] ) );
mark.setZip( "30306" );
assertEquals( 1, manager.createQuery( "select p from Person p where p.zip = '30306'" ).getResultList().size() );
manager.remove( mark );
manager.remove( joe );
manager.remove( yomomma );
assertTrue( manager.createQuery( "select p from Person p" ).getResultList().isEmpty() );
manager.getTransaction().commit();
manager.close();
}
@Override
public Class[] getAnnotatedClasses() {
return new Class[]{
Customer.class,
Employee.class,
Person.class
};
}
}

View File

@ -0,0 +1,257 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.callbacks;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import org.junit.Test;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.jpa.test.Cat;
import org.hibernate.jpa.test.Kitten;
import org.hibernate.testing.FailureExpected;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Emmanuel Bernard
*/
@SuppressWarnings("unchecked")
public class CallbacksTest extends BaseEntityManagerFunctionalTestCase {
@Test
public void testCallbackMethod() throws Exception {
EntityManager em = getOrCreateEntityManager();
Cat c = new Cat();
c.setName( "Kitty" );
c.setDateOfBirth( new Date( 90, 11, 15 ) );
em.getTransaction().begin();
em.persist( c );
em.getTransaction().commit();
em.clear();
em.getTransaction().begin();
c = em.find( Cat.class, c.getId() );
assertFalse( c.getAge() == 0 );
c.setName( "Tomcat" ); //update this entity
em.getTransaction().commit();
em.clear();
em.getTransaction().begin();
c = em.find( Cat.class, c.getId() );
assertEquals( "Tomcat", c.getName() );
em.getTransaction().commit();
em.close();
}
@Test
public void testEntityListener() throws Exception {
EntityManager em = getOrCreateEntityManager();
Cat c = new Cat();
c.setName( "Kitty" );
c.setLength( 12 );
c.setDateOfBirth( new Date( 90, 11, 15 ) );
em.getTransaction().begin();
int previousVersion = c.getManualVersion();
em.persist( c );
em.getTransaction().commit();
em.getTransaction().begin();
c = em.find( Cat.class, c.getId() );
assertNotNull( c.getLastUpdate() );
assertTrue( previousVersion < c.getManualVersion() );
assertEquals( 12, c.getLength() );
previousVersion = c.getManualVersion();
c.setName( "new name" );
em.getTransaction().commit();
em.getTransaction().begin();
c = em.find( Cat.class, c.getId() );
assertTrue( previousVersion < c.getManualVersion() );
em.getTransaction().commit();
em.close();
}
@Test
public void testPostPersist() throws Exception {
EntityManager em = getOrCreateEntityManager();
Cat c = new Cat();
em.getTransaction().begin();
c.setLength( 23 );
c.setAge( 2 );
c.setName( "Beetle" );
c.setDateOfBirth( new Date() );
em.persist( c );
em.getTransaction().commit();
em.close();
List ids = Cat.getIdList();
Object id = Cat.getIdList().get( ids.size() - 1 );
assertNotNull( id );
}
//Not a test since the spec did not make the proper change on listeners
public void listenerAnnotation() throws Exception {
EntityManager em = getOrCreateEntityManager();
Translation tl = new Translation();
em.getTransaction().begin();
tl.setInto( "France" );
em.persist( tl );
tl = new Translation();
tl.setInto( "Bimboland" );
try {
em.persist( tl );
em.flush();
fail( "Annotations annotated by a listener not used" );
}
catch (IllegalArgumentException e) {
//success
}
finally {
em.getTransaction().rollback();
em.close();
}
}
@Test
public void testPrePersistOnCascade() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Television tv = new Television();
RemoteControl rc = new RemoteControl();
em.persist( tv );
em.flush();
tv.setControl( rc );
tv.init();
em.flush();
assertNotNull( rc.getCreationDate() );
em.getTransaction().rollback();
em.close();
}
@Test
public void testCallBackListenersHierarchy() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Television tv = new Television();
em.persist( tv );
tv.setName( "Myaio" );
tv.init();
em.flush();
assertEquals( 1, tv.counter );
em.getTransaction().rollback();
em.close();
assertEquals( 5, tv.communication );
assertTrue( tv.isLast );
}
@Test
public void testException() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Rythm r = new Rythm();
try {
em.persist( r );
em.flush();
fail("should have raised an ArythmeticException:");
}
catch (ArithmeticException e) {
//success
}
catch( Exception e ) {
fail("should have raised an ArythmeticException:" + e.getClass() );
}
em.getTransaction().rollback();
em.close();
}
@Test
public void testIdNullSetByPrePersist() throws Exception {
Plant plant = new Plant();
plant.setName( "Origuna plantula gigantic" );
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( plant );
em.flush();
em.getTransaction().rollback();
em.close();
}
@Test
@FailureExpected(message = "collection change does not trigger an event", jiraKey = "EJB-288")
public void testPostUpdateCollection() throws Exception {
// create a cat
EntityManager em = getOrCreateEntityManager();
Cat cat = new Cat();
em.getTransaction().begin();
cat.setLength( 23 );
cat.setAge( 2 );
cat.setName( "Beetle" );
cat.setDateOfBirth( new Date() );
em.persist( cat );
em.getTransaction().commit();
// assert it is persisted
List ids = Cat.getIdList();
Object id = Cat.getIdList().get( ids.size() - 1 );
assertNotNull( id );
// add a kitten to the cat - triggers PostCollectionRecreateEvent
int postVersion = Cat.postVersion;
em.getTransaction().begin();
Kitten kitty = new Kitten();
kitty.setName("kitty");
List kittens = new ArrayList<Kitten>();
kittens.add(kitty);
cat.setKittens(kittens);
em.getTransaction().commit();
assertEquals("Post version should have been incremented.", postVersion + 1, Cat.postVersion);
// add another kitten - triggers PostCollectionUpdateEvent.
postVersion = Cat.postVersion;
em.getTransaction().begin();
Kitten tom = new Kitten();
tom.setName("Tom");
cat.getKittens().add(tom);
em.getTransaction().commit();
assertEquals("Post version should have been incremented.", postVersion + 1, Cat.postVersion);
// delete a kitty - triggers PostCollectionUpdateEvent
postVersion = Cat.postVersion;
em.getTransaction().begin();
cat.getKittens().remove(tom);
em.getTransaction().commit();
assertEquals("Post version should have been incremented.", postVersion + 1, Cat.postVersion);
// delete and recreate kittens - triggers PostCollectionRemoveEvent and PostCollectionRecreateEvent)
postVersion = Cat.postVersion;
em.getTransaction().begin();
cat.setKittens(new ArrayList<Kitten>());
em.getTransaction().commit();
assertEquals("Post version should have been incremented.", postVersion + 2, Cat.postVersion);
em.close();
}
@Override
public Class[] getAnnotatedClasses() {
return new Class[]{
Cat.class,
Translation.class,
Television.class,
RemoteControl.class,
Rythm.class,
Plant.class,
Kitten.class
};
}
}

View File

@ -0,0 +1,28 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.callbacks;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
/**
* @author Emmanuel Bernard
*/
@MappedSuperclass
@EntityListeners(IncreaseListener.class)
public class CommunicationSystem {
public int communication = 0;
public boolean isFirst = true;
public boolean isLast;
public void init() {
communication = 0;
isFirst = true;
isLast = false;
}
}

View File

@ -0,0 +1,23 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.callbacks;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.persistence.EntityListeners;
/**
* @author Emmanuel Bernard
*/
@EntityListeners(CountryNameCheckerListener.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface CountryChecker {
}

View File

@ -0,0 +1,36 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.callbacks;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
/**
* @author Emmanuel Bernard
*/
public class CountryNameCheckerListener {
private List<String> countries = new ArrayList<String>();
{
countries.add( "France" );
countries.add( "Netherland" );
}
@PrePersist
@PreUpdate
public void testCountryName(Object object) {
if ( object instanceof Translation ) {
Translation tr = (Translation) object;
if ( ! countries.contains( tr.getInto() ) ) {
throw new IllegalArgumentException( "Not a country name: " + tr.getInto() );
}
}
}
}

View File

@ -0,0 +1,44 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.callbacks;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/**
* @author Emmanuel Bernard
*/
@Entity
@Table(name = "CUSTOMER_TABLE")
@Inheritance(strategy = InheritanceType.JOINED)
public class Customer extends Person {
private Employee salesperson;
private String comments;
@OneToOne
@JoinColumn(name = "salesperson")
public Employee getSalesperson() {
return salesperson;
}
public void setSalesperson(Employee salesperson) {
this.salesperson = salesperson;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}

View File

@ -0,0 +1,70 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.callbacks;
import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/**
* @author Emmanuel Bernard
*/
@Entity
@Table(name = "EMPLOYEE_TABLE")
@Inheritance(strategy = InheritanceType.JOINED)
public class Employee extends Person {
private String title;
private BigDecimal salary;
private Employee manager;
/**
* @return Returns the title.
*/
public String getTitle() {
return title;
}
/**
* @param title The title to set.
*/
public void setTitle(String title) {
this.title = title;
}
@OneToOne
@JoinColumn(name = "manager")
public Employee getManager() {
return manager;
}
/**
* @param manager The manager to set.
*/
public void setManager(Employee manager) {
this.manager = manager;
}
/**
* @return Returns the salary.
*/
public BigDecimal getSalary() {
return salary;
}
/**
* @param salary The salary to set.
*/
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
}

View File

@ -0,0 +1,20 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.callbacks;
import javax.persistence.PrePersist;
/**
* @author Emmanuel Bernard
*/
public class ExceptionListener {
@PrePersist
public void raiseException(Object e) {
throw new ArithmeticException( "1/0 impossible" );
}
}

View File

@ -0,0 +1,23 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.callbacks;
import javax.persistence.PreUpdate;
/**
* @author Emmanuel Bernard
*/
public class FirstOneListener {
@PreUpdate
public void firstOne(CommunicationSystem object) {
if ( !object.isFirst ) throw new IllegalStateException();
object.isFirst = true;
object.isLast = false;
object.communication++;
}
}

View File

@ -0,0 +1,22 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.callbacks;
import javax.persistence.PreUpdate;
/**
* @author Emmanuel Bernard
*/
public class IncreaseListener {
@PreUpdate
public void increate(CommunicationSystem object) {
object.communication++;
object.isFirst = false;
object.isLast = false;
}
}

View File

@ -0,0 +1,80 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.callbacks;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
/**
* @author Emmanuel Bernard
*/
@Entity
@Table(name = "PERSON_TABLE")
@Inheritance(strategy = InheritanceType.JOINED)
public class Person {
private long id;
private String name;
private String address;
private String zip;
private String country;
private char sex;
@Id
@GeneratedValue
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String identity) {
this.name = identity;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

View File

@ -0,0 +1,49 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.callbacks;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PrePersist;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Plant {
@Id
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@PrePersist
private void defineId() {
//some (stupid) id generation
if ( name.length() > 5 ) {
setId( name.substring( 0, 5 ) );
}
else {
setId( name );
}
}
}

View File

@ -0,0 +1,51 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.callbacks;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* @author Emmanuel Bernard
*/
@Entity
public class RemoteControl {
private Integer id;
private Date creationDate;
@Basic
@Temporal(TemporalType.TIMESTAMP)
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@PrePersist
private void init() {
creationDate = new Date();
}
}

View File

@ -0,0 +1,30 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.callbacks;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* @author Emmanuel Bernard
*/
@Entity
@EntityListeners(ExceptionListener.class)
public class Rythm {
@Id @GeneratedValue private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}

View File

@ -0,0 +1,70 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.callbacks;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
/**
* @author Emmanuel Bernard
*/
@Entity
@EntityListeners({IncreaseListener.class})
public class Television extends VideoSystem {
private Integer id;
private RemoteControl control;
private String name;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@OneToOne(cascade = CascadeType.ALL)
public RemoteControl getControl() {
return control;
}
public void setControl(RemoteControl control) {
this.control = control;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@PreUpdate
public void isLast() {
if ( isLast ) throw new IllegalStateException();
isFirst = false;
isLast = true;
communication++;
}
@PrePersist
public void prepareEntity() {
//override a super method annotated with the same
// event for it not to be called
counter++;
}
}

View File

@ -0,0 +1,44 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.callbacks;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author Emmanuel Bernard
*/
@Entity
@Table(name = "Translatn")
@CountryChecker
public class Translation {
private Integer id;
private String into;
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "country_into")
public String getInto() {
return into;
}
public void setInto(String into) {
this.into = into;
}
}

View File

@ -0,0 +1,35 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.callbacks;
import javax.persistence.EntityListeners;
import javax.persistence.ExcludeSuperclassListeners;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
/**
* @author Emmanuel Bernard
*/
@ExcludeSuperclassListeners
@EntityListeners({FirstOneListener.class, IncreaseListener.class})
@MappedSuperclass
public class VideoSystem extends CommunicationSystem {
public transient int counter = 0;
@PreUpdate
public void increase() {
isFirst = false;
isLast = false;
communication++;
}
@PrePersist
public void prepareEntity() {
counter++;
}
}

View File

@ -0,0 +1,31 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.callbacks.hbmxml;
/**
* @author Steve Ebersole
*/
public class Entity {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,56 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.callbacks.hbmxml;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.jpa.AvailableSettings;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.hibernate.jpa.boot.spi.Bootstrap;
import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test;
/**
* @author Felix Feisst (feisst dot felix at gmail dot com)
*/
public class MappingClassMoreThanOnceTest extends BaseUnitTestCase {
/**
* Tests that an entity manager can be created when a class is mapped more than once.
*/
@Test
@TestForIssue(jiraKey = "HHH-8775")
// @FailureExpected(jiraKey = "HHH-8775")
public void testBootstrapWithClassMappedMOreThanOnce() {
Map settings = new HashMap( );
settings.put( AvailableSettings.HBXML_FILES, "org/hibernate/jpa/test/callbacks/hbmxml/ClassMappedMoreThanOnce.hbm.xml" );
final EntityManagerFactoryBuilder builder = Bootstrap.getEntityManagerFactoryBuilder(
new BaseEntityManagerFunctionalTestCase.TestingPersistenceUnitDescriptorImpl( getClass().getSimpleName() ),
settings
);
HibernateEntityManagerFactory emf = null;
try {
emf = builder.build().unwrap( HibernateEntityManagerFactory.class );
}
finally {
if ( emf != null ) {
try {
emf.close();
}
catch (Exception ignore) {
}
}
}
}
}

View File

@ -0,0 +1,46 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.callbacks.xml;
import javax.persistence.EntityManager;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.hibernate.testing.TestForIssue;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author Steve Ebersole
*/
public class EntityListenerViaXmlTest extends BaseEntityManagerFunctionalTestCase {
@Override
protected String[] getMappings() {
return new String[] { "org/hibernate/jpa/test/callbacks/xml/MyEntity.orm.xml" };
}
@Test
@TestForIssue( jiraKey = "HHH-9771" )
public void testUsage() {
JournalingListener.reset();
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( new MyEntity( 1, "steve" ) );
em.getTransaction().commit();
em.close();
assertEquals( 1, JournalingListener.getPrePersistCount() );
em = getOrCreateEntityManager();
em.getTransaction().begin();
em.createQuery( "delete MyEntity" ).executeUpdate();
em.getTransaction().commit();
em.close();
}
}

View File

@ -0,0 +1,28 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.callbacks.xml;
/**
* An entity listener that keeps a journal of calls
*
* @author Steve Ebersole
*/
public class JournalingListener {
private static int prePersistCount;
public void onPrePersist(Object entity) {
prePersistCount++;
}
public static int getPrePersistCount() {
return prePersistCount;
}
public static void reset() {
prePersistCount = 0;
}
}

View File

@ -0,0 +1,39 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.callbacks.xml;
/**
* @author Steve Ebersole
*/
public class MyEntity {
private Integer id;
private String name;
public MyEntity() {
}
public MyEntity(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,22 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.cascade;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Author {
@Id @GeneratedValue
private Long id;
}

View File

@ -0,0 +1,96 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cascade;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import org.junit.Test;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
/**
* @author Max Rydahl Andersen
*/
public class CascadeTest extends BaseEntityManagerFunctionalTestCase {
@Test
public void testCascade() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Teacher teacher = new Teacher();
Student student = new Student();
teacher.setFavoriteStudent(student);
student.setFavoriteTeacher(teacher);
teacher.getStudents().add(student);
student.setPrimaryTeacher(teacher);
em.persist( teacher );
em.getTransaction().commit();
em = getOrCreateEntityManager();
em.getTransaction().begin();
Teacher foundTeacher = (Teacher) em.createQuery( "select t from Teacher as t" ).getSingleResult();
System.out.println(foundTeacher);
System.out.println(foundTeacher.getFavoriteStudent());
for (Student fstudent : foundTeacher.getStudents()) {
System.out.println(fstudent);
System.out.println(fstudent.getFavoriteTeacher());
System.out.println(fstudent.getPrimaryTeacher());
}
em.getTransaction().commit(); // here *alot* of flushes occur on an object graph that has *Zero* changes.
em.close();
}
@Test
public void testNoCascadeAndMerge() throws Exception {
Song e1 = new Song();
Author e2 = new Author();
e1.setAuthor(e2);
EntityManager em = getOrCreateEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(e2);
em.persist(e1);
tx.commit();
em.close();
em = getOrCreateEntityManager();
e1 = em.find(Song.class, e1.getId());
tx = em.getTransaction();
tx.begin();
em.merge(e1);
//em.refresh(e1);
tx.commit();
em.close();
}
@Override
public Class[] getAnnotatedClasses() {
return new Class[]{
Teacher.class,
Student.class,
Song.class,
Author.class
};
}
}

View File

@ -0,0 +1,85 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.cascade;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/**
* @author Emmanuel Bernard
*/
@Entity
@Table(name = "portal_pk_conference")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.CHAR)
@DiscriminatorValue("X")
@org.hibernate.annotations.Entity(dynamicInsert = true, dynamicUpdate = true)
public class Conference implements Serializable {
private Long id;
private Date date;
private ExtractionDocumentInfo extractionDocument;
@OneToOne(mappedBy = "conference", cascade = CascadeType.ALL)
public ExtractionDocumentInfo getExtractionDocument() {
return extractionDocument;
}
public void setExtractionDocument(ExtractionDocumentInfo extractionDocument) {
this.extractionDocument = extractionDocument;
}
public Conference() {
date = new Date();
}
@Id
@GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "c_date", nullable = false)
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public boolean equals(Object o) {
if ( this == o ) return true;
if ( o == null || getClass() != o.getClass() ) return false;
final Conference that = (Conference) o;
return !( date != null ? !date.equals( that.date ) : that.date != null );
}
public int hashCode() {
return ( date != null ? date.hashCode() : 0 );
}
}

View File

@ -0,0 +1,101 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cascade;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import org.junit.Assert;
import org.junit.Test;
import org.hibernate.Hibernate;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
/**
* @author Emmanuel Bernard
*/
public class DeleteOrphanTest extends BaseEntityManagerFunctionalTestCase {
@Test
public void testDeleteOrphan() throws Exception {
EntityTransaction tx;
EntityManager em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
Troop disney = new Troop();
disney.setName( "Disney" );
Soldier mickey = new Soldier();
mickey.setName( "Mickey" );
disney.addSoldier( mickey );
em.persist( disney );
tx.commit();
em.close();
em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
Troop troop = em.find( Troop.class, disney.getId() );
Hibernate.initialize( troop.getSoldiers() );
tx.commit();
em.close();
Soldier soldier = troop.getSoldiers().iterator().next();
troop.getSoldiers().remove( soldier );
troop = (Troop) deserialize( serialize( troop ) );
em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
em.merge( troop );
tx.commit();
em.close();
em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
soldier = em.find( Soldier.class, mickey.getId() );
Assert.assertNull( "delete-orphan should work", soldier );
troop = em.find( Troop.class, disney.getId() );
em.remove( troop );
tx.commit();
em.close();
}
@Override
public Class[] getAnnotatedClasses() {
return new Class[]{
Troop.class,
Soldier.class
};
}
private byte[] serialize(Object object) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream( stream );
out.writeObject( object );
out.close();
byte[] serialized = stream.toByteArray();
stream.close();
return serialized;
}
private Object deserialize(byte[] serialized) throws IOException, ClassNotFoundException {
ByteArrayInputStream byteIn = new ByteArrayInputStream( serialized );
ObjectInputStream in = new ObjectInputStream( byteIn );
Object result = in.readObject();
in.close();
byteIn.close();
return result;
}
}

View File

@ -0,0 +1,95 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cascade;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.junit.Test;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import static javax.persistence.CascadeType.DETACH;
import static javax.persistence.CascadeType.REMOVE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
/**
* @author Emmanuel Bernard
*/
public class DetachAndContainsTest extends BaseEntityManagerFunctionalTestCase {
@Test
public void testDetach() {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Tooth tooth = new Tooth();
Mouth mouth = new Mouth();
em.persist( mouth );
em.persist( tooth );
tooth.mouth = mouth;
mouth.teeth = new ArrayList<Tooth>();
mouth.teeth.add( tooth );
em.getTransaction().commit();
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
mouth = em.find( Mouth.class, mouth.id );
assertNotNull( mouth );
assertEquals( 1, mouth.teeth.size() );
tooth = mouth.teeth.iterator().next();
em.detach( mouth );
assertFalse( em.contains( tooth ) );
em.getTransaction().commit();
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
em.remove( em.find( Mouth.class, mouth.id ) );
em.getTransaction().commit();
em.close();
}
@Override
public Class[] getAnnotatedClasses() {
return new Class[] {
Mouth.class,
Tooth.class
};
}
@Entity
@Table(name = "mouth")
public static class Mouth {
@Id
@GeneratedValue
public Integer id;
@OneToMany(mappedBy = "mouth", cascade = { DETACH, REMOVE } )
public Collection<Tooth> teeth;
}
@Entity
@Table(name = "tooth")
public static class Tooth {
@Id
@GeneratedValue
public Integer id;
public String type;
@ManyToOne
public Mouth mouth;
}
}

View File

@ -0,0 +1,71 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.cascade;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Proxy;
/**
* @author Emmanuel Bernard
*/
@Entity
@Table(name = "portal_pk_docs_extraction")
//@Cache(usage = READ_WRITE)
@org.hibernate.annotations.Entity(dynamicInsert = true, dynamicUpdate = true)
@Proxy
public class ExtractionDocument implements Serializable {
private Long id;
private byte[] body;
private ExtractionDocumentInfo documentInfo;
public ExtractionDocument() {
}
public ExtractionDocument(ExtractionDocumentInfo documentInfo) {
this.documentInfo = documentInfo;
}
@Id
@GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@OneToOne
@JoinColumn(name = "document_info_id")
public ExtractionDocumentInfo getDocumentInfo() {
return documentInfo;
}
public void setDocumentInfo(ExtractionDocumentInfo documentInfo) {
this.documentInfo = documentInfo;
}
@Column(nullable = false)
public byte[] getBody() {
return body;
}
public void setBody(byte[] body) {
this.body = body;
}
}

View File

@ -0,0 +1,127 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.cascade;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.PreRemove;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
* @author Emmanuel Bernard
*/
@Entity
@Table(name = "portal_pk_docs_extraction_info")
//@Cache(usage = READ_WRITE)
@org.hibernate.annotations.Entity(dynamicInsert = true, dynamicUpdate = true)
public class ExtractionDocumentInfo implements Serializable {
private Long id;
private Date lastModified;
private Conference conference;
private List<ExtractionDocument> documents;
public ExtractionDocumentInfo() {
lastModified = new Date();
}
public ExtractionDocumentInfo(Conference conference) {
this.conference = conference;
lastModified = new Date();
documents = new ArrayList<ExtractionDocument>();
documents.add( new ExtractionDocument( this ) );
}
@Transient
public ExtractionDocument getDocument() {
if ( documents.isEmpty() ) {
documents.add( new ExtractionDocument( this ) );
}
Iterator<ExtractionDocument> iterator = documents.iterator();
return iterator.next();
}
@Transient
public byte[] getBody() {
return getDocument().getBody();
}
public void setBody(byte[] body) {
getDocument().setBody( body );
}
@Id
@GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@OneToMany(mappedBy = "documentInfo", cascade = CascadeType.ALL)
public List<ExtractionDocument> getDocuments() {
return documents;
}
public void setDocuments(List<ExtractionDocument> documents) {
this.documents = documents;
}
@ManyToOne
@JoinColumn(name = "conference_id")
public Conference getConference() {
return conference;
}
public void setConference(Conference conference) {
this.conference = conference;
}
@Column(name = "last_modified", nullable = false)
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public boolean equals(Object o) {
if ( this == o ) return true;
if ( !( o instanceof ExtractionDocumentInfo ) ) return false;
final ExtractionDocumentInfo newsInfo = (ExtractionDocumentInfo) o;
return id.equals( newsInfo.id );
}
public int hashCode() {
return id.hashCode();
}
@PreRemove
public void preRemove() {
getConference().setExtractionDocument( null );
}
}

View File

@ -0,0 +1,160 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cascade;
import java.util.ArrayList;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import org.hibernate.Hibernate;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Emmanuel Bernard
*/
public class FetchTest extends BaseEntityManagerFunctionalTestCase {
@Test
public void testCascadeAndFetchCollection() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Troop disney = new Troop();
disney.setName( "Disney" );
Soldier mickey = new Soldier();
mickey.setName( "Mickey" );
disney.addSoldier( mickey );
em.persist( disney );
em.getTransaction().commit();
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
Troop troop = em.find( Troop.class, disney.getId() );
assertFalse( Hibernate.isInitialized( troop.getSoldiers() ) );
em.getTransaction().commit();
assertFalse( Hibernate.isInitialized( troop.getSoldiers() ) );
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
troop = em.find( Troop.class, disney.getId() );
em.remove( troop );
//Fail because of HHH-1187
em.getTransaction().commit();
em.close();
}
@Test
public void testCascadeAndFetchEntity() throws Exception {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Troop disney = new Troop();
disney.setName( "Disney" );
Soldier mickey = new Soldier();
mickey.setName( "Mickey" );
disney.addSoldier( mickey );
em.persist( disney );
em.getTransaction().commit();
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
Soldier soldier = em.find( Soldier.class, mickey.getId() );
assertFalse( Hibernate.isInitialized( soldier.getTroop() ) );
em.getTransaction().commit();
assertFalse( Hibernate.isInitialized( soldier.getTroop() ) );
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
Troop troop = em.find( Troop.class, disney.getId() );
em.remove( troop );
//Fail because of HHH-1187
em.getTransaction().commit();
em.close();
}
@Test
public void testTwoLevelDeepPersist() throws Exception {
EntityTransaction tx;
EntityManager em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
Conference jbwBarcelona = new Conference();
jbwBarcelona.setDate( new Date() );
ExtractionDocumentInfo info = new ExtractionDocumentInfo();
info.setConference( jbwBarcelona );
jbwBarcelona.setExtractionDocument( info );
info.setLastModified( new Date() );
ExtractionDocument doc = new ExtractionDocument();
doc.setDocumentInfo( info );
info.setDocuments( new ArrayList<ExtractionDocument>() );
info.getDocuments().add( doc );
doc.setBody( new byte[]{'c', 'f'} );
em.persist( jbwBarcelona );
tx.commit();
em.close();
em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
jbwBarcelona = em.find( Conference.class, jbwBarcelona.getId() );
assertTrue( Hibernate.isInitialized( jbwBarcelona ) );
assertTrue( Hibernate.isInitialized( jbwBarcelona.getExtractionDocument() ) );
assertFalse( Hibernate.isInitialized( jbwBarcelona.getExtractionDocument().getDocuments() ) );
em.flush();
assertTrue( Hibernate.isInitialized( jbwBarcelona ) );
assertTrue( Hibernate.isInitialized( jbwBarcelona.getExtractionDocument() ) );
assertFalse( Hibernate.isInitialized( jbwBarcelona.getExtractionDocument().getDocuments() ) );
em.remove( jbwBarcelona );
tx.commit();
em.close();
}
@Test
public void testTwoLevelDeepPersistOnManyToOne() throws Exception {
EntityTransaction tx;
EntityManager em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
Grandson gs = new Grandson();
gs.setParent( new Son() );
gs.getParent().setParent( new Parent() );
em.persist( gs );
tx.commit();
em.close();
em = getOrCreateEntityManager();
tx = em.getTransaction();
tx.begin();
gs = em.find( Grandson.class, gs.getId() );
em.flush();
assertTrue( Hibernate.isInitialized( gs.getParent() ) );
assertFalse( Hibernate.isInitialized( gs.getParent().getParent() ) );
em.remove( gs );
tx.commit();
em.close();
}
@Override
public Class[] getAnnotatedClasses() {
return new Class[]{
Troop.class,
Soldier.class,
Conference.class,
ExtractionDocument.class,
ExtractionDocumentInfo.class,
Parent.class,
Son.class,
Grandson.class
};
}
}

View File

@ -0,0 +1,77 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cascade;
import javax.persistence.EntityManager;
import org.junit.Test;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import static org.junit.Assert.fail;
public class FetchTest2 extends BaseEntityManagerFunctionalTestCase {
@Test
public void testProxyTransientStuff() throws Exception {
EntityManager em = entityManagerFactory().createEntityManager();
em.getTransaction().begin();
Troop2 disney = new Troop2();
disney.setName( "Disney" );
Soldier2 mickey = new Soldier2();
mickey.setName( "Mickey" );
mickey.setTroop( disney );
em.persist( disney );
em.persist( mickey );
em.getTransaction().commit();
em.close();
em = entityManagerFactory().createEntityManager();
em.getTransaction().begin();
Soldier2 soldier = em.find( Soldier2.class, mickey.getId() );
soldier.getTroop().getId();
try {
em.flush();
}
catch (IllegalStateException e) {
fail( "Should not raise an exception" );
}
em.getTransaction().commit();
em.close();
em = entityManagerFactory().createEntityManager();
em.getTransaction().begin();
//load troop wo a proxy
disney = em.find( Troop2.class, disney.getId() );
soldier = em.find( Soldier2.class, mickey.getId() );
try {
em.flush();
}
catch (IllegalStateException e) {
fail( "Should not raise an exception" );
}
em.remove( soldier );
em.remove( disney );
em.getTransaction().commit();
em.close();
}
@Override
public Class[] getAnnotatedClasses() {
return new Class[]{
Troop2.class,
Soldier2.class
};
}
}

View File

@ -0,0 +1,43 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//$Id$
package org.hibernate.jpa.test.cascade;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
/**
* @author Emmanuel Bernard
*/
@Entity
public class Grandson {
@Id
@GeneratedValue
private Integer id;
@ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.ALL})
private Son parent;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Son getParent() {
return parent;
}
public void setParent(Son parent) {
this.parent = parent;
}
}

View File

@ -0,0 +1,131 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.test.cascade;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import org.junit.Test;
import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase;
import static org.junit.Assert.assertEquals;
public class MergeTest extends BaseEntityManagerFunctionalTestCase {
@Test
public void testMergeDetachedEntityWithNewOneToManyElements() {
Order order = new Order();
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( order );
em.getTransaction().commit();
em.close();
Item item1 = new Item();
item1.name = "i1";
Item item2 = new Item();
item2.name = "i2";
order.addItem( item1 );
order.addItem( item2 );
em = getOrCreateEntityManager();
em.getTransaction().begin();
order = em.merge( order );
em.flush();
em.getTransaction().commit();
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
order = em.find( Order.class, order.id );
assertEquals( 2, order.items.size() );
em.remove( order );
em.getTransaction().commit();
em.close();
}
@Test
public void testMergeLoadedEntityWithNewOneToManyElements() {
Order order = new Order();
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
em.persist( order );
em.getTransaction().commit();
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
order = em.find( Order.class, order.id );
Item item1 = new Item();
item1.name = "i1";
Item item2 = new Item();
item2.name = "i2";
order.addItem( item1 );
order.addItem( item2 );
order = em.merge( order );
em.flush();
em.getTransaction().commit();
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
order = em.find( Order.class, order.id );
assertEquals( 2, order.items.size() );
em.remove( order );
em.getTransaction().commit();
em.close();
}
protected Class[] getAnnotatedClasses() {
return new Class[] {
Order.class,
Item.class
};
}
@Entity
private static class Order {
@Id
@GeneratedValue
private Long id;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "order", orphanRemoval = true)
private List<Item> items = new ArrayList<Item>();
public Order() {
}
public void addItem(Item item) {
items.add( item );
item.order = this;
}
}
@Entity
private static class Item {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToOne
private Order order;
}
}

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