Saturday, April 27, 2013

How to test a newly setup JPA project

  3. Testing the JPA project 

The purpose of this post is to show how to test a JPA project whether it is properly setup.
Besides, this solution can be used to test a newly created/generated entity as well.

The concept is quite simple, simply create a java class with main(String[] args), in the main method, create database connection and then execute a select statement.
If successfully select records from database, that's mean the JPA project is properly setup.

1. Create a new package called test in the project.
2. Create a new class called JpaTest in the test package.
3. Write the following codes in the main(String[] args) to test.
    factory = Persistence.createEntityManagerFactory("HelloJPA");
    EntityManager em = factory.createEntityManager();
    Query q = em.createQuery("select a from Ofuser a");
    List<Ofuser> users = q.getResultList();   

    System.out.println("Number of users: " + users.size());
    if(users.size() > 0) {
        for (Ofuser user : users) {

4. Change the entity (Ofuser) in the codes above to any entity in the JPA project.
5. R-click > Run As... > Java application.
6. If any number of records return, that's meaning the JPA project is properly setup.
    otherwise, there could be showing exceptions in the console.



Related Posts Plugin for WordPress, Blogger...