Two phase commit transaction in Java EE 5 - java

I want to know that how can I do two phase commit transaction by using Java EE5...I am using EJB with JPA which has hibernate configured with MySql. I just want to use JAVA EE specification for transaction not using hibernate or JDBC specific object....

All you need to do, to ensure that JTA transactions are used to perform all transactional work in JPA, is to specify that the Persistence Unit type is JTA, and designate a JTA datasource for use by the JPA provider. Your persistence.xml file would have contents similar to the following:
<persistence version="1.0" 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">
<!-- Specifies the type of the entity managers used by the persistence unit,
as a JTA entity manager -->
<persistence-unit name="example-pu" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<!-- Specifies a JTA datasource for use by the JPA provider.
All connections obtained by the JPA provider for this persistence unit
will be from this datasource -->
<jta-data-source>jdbc/myDS</jta-data-source>
...
</persistence-unit>
</persistence>
Additionally, you must ensure that the datasource defined in the jta-data-source attribute, does not employ optimizations like allowing local transactions. In simpler words, all transactions involving the said datasource must be XA transactions, or the datasource must be an XA datasource without any support for local transactions.
Note that merely specifiying a JTA data source is not sufficient. You must define the persistence unit as one requiring the use of JTA entity managers, as an undefined value for the transaction-type attribute, depends on the environment in which the JPA provider operates. If the provider operates in a Java EE environment, JTA entity managers will be created, where as RESOURCE_LOCAL entity managers will be created in a Java SE environment.
Also, note that, if you specify the transaction-type as RESOURCE_LOCAL, then in a Java EE environment, the JPA provider will ignore the jta-data-source value, and will instead rely on the non-jta-data-source value for creating connections.

Related

Persistence Unit not started, when only using #Transactional

I am using Wildfly 10.1.0 and I am trying to change all the EJB's to only use #Transactional annotations, which are provided since Jave EE 7 (because of JTA 1.2). The thing is when my project has 0 EJB's, the PersistenceUnit is not started by the container. If I add an empty class with only the annotation #Stateless then it works again.
This is my persistence.xml
<persistence version="2.1">
<persistence-unit name="Storage-PU" transaction-type="JTA">
<jta-data-source>java:/PostGreDS</jta-data-source>
<class>SomeEntity<class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
</persistence-unit>
</persistence>
What is the reason why the PersistenceUnit is not started, when there are no EJB's available?
What is the reason why the PersistenceUnit is not started, when there are no EJB's available?
The reason is that in a JEE application the Persistence Context (including DB connection, Persistence Units and stuff) is started and managed by the EJB container:
So, just annotating beans methods at the Web tier with #Transactional is not enough to get Persistence Context started. Beware that transactions are also managed by the EJB container, not the Web Container.
See Java Platform, Enterprise Edition: The Java EE Tutorial for further details on JEE architecture.

StandAlone CDI + JTA Without JNDI

I am using CDI + DeltaSpike + Camel in a standalone app.
Here is my current setup :
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="primary" transaction-type="RESOURCE_LOCAL">
<shared-cache-mode>DISABLE_SELECTIVE</shared-cache-mode>
</persistence-unit>
Custom properties on EntityManagerFactoryProducer:
properties.put("hibernate.connection.provider_class", "org.example.HikariConnectionProvider");
I'm using DeltaSpike JPA Transaction with (https://deltaspike.apache.org/documentation/jpa.html):
org.apache.deltaspike.jpa.api.transaction.TransactionScoped;
org.apache.deltaspike.jpa.api.transaction.Transactional;
I would like to use Infinispan to sync my app caches.
According to Infinispan doc:
"It is highly recommended that Hibernate is configured with JTA transactions"
How can I use JTA transactions ?
I tried to change "RESOURCE_LOCAL" to "JTA" but I don't understand what am I supposed to configure for :
hibernate.transaction.factory_class
hibernate.transaction.jta.platform
I am not using JNDI, and I am not in an application server.
Also, I would like to use #javax.transaction.Transactional instead of DeltaSpike.
Essentially, you are asking how to use most Java EE features without using a Java EE container.
Of course, there are JTA implementations like Atomikos you can embed in a "standalone" application.
On the other hand, it might be a lot easier to start with a full-blown Java EE environment and then ignore or exclude anything you don't need.
App servers are rather lightweight these days, and if a self-contained executable is a must-have for you, then have a look at WildFly Swarm or Payara Micro.

