Search code examples
hibernatejpadatasourcejndijta

How to correctly use LocalContainerEntityManagerFactoryBean with JPA


I downloaded a sample app which uses Hibernate and JPA the issue is the persistence unit. It seems I can use either <persistence-unit name="hibernatePersistenceUnit" transaction-type="RESOURCE_LOCAL"> or <persistence-unit name="hibernatePersistenceUnit" transaction-type="JTA"> from my research I found that if I use the first I also have to specify <non-jta-data-source> and with the second <jta-data-source> (I think that is right but correct me if I am wrong)

I think the first one implies that the url,driver,user, pwd will be configured within the web-app. And the second one will look for the source via JNDI in the container (Again correct me if I wrong) But the value which I need to specify for that property is my stumbling block. I have seen jdbc:sampleDS, java:sampleDS. (Are these also jndi lookups? Haven't seen jndi:sampleDS) So should it be jdbc: or java: or jndi: and are these all "JNDI"?

And the "sampleDS" what does that name actually refer to? In other words does it refer to a bean name (I am using spring and my bean which configures the datasource information is called jpaDataSource) if I use resource_local or does it refer to a jndi resource somewhere on the application server, JBOSS for instance, or something else I am not aware of?


Solution

  • RESOURCE_LOCAL you use if you don't need global transactions (transaction spanning multiple persistence units i.e. databases) or JNDI defined datasources, if you need global transactions you must use JTA which in turn requires that you use JNDI datasources as they reside within the application server which is the one that can handle global transactions.

    JNDI datasources are configured in the application server - in case of JBOSS either in the configuration/standalone.xml or with *-ds.xml files in the deployments folder.

    java:sampleDS is a JNDI name, example mssql-ds.xml file:

    <?xml version="1.0" encoding="UTF-8"?> 
    <datasources>
      <datasource jndi-name="java:jboss/datasources/myDatabase" pool-name="myDatabase" enabled="true" jta="true" use-java-context="true" use-ccm="true">
        <connection-url>
            jdbc:sqlserver://localhost;databaseName=myDatabase
        </connection-url>
        <driver>
            sqljdbc
        </driver>
        <security>
            <user-name>
                myusername
            </user-name>
            <password>
                mypassword
            </password>
        </security>
      </datasource>
    <datasources>