Move User Guide Bootstrap chapter code snippets from extras to test folder

This commit is contained in:
vladmihalcea 2016-01-26 11:13:40 +02:00
parent 4e36781b42
commit b23784647d
16 changed files with 533 additions and 180 deletions

View File

@ -1,6 +1,6 @@
[[bootstrap]]
== Bootstrap
:sourcedir: extras
:sourcedir: ../../../../../test/java/org/hibernate/userguide/bootstrap
The term bootstrapping refers to initializing and starting a software component.
In Hibernate, we are specifically talking about the process of building a fully functional `SessionFactory` instance or `EntityManagerFactory` instance, for JPA.
@ -43,11 +43,12 @@ If you are ok with the default behavior of Hibernate in regards to these `Bootst
If you wish to alter how the `BootstrapServiceRegistry` is built, that is controlled through the `org.hibernate.boot.registry.BootstrapServiceRegistryBuilder:`
.Controlling BootstrapServiceRegistry building
[[bootstrap-bootstrap-native-registry-BootstrapServiceRegistry-example]]
.Controlling `BootstrapServiceRegistry` building
====
[source,java]
[source, JAVA, indent=0]
----
include::{sourcedir}/native1.java[]
include::{sourcedir}/BootstrapTest.java[tags=bootstrap-bootstrap-native-registry-BootstrapServiceRegistry-example]
----
====
@ -59,16 +60,12 @@ The services of the `BootstrapServiceRegistry` cannot be extended (added to) nor
The second ServiceRegistry is the `org.hibernate.boot.registry.StandardServiceRegistry`.
You will almost always need to configure the `StandardServiceRegistry`, which is done through `org.hibernate.boot.registry.StandardServiceRegistryBuilder`:
.Building a BootstrapServiceRegistryBuilder
[[bootstrap-bootstrap-native-registry-StandardServiceRegistryBuilder-example]]
.Building a `BootstrapServiceRegistryBuilder`
====
[source,java]
[source, JAVA, indent=0]
----
include::{sourcedir}/native2.java[]
----
[source,java]
----
include::{sourcedir}/native3.java[]
include::{sourcedir}/BootstrapTest.java[tags=bootstrap-bootstrap-native-registry-StandardServiceRegistryBuilder-example]
----
====
@ -77,24 +74,27 @@ See the `StandardServiceRegistryBuilder` https://docs.jboss.org/hibernate/stable
Some specific methods of interest:
.Configuring a MetadataSources
[[bootstrap-bootstrap-native-registry-MetadataSources-example]]
.Configuring a `MetadataSources`
====
[source,java]
[source, JAVA, indent=0]
----
include::{sourcedir}/native5.java[]
include::{sourcedir}/BootstrapTest.java[tags=bootstrap-bootstrap-native-registry-MetadataSources-example]
----
====
[[event-listener-registration]]
[[bootstrap-event-listener-registration]]
==== Event Listener registration
The main use cases for an `org.hibernate.integrator.spi.Integrator` right now are registering event listeners and providing services (see `org.hibernate.integrator.spi.ServiceContributingIntegrator`).
With 5.0 we plan on expanding that to allow altering the metamodel describing the mapping between object and relational models.
[[bootstrap-event-listener-registration-example]]
.Configuring an event listener
====
[source,java]
[source, JAVA, indent=0]
----
include::{sourcedir}/register-event-listeners-example.java[]
include::{sourcedir}/BootstrapTest.java[tags=bootstrap-event-listener-registration-example]
----
====
@ -108,11 +108,12 @@ This is the purpose of `org.hibernate.boot.MetadataSources`:
`MetadataSources` has many other methods as well, explore its API and https://docs.jboss.org/hibernate/stable/orm/javadocs/org/hibernate/boot/MetadataSources.html[Javadocs] for more information.
Also, all methods on `MetadataSources` offer fluent-style call chaining::
.Configuring a MetadataSources with method chaining
[[bootstrap-native-metadata-source-example]]
.Configuring a `MetadataSources` with method chaining
====
[source,java]
[source, JAVA, indent=0]
----
include::{sourcedir}/native6.java[]
include::{sourcedir}/BootstrapTest.java[tags=bootstrap-native-metadata-source-example]
----
====
@ -131,15 +132,16 @@ you will need to use the `MetadataBuilder` as obtained via `MetadataSources#getM
`MetadataBuilder` allows a lot of control over the `Metadata` building process.
See its https://docs.jboss.org/hibernate/stable/orm/javadocs/org/hibernate/boot/MetadataBuilder.html[Javadocs] for full details.
.Building Metadata via MetadataBuilder
[[bootstrap-native-metadata-builder-example]]
.Building Metadata via `MetadataBuilder`
====
[source,java]
[source, JAVA, indent=0]
----
include::{sourcedir}/native7.java[]
include::{sourcedir}/BootstrapTest.java[tags=bootstrap-native-metadata-builder-example]
----
====
[[bootstrap-native-sessionfactory]]
[[bootstrap-native-SessionFactory]]
==== Building the SessionFactory
The final step in native bootstrapping is to build the `SessionFactory` itself.
@ -147,11 +149,12 @@ Much like discussed above, if you are ok with the default behavior of building a
However, if you would like to adjust that building process you will need to use `SessionFactoryBuilder` as obtained via [`Metadata#getSessionFactoryBuilder`. Again, see its https://docs.jboss.org/hibernate/stable/orm/javadocs/org/hibernate/boot/Metadata.html#getSessionFactoryBuilder--[Javadocs] for more details.
[[bootstrap-native-SessionFactory-example]]
.Native Bootstrapping - Putting it all together
====
[source,java]
[source, JAVA, indent=0]
----
include::{sourcedir}/native9.java[]
include::{sourcedir}/BootstrapTest.java[tags=bootstrap-native-SessionFactory-example]
----
====
@ -161,11 +164,12 @@ The bootstrapping API is quite flexible, but in most cases it makes the most sen
2. Build the `Metadata`
3. Use those 2 to build the `SessionFactory`
[[bootstrap-native-SessionFactoryBuilder-example]]
.Building `SessionFactory` via `SessionFactoryBuilder`
====
[source,java]
[source, JAVA, indent=0]
----
include::{sourcedir}/native8.java[]
include::{sourcedir}/BootstrapTest.java[tags=bootstrap-native-SessionFactoryBuilder-example]
----
====
@ -189,22 +193,24 @@ If you would like additional details on accessing and using `EntityManager` inst
For compliant container-bootstrapping, the container will build an `EntityManagerFactory` for each persistent-unit defined in the `META-INF/persistence.xml` configuration file
and make that available to the application for injection via the `javax.persistence.PersistenceUnit` annotation or via JNDI lookup.
[[bootstrap-jpa-compliant-PersistenceUnit-example]]
.Injecting a EntityManagerFactory
====
[source,java]
[source, JAVA, indent=0]
----
include::{sourcedir}/jpa1.java[]
include::{sourcedir}/BootstrapTest.java[tags=bootstrap-jpa-compliant-PersistenceUnit-example]
----
====
For compliant application-bootstrapping, rather than the container building the `EntityManagerFactory` for the application, the application builds the `EntityManagerFactory` itself using the `javax.persistence.Persistence` bootstrap class.
The application creates an `EntityManagerFactory` by calling the `createEntityManagerFactory` method:
[[bootstrap-jpa-compliant-EntityManagerFactory-example]]
.Application bootstrapped EntityManagerFactory
====
[source,java]
[source, JAVA, indent=0]
----
include::{sourcedir}/jpa2.java[]
include::{sourcedir}/BootstrapTest.java[tags=bootstrap-jpa-compliant-EntityManagerFactory-example]
----
====
@ -215,11 +221,12 @@ Hibernate defines a proprietary https://docs.jboss.org/hibernate/stable/orm/java
utility, which allows bootstrapping the JPA environment without even in the absence of the `persistence.xml` configuration file.
To substitute the `persistence.xml` file, Hibernate offers the `PersistenceUnitInfoDescriptor` utility, which can take configuration that's available in the standard XML configuration file.
[[bootstrap-native-EntityManagerFactory-example]]
.Proprietary bootstrapped `EntityManagerFactory`
====
[source,java]
[source, JAVA, indent=0]
----
include::{sourcedir}/jpa3.java[]
include::{sourcedir}/BootstrapTest.java[tags=bootstrap-native-EntityManagerFactory-example]
----
====

View File

@ -1,2 +0,0 @@
@PersistenceUnit
EntityManagerFactory emf;

View File

@ -1,2 +0,0 @@
// Create an EMF for our CRM persistence-unit.
EntityManagerFactory emf = Persistence.createEntityManagerFactory( "CRM" );

View File

@ -1,18 +0,0 @@
String persistenceUnitName = ...
List<String> entityClassNames = ...
Properties properties = ...
PersistenceUnitInfo persistenceUnitInfo = new PersistenceUnitInfoImpl(
persistenceUnitName,
entityClassNames,
properties
);
Map<String, Object> integrationSettings = new HashMap<>();
integrationSettings.put(AvailableSettings.INTERCEPTOR, interceptor());
EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = new EntityManagerFactoryBuilderImpl(
new PersistenceUnitInfoDescriptor(persistenceUnitInfo),
integrationSettings
);
EntityManagerFactory emf = entityManagerFactoryBuilder.build();

View File

@ -1,9 +0,0 @@
BootstrapServiceRegistryBuilder bootstrapRegistryBuilder = new BootstrapServiceRegistryBuilder();
// add a special ClassLoader
bootstrapRegistryBuilder.applyClassLoader( mySpecialClassLoader );
// manually add an Integrator
bootstrapRegistryBuilder.applyIntegrator( mySpecialIntegrator );
...
BootstrapServiceRegistry bootstrapRegistry = bootstrapRegistryBuilder.build();

View File

@ -1,2 +0,0 @@
// An example using an implicitly built BootstrapServiceRegistry
StandardServiceRegistryBuilder standardRegistryBuilder = new StandardServiceRegistryBuilder();

View File

@ -1,4 +0,0 @@
// An example using an explicitly built BootstrapServiceRegistry
BootstrapServiceRegistry bootstrapRegistry = ...;
StandardServiceRegistryBuilder standardRegistryBuilder = new StandardServiceRegistryBuilder( bootstrapRegistry );

View File

@ -1,19 +0,0 @@
StandardServiceRegistryBuilder standardRegistryBuilder = ...;
// load some properties via resource lookup
standardRegistryBuilder.loadProperties( "org/hibernate/example/MyProperties.properties" );
// configure the registry from a resource lookup for a cfg.xml config file
standardRegistryBuilder.configure( "org/hibernate/example/my.cfg.xml" );
// apply a random setting
standardRegistryBuilder.applySetting( "myProp","some value" );
// apply a service initiator
standardRegistryBuilder.addInitiator( new CustomServiceInitiator() );
// apply a service impl
standardRegistryBuilder.addService( SomeCustomService.class,new SomeCustomServiceImpl() );
// and finally build the StandardServiceRegistry
StandardServiceRegistry standardRegistry = standardRegistryBuilder.build();

View File

@ -1,23 +0,0 @@
MetadataSources sources = new MetadataSources( standardRegistry );
// alternatively, we can build the MetadataSources without passing
// a service registry, in which case it will build a default
// BootstrapServiceRegistry to use. But the approach shown
// above is preferred
// MetadataSources sources = new MetadataSources();
// add a class using JPA/Hibernate annotations for mapping
sources.addAnnotatedClass( MyEntity.class );
// add the name of a class using JPA/Hibernate annotations for mapping.
// differs from above in that accessing the Class is deferred which is
// important if using runtime bytecode-enhancement
sources.addAnnotatedClassName( "org.hibernate.example.Customer" );
// Adds the named hbm.xml resource as a source: which performs the
// classpath lookup and parses the XML
sources.addResource( "org/hibernate/example/Order.hbm.xml" );
// Adds the named JPA orm.xml resource as a source: which performs the
// classpath lookup and parses the XML
sources.addResource( "org/hibernate/example/Product.orm.xml" );

View File

@ -1,5 +0,0 @@
MetadataSources sources = new MetadataSources( standardRegistry )
.addAnnotatedClass( MyEntity.class )
.addAnnotatedClassName( "org.hibernate.example.Customer" )
.addResource( "org/hibernate/example/Order.hbm.xml" )
.addResource( "org/hibernate/example/Product.orm.xml" );

View File

@ -1,9 +0,0 @@
MetadataBuilder metadataBuilder = sources.getMetadataBuilder();
// Use the JPA-compliant implicit naming strategy
metadataBuilder.applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE );
// specify the schema name to use for tables, etc when none is explicitly specified
metadataBuilder.applyImplicitSchemaName( "my_default_schema" );
Metadata metadata = metadataBuilder.build();

