configure Hibernate to use a renamed persistence.xml - java

We have to rename persistence.xml to fool WebSphere 7 not to use its built-in OpenJPA.
It is pretty easy to do when you use Spring, you just instruct its entity manager factory to use another location for persistence.xml:
<property name="persistenceXmlLocation" value="META-INF/persistence-xxx.xml"/>
But now we want to use plain Hibernate/JPA without Spring, and couldn't find any way to specify the alternate persistence.xml location.
JPA2 spec doesn't say anything about it...
Any clues? Is it possible to instruct Hibernate to use a renamed persistence.xml?
======
It appears that it is NOT POSSIBLE to make Hibernate read a renamed persistence.xml file.
And not necessary in my case.

As far as I know, it's not possible to change the location of the persistence.xml file.
Also take a look at this document: Alternate JPA Providers in WebSphere Application Server, it seems like you should be able to use Hibernate as JPA provider by specifying it in the persistence.xml file, and embedding the required jars in your application.
Make sure your persistence.xml is specifying Hibernate as JPA provider:
<persistence>
<persistence-unit name="myapp">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
You should also be able to achieve this by creating a shared library and using it to configure WebSphere to use an alternative persistence provider.
Here you can find how to do it: Configuring the Java Persistence API (JPA) default persistence provider
EDIT
Given the information in the comments in this answer, it seems the problem can be solved by adding these properties in persistence.xml, as indicated in this post Websphere EntityManagerFactory creation problem:
<property name="hibernate.transaction.manager_lookup_class"
value="org.hibernate.transaction.WebSphereExtendedJTATransactionLookup" />
<property name="hibernate.transaction.factory_class"
value="org.hibernate.transaction.CMTTransactionFactory" />
This same information is also provided in the Alternate JPA Providers in WebSphere Application Server document.

the persistence.xml should exist in a META-INF directory, usually packaged alongside a jar file that contains your entity classes. What I do is I have the entity clases in a seperate project under eclipse, with a META-INF directory that contains the persistence.xml, package this a jar file, and include it in the applications project dependencies (ie. WEB-INF/lib), or, deploy it straight to the app server.

Related

db.properties vs persistence.xml which one is better?

Recently I started a maven project to build an application for integrating
Spring, JPA, JSF
But in the automatically generated folder structure I can see one file named as
db.properties
and also I have one
persistence.xml
Now my question is that Database connection can be defined in either of these files, Can anybody tell me
1. Which way is better and why ?
2. Why there is db.properties file automatically generated while I already have persistence.xml ?
db.properties file is like messages.properties which is used to define key value pair. And after that we will use keys in expression language. So configurations will only be done in
persistence.xml or dataSource.xml
whichever is preferred choice but the values we will take from db.properties in the form of expression language eg.
driverClassName=com.mysql.jdbc.Driver
this is an entry in your db.properties. and you will use it in persistence.xml as follows.
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driverClassName}" />
I assume, from the fact that you mention JSF, that you are building a web application for deployment to an application server. I also caveat this question in that I don't know about db.properties or where it comes from.
When deploying to an application server, it is always best to configure your database connections in the container and expose them to the application via JNDI. This allows the container to manage connection pooling and credentials and keeps this information out of your WAR/EAR files. It also ensures that your WAR/EAR files are agnostic to the particular database instance, so can be deployed to a container in any environment without modification.
Therefore, I recommend against configuring your datasource in persistence.xml.
See also Difference between configuring data source in persistence.xml and in spring configuration files which is a similar question- the accepted answer there expresses the solution in more detail.

Where to set EclipseLink properties using Glassfish if not set in persistence.xml

Is there a way to set the EclipseLink properties (e.g. target database) in a place different from persistence.xml?
Rational: I have a JPA module defining the data structure and containing persistence.xml. The module might be used with different target databases. In a Java SE application one can set the eclipse link properties programmatically upon creation of EntityManagerFactory. However, when the JPA module is packaged in an EAR for the Glassfish application server the target database must be defined in persistence.xml ... or is there another way?
You can use a RESOURCE_LOCAL persistence unit and access it the same way through EntityManagerFactory.

Glassfish 3 with JPA configuration

I have use JPA with Hibernate in a standalone application but now I want to try with with an application server. I know GlassFish provides EclipseLink implementation for JPA but I have a few questions.
Do I need to specify in persistence.xml EclipseLink as a provider for my persistence-unit?
Does persistence.xml look the same as if it the application would not be deployed? If it does not look the same how does it look?
Do I need to specifically download the implementation jars for EclipseLink and build with them or does the container handles this after my application is deployed?
How do I specify the jdbc driver in persistence.xml?
Does my application need to be deployed as a .ear?
You don't need to specify the persistence provider, by default the one contained in your application server will be used (if it has at least the Web profile, of course, otherwise servers such as Tomcat won't provide you EclipseLink).
Yes, it will have the same look (in both applications you are just using JPA the same way).
For your code to compile, you will only need to have persistence-api.jar in your classpath (if you use Maven, set the scope to "provided"). Then the server will automatically provide its implementation jars.
You could use a persistence unit like described in this page ("typical configuration in a Java SE environment"). But I would rather suggest you use a <jta-data-source> instead, that refers to a datasource provided by GlassFish.
As far as I can tell, it can also be a WAR file, I didn't have any problem deploying it (webapp as a Maven WAR module + beans in a JAR module).

Spring-hibernate jpa and jboss - Saving objects to a second database

Note: Although at first similar, this is not a duplicate of Using Spring, JPA with Hibernate to access multiple databases/datasources configured in Jboss
Dear Stackoverflow,
I had a spring-jpa with hibernate application running on jboss-4.2.1.GA and using a single database.
I now have a second spring-hibernate project bundled up in the same ear file with the project described above but it needs to use a second database. This second hibernate/spring project is set up with the database.properties and hibernate.cfg.xml files.
The two databases details are stored on jboss oracle-ds.xml file:
<datasources>
<local-tx-datasource>
<jndi-name>DefaultDS</jndi-name>
...
</local-tx-datasource>
<local-tx-datasource>
<jndi-name>SecondDS</jndi-name>
...
</local-tx-datasource>
</datasources>
My question is, in the second project, with objects for the second database and not the first one, how can I call sessionFactory for the second database whose details are stored on the oracle-ds.xml instead of using database.properties files?
I have seen an example calling
#Resource(mappedName = "java:SecondDS")
private DataSource secondDS;
...
java.sql.Connection conn = secondDS.getConnection();
If it is that easy to obtain a connection, that is only useful for prepared statements, how can I in get hold of the sessionFactory? Is there a similar approach?
All examples I have seen refer to database.properties and not the jboss ds.xml file.
Thanks in advance
There is several solution, depending on how you bind the data source to a presistance context, Spring way, JPA way or Hibernate way....
Spring
To link spring/hibernate application to JNDI data source, you will need to use JndiObjectFactoryBean
<bean id="serverDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/blah"/>
<property name="proxyInterface" value="javax.sql.DataSource"></property>
</bean>
This way you have a spring bean representing the JNDI data source. You will need to create 2 of them (one for each of you data source). They you need to inject the data source in your spring defined SessionFactory. The same can be use if you use Spring managed JPA entity manager.
JPA
If you are using JPA (session factory is hibernate not jpa...) you can also defined a jndi data source name in the corresponding persistance.xml file.
<persistence-unit name="sample">
<jta-data-source>java:/DefaultDS</jta-data-source>
...
</persistence-unit>
You need to use unitName parameter when injecting the entityManager:
#PersistenceContext(unitName="sample")
Hibernate
For hibernate.cfg.xml file you can specify the JNDI data source with this property
<property name="connection.datasource">java:/comp/env/jdbc/MyDB</property>
The database.property should be removed to be sure the jndi data source is used.
These are only example, the final result will depend on how you made your plumbing.

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

Categories

Resources