Monday, November 05, 2007

JPA Code Examples

So here are the goodies:

first you need to make your persistence.xml file look kind of like this:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="" xmlns:xsi="" version="1.0" xsi:schemalocation="">
<persistence-unit name="TestJPA">
<property name="hibernate.connection.driver_class" value=""></property>
<property name="hibernate.connection.url" value="jdbc:mysql://serverName/dbName"></property>
<property name="hibernate.connection.username" value="webUser"></property>
<property name="hibernate.connection.password" value="myPassword"></property>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"></property>


Notice the properties section and the lack of jta-data-source tag, this will create a problem if you want to use this persistence file to deploy to the app server.

Your Entities won't need to change, they'll work the same. 

Your Junit tests can be configured lots of ways but this is how I did mine:

public class TestUsers extends TestCase {
private EntityManagerFactory emf;
private EntityManager em;
protected void setUp() throws Exception {
emf = Persistence.createEntityManagerFactory("TestJPA");
em = emf.createEntityManager();
public void testRetrieveUsers(){

List<Users> users = null;
Query query = em.createQuery("Select u from Users u");
users = (List<Users>)query.getResultList();
} catch (Exception e){
for (Users u : users){
System.out.println("returning: " + users.size() + " users");

That is it in a nutshell, I'm surprised that this isn't documented somewhere better but here it is for your testing enjoyment... So don't give me any excuses test that code!

No comments: