Sathya Elangovan
Sathya Elangovan

Reputation: 163

JPA2 in liberty 18.0.0.3 using MySQL database

I'm new to JPA and Liberty. Could anyone please explain how to relate/link the server.xml, web.xml and persistence.xml configuration to set up the database connection? your help on this is much appreciated.

Upvotes: 1

Views: 306

Answers (2)

njr
njr

Reputation: 3484

In Liberty, you define the location of the JDBC driver jar files and configure a dataSource element with a JNDI name. This knowledge center page contains an example for MySQL,

https://www.ibm.com/support/knowledgecenter/en/SSEQTP_liberty/com.ibm.websphere.wlp.doc/ae/twlp_dep_configuring_ds.html

Directly quoting from the above page,

<dataSource id="DefaultDataSource" jndiName="jdbc/mySQL">
<jdbcDriver libraryRef="MySQLLib"/>
    <properties databaseName="SAMPLEDB" serverName="localhost" portNumber="3306"/>
</dataSource>

<library id="MySQLLib">
    <file name="C:/mysql-connector-java-x.x.xx/mysql-connector-java-x.x.xx.jar"/>
</library>

After this, you can configure the jta-data-source element in your persistence.xml pointing at the JNDI name that you chose. For example,

...
<persistence-unit name="ExamplePersistenceUnit">
  <jta-data-source>jdbc/mySQL</jta-data-source>
</persistence-unit>

The above is sufficient to get it working, without involving web.xml. The deployment descriptor (web.xml) gives you the option of adding a level of indirection/mapping and the ability to configure some additional settings such as shareability and container vs application authentication. You can do this by defining a resource reference in web.xml pointing to the data source. Resource references have names in java:comp/env, java:module/env, java:app/env or java:global/env that reflect their visibility. I'll use java:module in the following example, meaning that the reference we are defining is only visibility within the same module (the web module that provides the web.xml),

<resource-ref>
  <res-ref-name>java:module/env/jdbc/mySQLRef</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
  <res-sharing-scope>Shareable</res-sharing-scope>
  <lookup-name>jdbc/mySQL</lookup-name>
</resource-ref>

After defining the resource reference above, the data source continues to be available at the JNDI name specified in server.xml, but also becomes available via the JNDI name of the resource reference, meaning you could alternately specify,

  <jta-data-source>java:module/env/jdbc/mySQLRef</jta-data-source>

Deployment descriptors can also do some more advanced things like defining a data source in place of the server config. However, to keep this answer simple, I've skipped over that possibility.

Upvotes: 2

F Rowe
F Rowe

Reputation: 2064

This IBM KnowledgeCenter topic is a good place to start

Upvotes: 0

Related Questions