Use JPA In Code
Contents
On WildFly, a datasource really means a datasource. It contains a connection pool and the JNDI name is just another property. The JNDI name is used by the application to reference the DataSource. In WildFly, you need to append the prefix java:/
or java:jboss/
, resulting in java:/datasources/mysqlDSs
or java:jboss/datasources/mysqlDS
respectively.
Resource injection enables you to inject any resource available in the JNDI namespace into any container-managed object, such as a servlet, an enterprise bean, or a managed bean. For eg, we can use resource injection to inject DataSource connectors, or any other desired resources available in the JNDI namespace. Applications that use the Persistence API specify the DataSource object they are using in the jta-data-source element of the persistence.xml file. The persistence unit is given a name so that the application can use multiple if needed. If only one is defined, JPA will automatically use it. The persistence unit references the DataSource:
JPA allows us to configure the JPA provider specific properties. Here we tell Hibernate to automatically create any needed tables when the application starts (and drop them when the application is stopped).
<?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="myPU" transaction-type="JTA">
<jta-data-source>java:jboss/datasources/mysqlDS</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
</properties>
</persistence-unit>
</persistence>
In application code, you would specify the DataSource as a Resource. See the corresponding annotation in an EJB here:
@Resource(name = "java:jboss/datasources/mysqlDS") DataSource dataSource;
Full example:
@Stateless public class EmployeeBean implements EmployeeServiceLocal, EmployeeServiceRemote { @PersistenceContext private EntityManager em; @Resource(mappedName="java:/jboss/datasources/mysqlDS") DataSource dataSource; public void doAction(){ PreparedStatement ps = null; Connection con = null; try { con = dataSource.getConnection(); System.out.println("Creating table PAYMENT..."); ps = con.prepareStatement("drop TABLE PAYMENT"); ps.execute(); ps = con.prepareStatement("CREATE TABLE PAYMENT ( " + "CUSTOMER_ID INT, " + "AMOUNT DECIMAL (8,2), " + "TYPE CHAR (10), " + "CHECK_BAR_CODE CHAR (50), " + "CHECK_NUMBER INTEGER, " + "CREDIT_NUMBER CHAR (20), " + "CREDIT_EXP_DATE DATE" + ")"); ps.execute(); System.out.println("...done!"); } catch (SQLException sql) { throw new EJBException(sql); } finally { try { if (ps != null) ps.close(); } catch (Exception e) {} try { if (con != null) con.close(); } catch (Exception e) {} } }