Port of schuchert.wikispaces.com


TestPage3

TestPage3

title: Tutorial_2_The_Queries —

Queries

In these example, the variable “em” is an entity manger initialized just like it was in the first tutorial.

Empty String

Setup: None required

em.createQuery(""); 

Unknown Class

Setup: None required

em.createQuery("from IncorrectClassName"); 

Minimal “Get All”

Setup: None required

em.createQuery("from Person").getResultList(); 

Successfully Get a Single Object

Setup: Insert exactly 1 Person entity in the database

final Person p = (Person) em.createQuery("from Person").getSingleResult(); 

Unsuccessfully Try to get a Single Object When There Are None

Setup: Make sure there are no Person entities in the database

 em.createQuery("from Person").getSingleResult(); 

Unsuccessfully Try to get a Single Object With Too Many

Setup: Insert two or more Person entities in the database

em.createQuery("from Person").getSingleResult(); 

Find By Primary Key

Setup: Insert a Person in the database, make sure to get the key of the object inserted

final Person p = em.find(Person.class, personKey);

Unsuccessfully Find by Primary Key

Setup: None required

final Person p = em.find(Person.class, -42);

Search Using Query Parameter and Storing Result as List<?>

Setup: Insert one person record where the Person’s first name = “Brett”.

    final List<?> list = em.createQuery("from Person where p.firstName = ?1")
        .setParameter(1, "Brett").getResultList();

Search Using Query Parameter and Storing Result as List

Setup: Insert one person record where the Person’s first name = “Brett”.

    final List<Person> list = em.createQuery(
        "from Person where firstName = ?1").setParameter(1, "Brett")
        .getResultList();

Do Find by Primary Key and Queries Return == Objects

Setup: Insert one person record and store the primary key. Also make sure the first name of the person equals “Brett”.

    final Person pByKey = em.find(Person.class, personKey);

    final Person pByWhere = (Person) em.createQuery(
        "SELECT p from Person p where firstName='Brett'")
        .getSingleResult();

Use Wrong Class Name

Setup: None required

em.createQuery("from PERSON").getSingleResult(); 

Use Wrong Field Name

Setup: None required

em.createQuery("from Person p where p.FirstName='Brett'"); 

Use Column Name Instead of Field Name

Setup: None required, but maybe insert a single person whose first name = “Brett”.

 em.createQuery("from Person p where p.firstName='Brett'").getResultList(); 

Use a Parameter but Provide Wrong Index

Setup: None required

 em.createQuery("from Person p where p.firstName=?1").setParameter(0, "Brett"); 

Set Parameter Where There are None: Version 1

Setup: None required

 em.createQuery("from Person p where p.firstName='Brett'").setParameter(1, "Brett"); 

Set Parameter When There Are None: Version 2

Setup: None required

 em.createQuery("from Person p where p.firstName='?1'").setParameter(1, "Brett"); 

title: Tutorial_2_The_First_Example —

Test Setup

We have a bit of setup/initialization code we need to do before we can get started. We have seen all of this code before in Tutorial 1. The difference here is that we are going to work though some refactorings to get to where we were in tutorial 1. Here are the various parts:

Configure the Logger

    BasicConfigurator.configure();
    Logger.getLogger("org").setLevel(Level.ERROR);

Create the Entity Manager Factory

    final EntityManagerFactory emf = Persistence
        .createEntityManagerFactory("examplePersistenceUnit");

Create the Entity Manager

    final EntityManager em = emf.createEntityManager();

Create Entities

    final Address a1 = new Address("A Rd.", "", "Dallas", "TX", "75001");
    final Person p1 = new Person("Brett", 'L', "Schuchert", a1);

    final Address a2 = new Address("B Rd.", "S2", "OkC", "OK", "73116");
    final Person p2 = new Person("FirstName" + System.currentTimeMillis(),
        'K', "LastName", a2);

Use the Entity Manager

    em.getTransaction().begin();
    em.persist(p1);
    em.persist(p2);
    em.flush();

Perform a Query and Verify it Works

    final int numberFound = em.createQuery("Select p from Person p")
        .getResultList().size();
    assertEquals(2, numberFound);

The Whole Thing

Here’s all of this put together. Note that we’re going to refactor this heavily coming up.

package entity;

import static org.junit.Assert.assertEquals;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.Test;

public class JpaApiTests {