View File

@ -1,12 +0,0 @@
SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder();
// Supply an SessionFactory-level Interceptor
sessionFactoryBuilder.applyInterceptor( new MySessionFactoryInterceptor() );
// Add a custom observer
sessionFactoryBuilder.addSessionFactoryObservers( new MySessionFactoryObserver() );
// Apply a CDI BeanManager ( for JPA event listeners )
sessionFactoryBuilder.applyBeanManager( getBeanManagerFromSomewhere() );
SessionFactory sessionFactory = sessionFactoryBuilder.build();

View File

@ -1,16 +0,0 @@
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure( "org/hibernate/example/MyCfg.xml" )
.build();
Metadata metadata = new MetadataSources( standardRegistry )
.addAnnotatedClass( MyEntity.class )
.addAnnotatedClassName( "org.hibernate.example.Customer" )
.addResource( "org/hibernate/example/Order.hbm.xml" )
.addResource( "org/hibernate/example/Product.orm.xml" )
.getMetadataBuilder()
.applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE )
.build();
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder()
.applyBeanManager( getBeanManagerFromSomewhere() )
.build();

View File

@ -1,23 +0,0 @@
public class MyIntegrator implements org.hibernate.integrator.spi.Integrator {
public void integrate(
Configuration configuration,
SessionFactoryImplementor sessionFactory,
SessionFactoryServiceRegistry serviceRegistry) {
// As you might expect, an EventListenerRegistry is the thing with which event listeners are registered It is a
// service so we look it up using the service registry
final EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );
// If you wish to have custom determination and handling of "duplicate" listeners, you would have to add an
// implementation of the org.hibernate.event.service.spi.DuplicationStrategy contract like this
eventListenerRegistry.addDuplicationStrategy( myDuplicationStrategy );
// EventListenerRegistry defines 3 ways to register listeners:
// 1) This form overrides any existing registrations with
eventListenerRegistry.setListeners( EventType.AUTO_FLUSH, myCompleteSetOfListeners );
// 2) This form adds the specified listener(s) to the beginning of the listener chain
eventListenerRegistry.prependListeners( EventType.AUTO_FLUSH, myListenersToBeCalledFirst );
// 3) This form adds the specified listener(s) to the end of the listener chain
eventListenerRegistry.appendListeners( EventType.AUTO_FLUSH, myListenersToBeCalledLast );
}
}