Understanding Persistence.xml in JPA

I am trying to understand the following things:
When I make an EJB project and deploys it to Glassfish do I set up JDBC resources/connection pools at the administrator center of Glassfish or do I add all the different properites for username, password etc in the persistence.xml? I don't understand one bit of that.
I do not understand why we have both JDBC resource and JDBC Connection pool either. What is it and what is the difference between them? Could somebody explain me these things or/and provide some good link about the persistence.xml file and the part around it?
It's better to define a JDBC resource rather than putting the information in the persistence.xml. In this way you are going to take advantage of connection pooling. You are going to define the JNDI name you provided for the JDBC resource in the persistence.xml.
What is it and what is the difference between them
Below I pasted some parts of the Glassfish 3.x help. Check it out. It's really helpful
JDBC connection pool
A JDBC connection pool contains a group of JDBC connections that are created when the connection pool is registered
JDBC resource
A Java DataBase Connectivity (JDBC) resource (data source) provides applications with the means of connecting to a database. Typically, the administrator creates a JDBC resource for each database accessed by the applications deployed in a domain; however, more than one JDBC resource can be created for a database.
Applications get a database connection from a connection pool by looking up a data source on the Java Naming and Directory Interface (JNDI) API tree and then requesting a connection. The connection pool associated with the data source provides the connection to the application.
Think of the data source(JDBC) resource as a factory for a facade of some type of data service(Connection Pool). In this case it implicitly gets a connection from the pool and provides it to your application.
An example persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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">
<persistence-unit name="WebApplication2PU" transaction-type="JTA">
<jta-data-source>jdbc/sample</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
This line is the JNDI name I gave to my JDBC resourse:
<jta-data-source>jdbc/sample</jta-data-source>
You dont need to define anything related to the database connection in your persistence.xml this way...just the JNDI name of the resource
When you configure a data source in your application server, all you need to set in persistence.xml is the JNDI name of that data source.
I found this in the book that I read to learn Spring and Hibernate. The book name is Professional Java for Web Applications written by Nicholas S. Williams. I think this will be helpful for many people.
Creating the Persistence Configuration:
To use the entities you create, you must define a persistence unit. Doing so is simple. Create a
persistence.xml file not dissimilar from a deployment descriptor, but with far fewer options
to worry about. The root element of a persistence configuration file is <persistence>. This
element may contain one or more <persistence-unit> elements. No other elements are
within <persistence>. <persistence-unit> has two attributes: name specifies the name of
the persistence unit and transaction-type indicates whether this persistence unit uses Java
Transaction API (JTA) transactions or standard local transactions.
You must specify a name, which is how you locate the persistence unit in code. If not specified,
transaction-type defaults to JTA in a Java EE application server and RESOURCE_LOCAL in a Java
SE environment or simple Servlet container. However, to prevent unexpected behavior it’s best to
always set this value explicitly instead of relying on a default value.
<persistence-unit> contains the following inner elements. None of them are required (so
<persistence-unit> may be empty); however, you must specify whichever elements you use in the
following order:
<description> contains a useful description for this persistence unit. Although it makes
reading the persistence file easier, it has no semantic value.
<provider> specifies the fully qualified class name of the javax.persistence.spi
.PersistenceProvider implementation used for this persistence unit. By default, when you
look up the persistence unit, the API will use the first JPA provider on the classpath. You
can include this element to mandate a specific JPA provider.
You can use either <jta-data-source> or <non-jta-data-source> (but not both) to
use a JNDI DataSource resource. You may use <jta-data-source> only if
transaction-type is JTA; likewise you may use <non-jta-data-source> only
if transaction-type is RESOURCE_LOCAL. Specifying a DataSource causes the persistence
unit to use that DataSource for all entity operations.
<mapping-file> specifies the classpath-relative path to an XML mapping file. If you don’t
specify any <mapping-file>, the provider looks for orm.xml. You may specify multiple
<mapping-file> elements to use multiple mapping files.
You can use one or more <jar-file> elements to specify a JAR file or JAR files that the
JPA provider should scan for mapping-annotated entities. Any #Entity, #Embeddable,
#javax.persistence.MappedSuperclass, or #javax.persistence.Converter classes
found are added to the persistence unit.
You can use one or more <class> elements to indicate specific #Entity, #Embeddable,
#MappedSuperclass, or #Converter classes that should be added to the persistence unit.
You must annotate the class or classes with JPA annotations.
Using <exclude-unlisted-classes /> or <exclude-unlisted-classes>true</exclude-unlisted-classes> indicates that the provider should ignore classes not
specified with <jar-file> or <class>. Omitting <exclude-unlisted-classes> or using
<exclude-unlisted-classes>false</exclude-unlisted-classes> causes the JPA
provider to scan the classpath location of the persistence file for JPA-annotated classes. If
persistence.xml is located in a JAR file, that JAR file (and only that JAR file) is scanned
for classes. If persistence.xml is located in a directory-based classpath location (such as /
WEB-INF/classes), that directory (and only that directory) is scanned for classes. Prior to
Hibernate 4.3.0 and Spring Framework 3.2.5, specifying this element with the value false
was incorrectly interpreted as true.
<shared-cache-mode> indicates how entities are cached in the persistence unit (if the JPA
provider supports caching, which is optional). NONE disables caching, whereas ALL enables
caching for all entities. ENABLE_SELECTIVE means that only entities annotated #javax
.persistence.Cacheable or #Cacheable(true) (or marked as cacheable in orm.xml)
are cached. DISABLE_SELECTIVE results in caching of all entities except those annotated
#Cacheable(false) (or marked as non-cacheable in orm.xml). The default value,
UNSPECIFIED, means that the JPA provider decides what the effective default is. Hibernate
ORM defaults to ENABLE_SELECTIVE, but relying on this is not portable.
<validation-mode> indicates if and how Bean Validation should be applied to entities.
NONE means that Bean Validation is not enabled, whereas CALLBACK makes the provider
validate all entities on insert, update, and delete. AUTO has an effective value of CALLBACK
if a Bean Validation provider exists on the classpath and an effective value of NONE if no
Bean Validation provider exists on the classpath. If you enable validation, the JPA provider
configures a new Validator to validate your entities. If you have configured a special
Spring Framework Validator with your custom localized error codes, the JPA provider
ignores it. As such, it’s best to set the validation mode to NONE and use Bean Validation
before your persistence layer is invoked.
<properties> provides a way to specify other JPA properties, including standard JPA
properties (such as JDBC connection string, username, and password, or schema generation
settings) as well as provider-specific properties (such as Hibernate settings). You specify
one or more properties using nested elements, each with a name and value
attribute.
Nicholas S. Williams, Professional Java for Web Applications, (Indianapolis, Indiana: John Wiley & Sons, Inc., 2014), pg 584-585

