Tutorials/howto jpa

= How to use JPA =

Note: This page is relevant for Firebase 1.9 or greater.

Requirements
You need to know have a basic understanding of Firebase, JPA and DataSources to understand this page.

Deploy Data Source
In order for any JPA unit to work you need a data source. In Firebase you deploy data sources with XML files in "game/deploy". Details on the XML format and properties can be found in the development reference, but here is an example of a data source file:

<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> com.mysql.jdbc.Driver jdbc:mysql://localhost/test1 password1 user1

The name of this data source file is important for Firebase to recognize what it is. It must end with "-ds.xml", and Firebase will refer to whatever came before "-ds.xml" as the name of the data source. If you name the file "testdata-ds.xml", within Firebase it will be known as "testdata". And so, if you deploy this file...

game/deploy/game-data-ds.xml

... Firebase will refer to it as simply "game-data". Similarly, the JNDI context location of the above data source will be:

java:comp/env/jdbc/game-data

Copy Driver
In order for database drivers to work properly they often need to be included in the top most class loader. In Firebase this means copying the driver JAR file to "lib/common". If you are running Firebase as a stand-alone server this is straight forward. If you're developing and use Maven to run Firebase you can copy the driver JAR to "src/test/resources/firebase/lib/common" and it will be included in the runtime.

Configure JPA
Configuring JPA should now be straightforward given the name, and JNDI path, of the deployed data source. For example, if we asume MySQL and Hibernate and the name of the data source from above, a JPA deployment descriptor might look like this:

  org.hibernate.ejb.HibernatePersistence java:comp/env/jdbc/game-data   

Note that the data source is pointed to using a JNDI context path which ends with the name of the file it was deployed in. You can include this file in any JAR used in a game, service or tournament as it will be searched for via the class loaders.

Use JPA
You should now be able to use JPA as normal. For example, to get the above entity manager factory in the "init" method of a game, it might look like this:

public void init(GameContext con) { EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("game-entities"); [...] }

Enjoy!