View File

@ -80,7 +80,7 @@ Hibernate allows certain actions to be authorized via JACC and JAAS.
This is an optional functionality that is built on top of the event architecture.
First, you must configure the appropriate event listeners, to enable the use of JACC authorization.
Again, see <<chapters/bootstrap/Bootstrap.adoc#event-listener-registration,Event Listener Registration>> for the details.
Again, see <<chapters/bootstrap/Bootstrap.adoc#bootstrap-event-listener-registration,Event Listener Registration>> for the details.
Below is an example of an appropriate `org.hibernate.integrator.spi.Integrator` implementation for this purpose.

View File

@ -0,0 +1,490 @@
/*
* 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.userguide.bootstrap;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.persistence.Entity;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Id;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
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.EmptyInterceptor;
import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataBuilder;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.beanvalidation.BeanValidationIntegrator;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.event.internal.DefaultAutoFlushEventListener;
import org.hibernate.event.internal.DefaultMergeEventListener;
import org.hibernate.event.internal.DefaultPersistEventListener;
import org.hibernate.event.service.spi.DuplicationStrategy;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.integrator.spi.Integrator;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.spi.SessionFactoryServiceRegistry;
import org.junit.Test;
/**
* @author Vlad Mihalcea
*/
public class BootstrapTest {
@Test
public void dummy() {}
{
ClassLoader customClassLoader = Thread.currentThread().getContextClassLoader();
Integrator customIntegrator = new BeanValidationIntegrator();
//tag::bootstrap-bootstrap-native-registry-BootstrapServiceRegistry-example[]
BootstrapServiceRegistryBuilder bootstrapRegistryBuilder =
new BootstrapServiceRegistryBuilder();
// add a custom ClassLoader
bootstrapRegistryBuilder.applyClassLoader( customClassLoader );
// manually add an Integrator
bootstrapRegistryBuilder.applyIntegrator( customIntegrator );
BootstrapServiceRegistry bootstrapRegistry = bootstrapRegistryBuilder.build();
//end::bootstrap-bootstrap-native-registry-BootstrapServiceRegistry-example[]
}
{
//tag::bootstrap-bootstrap-native-registry-StandardServiceRegistryBuilder-example[]
// An example using an implicitly built BootstrapServiceRegistry
StandardServiceRegistryBuilder standardRegistryBuilder =
new StandardServiceRegistryBuilder();
//end::bootstrap-bootstrap-native-registry-StandardServiceRegistryBuilder-example[]
}
{
//tag::bootstrap-bootstrap-native-registry-StandardServiceRegistryBuilder-example[]
// An example using an explicitly built BootstrapServiceRegistry
BootstrapServiceRegistry bootstrapRegistry =
new BootstrapServiceRegistryBuilder().build();
StandardServiceRegistryBuilder standardRegistryBuilder =
new StandardServiceRegistryBuilder( bootstrapRegistry );
//end::bootstrap-bootstrap-native-registry-StandardServiceRegistryBuilder-example[]
}
{
try {
//tag::bootstrap-bootstrap-native-registry-MetadataSources-example[]
ServiceRegistry standardRegistry =
new StandardServiceRegistryBuilder().build();
MetadataSources sources = new MetadataSources( standardRegistry );
// alternatively, we can build the MetadataSources without passing
// a service registry, in which case it will build a default
// BootstrapServiceRegistry to use. But the approach shown
// above is preferred
// MetadataSources sources = new MetadataSources();
// add a class using JPA/Hibernate annotations for mapping
sources.addAnnotatedClass( MyEntity.class );
// add the name of a class using JPA/Hibernate annotations for mapping.
// differs from above in that accessing the Class is deferred which is
// important if using runtime bytecode-enhancement
sources.addAnnotatedClassName( "org.hibernate.example.Customer" );
// Adds the named hbm.xml resource as a source: which performs the
// classpath lookup and parses the XML
sources.addResource( "org/hibernate/example/Order.hbm.xml" );
// Adds the named JPA orm.xml resource as a source: which performs the
// classpath lookup and parses the XML
sources.addResource( "org/hibernate/example/Product.orm.xml" );
//end::bootstrap-bootstrap-native-registry-MetadataSources-example[]
}
catch (Exception ignore) {
}
}
{
try {
{
//tag::bootstrap-native-metadata-source-example[]
ServiceRegistry standardRegistry =
new StandardServiceRegistryBuilder().build();
MetadataSources sources = new MetadataSources( standardRegistry )
.addAnnotatedClass( MyEntity.class )
.addAnnotatedClassName( "org.hibernate.example.Customer" )
.addResource( "org/hibernate/example/Order.hbm.xml" )
.addResource( "org/hibernate/example/Product.orm.xml" );
//end::bootstrap-native-metadata-source-example[]
}
{
//tag::bootstrap-native-metadata-builder-example[]
ServiceRegistry standardRegistry =
new StandardServiceRegistryBuilder().build();
MetadataSources sources = new MetadataSources( standardRegistry );
MetadataBuilder metadataBuilder = sources.getMetadataBuilder();
// Use the JPA-compliant implicit naming strategy
metadataBuilder.applyImplicitNamingStrategy(
ImplicitNamingStrategyJpaCompliantImpl.INSTANCE );
// specify the schema name to use for tables, etc when none is explicitly specified
metadataBuilder.applyImplicitSchemaName( "my_default_schema" );
Metadata metadata = metadataBuilder.build();
//end::bootstrap-native-metadata-builder-example[]
}
}
catch (Exception ignore) {
}
}
{
try {
{
//tag::bootstrap-native-SessionFactory-example[]
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure( "org/hibernate/example/hibernate.cfg.xml" )
.build();
Metadata metadata = new MetadataSources( standardRegistry )
.addAnnotatedClass( MyEntity.class )
.addAnnotatedClassName( "org.hibernate.example.Customer" )
.addResource( "org/hibernate/example/Order.hbm.xml" )
.addResource( "org/hibernate/example/Product.orm.xml" )
.getMetadataBuilder()
.applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE )
.build();
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder()
.applyBeanManager( getBeanManager() )
.build();
//end::bootstrap-native-SessionFactory-example[]
}
{
//tag::bootstrap-native-SessionFactoryBuilder-example[]
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure( "org/hibernate/example/hibernate.cfg.xml" )
.build();
Metadata metadata = new MetadataSources( standardRegistry )
.addAnnotatedClass( MyEntity.class )
.addAnnotatedClassName( "org.hibernate.example.Customer" )
.addResource( "org/hibernate/example/Order.hbm.xml" )
.addResource( "org/hibernate/example/Product.orm.xml" )
.getMetadataBuilder()
.applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE )
.build();
SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder();
// Supply an SessionFactory-level Interceptor
sessionFactoryBuilder.applyInterceptor( new CustomSessionFactoryInterceptor() );
// Add a custom observer
sessionFactoryBuilder.addSessionFactoryObservers( new CustomSessionFactoryObserver() );
// Apply a CDI BeanManager ( for JPA event listeners )
sessionFactoryBuilder.applyBeanManager( getBeanManager() );
SessionFactory sessionFactory = sessionFactoryBuilder.build();
//end::bootstrap-native-SessionFactoryBuilder-example[]
}
}
catch (Exception ignore) {
}
}
public Object getBeanManager() {
return null;
}
@Entity
public static class MyEntity {
@Id
private Long id;
}
//tag::bootstrap-event-listener-registration-example[]
public class MyIntegrator implements org.hibernate.integrator.spi.Integrator {
@Override
public void integrate(
Metadata metadata,
SessionFactoryImplementor sessionFactory,
SessionFactoryServiceRegistry serviceRegistry) {
// As you might expect, an EventListenerRegistry is the thing with which event
// listeners are registered
// It is a service so we look it up using the service registry
final EventListenerRegistry eventListenerRegistry =
serviceRegistry.getService( EventListenerRegistry.class );
// If you wish to have custom determination and handling of "duplicate" listeners,
// you would have to add an implementation of the
// org.hibernate.event.service.spi.DuplicationStrategy contract like this
eventListenerRegistry.addDuplicationStrategy( new CustomDuplicationStrategy() );
// EventListenerRegistry defines 3 ways to register listeners:
// 1) This form overrides any existing registrations with
eventListenerRegistry.setListeners( EventType.AUTO_FLUSH,
DefaultAutoFlushEventListener.class );
// 2) This form adds the specified listener(s) to the beginning of the listener chain
eventListenerRegistry.prependListeners( EventType.PERSIST,
DefaultPersistEventListener.class );
// 3) This form adds the specified listener(s) to the end of the listener chain
eventListenerRegistry.appendListeners( EventType.MERGE,
DefaultMergeEventListener.class );
}
@Override
public void disintegrate(
SessionFactoryImplementor sessionFactory,
SessionFactoryServiceRegistry serviceRegistry) {
}
}
//end::bootstrap-event-listener-registration-example[]
public class CustomDuplicationStrategy implements DuplicationStrategy {
@Override
public boolean areMatch(Object listener, Object original) {
return false;
}
@Override
public Action getAction() {
return null;
}
}
public class CustomSessionFactoryInterceptor extends EmptyInterceptor {}
public class CustomSessionFactoryObserver implements SessionFactoryObserver {
@Override
public void sessionFactoryCreated(SessionFactory factory) {
}
@Override
public void sessionFactoryClosed(SessionFactory factory) {
}
}
//tag::bootstrap-jpa-compliant-PersistenceUnit-example[]
@PersistenceUnit
private EntityManagerFactory emf;
//end::bootstrap-jpa-compliant-PersistenceUnit-example[]
{
try {
//tag::bootstrap-jpa-compliant-EntityManagerFactory-example[]
// Create an EMF for our CRM persistence-unit.
EntityManagerFactory emf = Persistence.createEntityManagerFactory( "CRM" );
//end::bootstrap-jpa-compliant-EntityManagerFactory-example[]
} catch (Exception ignore) {}
}
{
try {
//tag::bootstrap-native-EntityManagerFactory-example[]
String persistenceUnitName = "CRM";
List<String> entityClassNames = new ArrayList<>( );
Properties properties = new Properties( );
PersistenceUnitInfoImpl persistenceUnitInfo = new PersistenceUnitInfoImpl(
persistenceUnitName,
entityClassNames,
properties
);
Map<String, Object> integrationSettings = new HashMap<>();
integrationSettings.put(
AvailableSettings.INTERCEPTOR,
new CustomSessionFactoryInterceptor()
);
EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder =
new EntityManagerFactoryBuilderImpl(
new PersistenceUnitInfoDescriptor( persistenceUnitInfo ),
integrationSettings
);
EntityManagerFactory emf = entityManagerFactoryBuilder.build();
//end::bootstrap-native-EntityManagerFactory-example[]
}
catch (Exception ignore) {
}
}
//tag::bootstrap-native-EntityManagerFactory-example[]
public class PersistenceUnitInfoImpl implements PersistenceUnitInfo {
private final String persistenceUnitName;
private PersistenceUnitTransactionType transactionType =
PersistenceUnitTransactionType.RESOURCE_LOCAL;
private final List<String> managedClassNames;
private final Properties properties;
private DataSource jtaDataSource;
private DataSource nonJtaDataSource;
public PersistenceUnitInfoImpl(
String persistenceUnitName,
List<String> managedClassNames,
Properties properties) {
this.persistenceUnitName = persistenceUnitName;
this.managedClassNames = managedClassNames;
this.properties = properties;
}
@Override
public String getPersistenceUnitName() {
return persistenceUnitName;
}
@Override
public String getPersistenceProviderClassName() {
return HibernatePersistenceProvider.class.getName();
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
return transactionType;
}
@Override
public DataSource getJtaDataSource() {
return jtaDataSource;
}
public PersistenceUnitInfoImpl setJtaDataSource(DataSource jtaDataSource) {
this.jtaDataSource = jtaDataSource;
this.nonJtaDataSource = null;
transactionType = PersistenceUnitTransactionType.JTA;
return this;
}
@Override
public DataSource getNonJtaDataSource() {
return nonJtaDataSource;
}
public PersistenceUnitInfoImpl setNonJtaDataSource(DataSource nonJtaDataSource) {
this.nonJtaDataSource = nonJtaDataSource;
this.jtaDataSource = null;
transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
return this;
}
@Override
public List<String> getMappingFileNames() {
return null;
}
@Override
public List<URL> getJarFileUrls() {
return Collections.emptyList();
}
@Override
public URL getPersistenceUnitRootUrl() {
return null;
}
@Override
public List<String> getManagedClassNames() {
return managedClassNames;
}
@Override
public boolean excludeUnlistedClasses() {
return false;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return SharedCacheMode.UNSPECIFIED;
}
@Override
public ValidationMode getValidationMode() {
return ValidationMode.AUTO;
}
public Properties getProperties() {
return properties;
}
@Override
public String getPersistenceXMLSchemaVersion() {
return "2.1";
}
@Override
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
@Override
public void addTransformer(ClassTransformer transformer) {
}
@Override
public ClassLoader getNewTempClassLoader() {
return null;
}
}
//end::bootstrap-native-EntityManagerFactory-example[]
}