    @Test
    public void example1InsertTwoPeople() {
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ERROR);

        final EntityManagerFactory emf = Persistence
                .createEntityManagerFactory("examplePersistenceUnit");
        final EntityManager em = emf.createEntityManager();

        final Address a1 = new Address("A Rd.", "", "Dallas", "TX", "75001");
        final Person p1 = new Person("Brett", 'L', "Schuchert", a1);

        final Address a2 = new Address("B Rd.", "S2", "OkC", "OK", "73116");
        final Person p2 = new Person("FirstName" + System.currentTimeMillis(),
                'K', "LastName", a2);

        em.getTransaction().begin();
        em.persist(p1);
        em.persist(p2);
        em.flush();

        final int numberFound = em.createQuery("Select p from Person p")
                .getResultList().size();
        assertEquals(2, numberFound);
    }
}

Get it Running

After creating your Test Class, verify that it runs and that this test passes:

  • Right-click anywhere in your class’ editor pane.
  • Select Run As:JUnit Test

title: Tutorial_2_Second_Example — There are several things for which we need some support code:

  • Per test method setup
  • Per test method cleanup
  • One-time logger initialization
  • Inserting a single record

Before putting all of this together, let’s examine each of these things.

Per test method setup

public class JpaApiTests {
    private EntityManagerFactory emf;
    private EntityManager em;

    @Before
    public void initEmfAndEm() {
        emf = Persistence.createEntityManagerFactory("examplePersistenceUnit");
        em = emf.createEntityManager();
    }
}

This creates two fields. We then use the JUnit 4 @Before annotation to initialize that before the execution of each individual unit test. For details, please see here.

Per test method cleanup

    @After
    public void closeEmfAndEm() {
        em.close();
        emf.close();
    }

This example uses the JUnit 4 @After annotation to cleanup up resources we’ve allocation after the execution of each individual unit test. For details, please see here.

One-time logger initialization

    @BeforeClass
    public static void initializeLogging() {
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ERROR);
    }

This example uses the JUnit 4 @BeforeClass annotation to perform one-time initialization for the whole class. For details, please see here.

In this case, the first line in the method performs basic configuration of the Log4J logging system. The second line sets the default logging level for any class whose package starts with org to ERROR. This significantly reduces the output. It is possible to reduce the output one level further by setting it to FATAL.

Inserting a single record

    private int insertPerson() {
        final Address a1 = new Address("A Rd.", "", "Dallas", "TX", "75001");
        final Person p1 = new Person("Brett", 'L', "Schuchert", a1);

        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        em.persist(p1);
        return p1.getId();
    }

Rewrite and New Method

With these changes in hand, we can rewrite the previous test method as follows:

    @Test
    public void example1InsertTwoPeople() {
        insertPerson();
        insertPerson();

        final int numberFound = em.createQuery("Select p from Person p")
                .getResultList().size();
        assertEquals(2, numberFound);
    }

Here’s a second test to justify all of this refactoring.

    @Test
    public void example2() {
        final int primaryKey = insertPerson();
        final Person p = (Person) em.find(Person.class, primaryKey);
        assertNotNull(p);
    }

Putting it all Together

And finally, here’s all of the above changes together in one place.

package entity;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class JpaApiTests {
    private EntityManagerFactory emf;
    private EntityManager em;

    @BeforeClass
    public static void initializeLogging() {
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ERROR);
    }

    @Before
    public void initEmfAndEm() {
        emf = Persistence.createEntityManagerFactory("examplePersistenceUnit");
        em = emf.createEntityManager();
    }

    @After
    public void closeEmfAndEm() {
        em.close();
        emf.close();
    }

    @Test
    public void example1InsertTwoPeople() {
        insertPerson();
        insertPerson();

        final int numberFound = em.createQuery("Select p from Person p")
                .getResultList().size();
        assertEquals(2, numberFound);
    }

    @Test
    public void example2() {
        final int primaryKey = insertPerson();
        final Person p = (Person) em.find(Person.class, primaryKey);
        assertNotNull(p);
    }

    private int insertPerson() {
        final Address a1 = new Address("A Rd.", "", "Dallas", "TX", "75001");
        final Person p1 = new Person("Brett", 'L', "Schuchert", a1);

        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        em.persist(p1);
        return p1.getId();
    }
}

Comments

" Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.