Setting Up a Data Source in Payara Micro

Photo of Jonathan Coustick by Jonathan Coustick

Having previously blogged about setting up data sources in Payara Server, we thought we should mention that you can also set up data sources in Payara Micro. In this blog, we'll take you through the process of setting up a data source using Payara Micro, including code snippets and where to find full code examples. Let's get started!

 

First, to use a database as a data source in Payara Micro, you'll need to have the database already running. Once you have that in place,  download the JDBC driver for the database and put it into your WEB-INF/lib directory.

 

In your web.xml add the following:

<data-source>
<name>java:global/ExampleDataSource</name>
<class-name>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</class-name>
<server-name>localhost</server-name>
<port-number>3306</port-number>
<database-name>mysql</database-name>
<user>root</user>
<password>root</password>
<!-- Example of how to use a Payara specific custom connection pool setting -->
<property>
<name>fish.payara.sql-trace-listeners</name>
<value>com.sun.gjc.util.SQLTraceLogger</value>
</property>
</data-source>

The class name is the name of the data source class for your database.

For Oracle DB:

<class-name>oracle.jdbc.pool.OracleDataSource</class-name>

For PostgreSQL:

<class-name>org.postgresql.ds.PGSimpleDataSource</class-name>

 

The database name must also be changed to the name of the database you are using i.e. Oracle or PostgreSQL.

 

Edit the user, password, server name and port number to match your database installation.

 

Environment variables, system properties and aliases are supported in the web.xml, so for example, instead of specifying localhost as the server name you could do the following:

<server-name>${server.name}</server-name>

 

These can be supplied to Payara Micro when starting it as -Dserver.name=localhost.

 

To use it in your code just use the following:

@Resource(name=”java:global/ExampleDataSource”)

DataSource ds;

A complete example is available on Github at: https://github.com/payara/Payara-Examples/tree/master/Payara-Micro/datasource-example

Why not give it a try? Payara Micro is the microservices-ready version of Payara Server. Less than 70MB in size, it requires no installation or configuration and no need for code rewrites – so you can build and deploy a fully working app within minutes.

 

Download Payara Micro

 Download Payara Micro 

 

 

Comments