How to use JTA support in Tomcat 6 for Hibernate?

They recommend using JTA transaction support in Java EE environment.
But how to configure JTA in Tomcat6 so that Hibernate Session could use it ?
Starting with version 3.0.1, Hibernate added the SessionFactory.getCurrentSession() method. Initially, this assumed usage of JTA transactions, where the JTA transaction defined both the scope and context of a current session. Given the maturity of the numerous stand-alone JTA TransactionManager implementations, most, if not all, applications should be using JTA transaction management, whether or not they are deployed into a J2EE container. Based on that, the JTA-based contextual sessions are all you need to use.
(Hibernate Reference Documentation | Architecture. Contextual Sessions)
If you want JTA support in Tomcat you'll need to use a standalone transaction manager like Atomikos, JOTM, Bitronix, SimpleJTA, JBossTS or GeronimoTM/Jencks. But honestly, if you're not going to handle transactions across multiple resources, then you can live without JTA (and if you really need JTA, use a full blown application server).
If you just want to use SessionFactory.getCurrentSession() you can just add the following two lines to your hibernate.cfg.xml:
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="hibernate.current_session_context_class">thread</property>
This will give you a unique Session for each thread. As a servlet request is always handled within one thread (given that your code doesn't spawn new ones), the Session will live for the whole request.
Don't forget to use a filter to close the Session after the request!

Persistence unit as RESOURCE_LOCAL or JTA?

I have queries as below:
What is the difference of these two?
Are both of these supported by all databases?
Are JPA TransactionManager and JTA TransactionManager different?
JPA implementations have the choice of managing transactions themselves (RESOURCE_LOCAL), or having them managed by the application server's JTA implementation.
In most cases, RESOURCE_LOCAL is fine. This would use basic JDBC-level transactions. The downside is that the transaction is local to the JPA persistence unit, so if you want a transaction that spans multiple persistence units (or other databases), then RESOURCE_LOCAL may not be good enough.
JTA is also used for managing transactions across systems like JMS and JCA, but that's fairly exotic usage for most of us.
To use JTA, you need support for it in your application server, and also support from the JDBC driver.
As an addition to other answers
Here is an excerpt from the extremely useful article (published on the Apache TomEE website), which can also help answer the OP's first question (the link to the article is below).
Comparing RESOURCE_LOCAL and JTA persistence
contexts
With <persistence-unit
transaction-type="RESOURCE_LOCAL">
YOU are responsible for EntityManager
(PersistenceContext/Cache) creating and tracking...
You must use the
EntityManagerFactory to get an EntityManager
The resulting EntityManager instance
is a PersistenceContext/Cache An
EntityManagerFactory can be injected via the
#PersistenceUnit annotation only (not
#PersistenceContext) You are not allowed to
use #PersistenceContext to refer to a unit of type RESOURCE_LOCAL
You must use the
EntityTransaction API to begin/commit around
every call to your EntityManger Calling
entityManagerFactory.createEntityManager() twice results in
two separate EntityManager instances and therefor
two separate PersistenceContexts/Caches. It
is almost never a good idea to have more than one
instance of an EntityManager in use (don't create a
second one unless you've destroyed the first)
With <persistence-unit
transaction-type="JTA"> the
CONTAINER will do EntityManager
(PersistenceContext/Cache) creating and tracking...
You cannot use the
EntityManagerFactory to get an EntityManager
You can only get an EntityManager supplied by the
container An EntityManager
can be injected via the #PersistenceContext
annotation only (not #PersistenceUnit) You are
not allowed to use #PersistenceUnit to refer to a
unit of type JTA The EntityManager given by
the container is a reference to the
PersistenceContext/Cache associated with a JTA Transaction.
If no JTA transaction is in progress, the EntityManager
cannot be used because there is no
PersistenceContext/Cache. Everyone with an EntityManager
reference to the same unit in the same
transaction will automatically have a reference to the
same PersistenceContext/Cache The
PersistenceContext/Cache is flushed and cleared at
JTA commit time
Anyone interested in learning the Java Persistence API - please do yourself a favor and read the full article here: JPA Concepts: JPA 101.
Resource_Local and JTA are transaction managers (methods of doing transactions). This is not the property of database but the component responsible for coordinating transactions. JPA and JTA transaction managers are different. JPA transaction manager is responsible for JPA transactions and you want to use one if you are only doing JPA transaction. JTA transaction manager is general purpose transaction manager and can enlist other resources such as JMS queues in transaction. Typically Java EE containers employ a JTA transaction manager for EJBs, JPA entities, etc.
resource_local vs JTA its about local transaction vs global transaction. It's about can we manage multiple resources under a single transaction.
CMT vs BMT its about who is opening and closing transaction - application developer or application server.

Categories

Resources