Enterprise Java

Project Student: JPA Criteria Queries

This is part of Project Student. Other posts are Webservice Client With Jersey, Webservice Server with Jersey, Business Layer, Persistence with Spring Data, Sharding Integration Test Data and Webservice Integration.

We’ve covered basic CRUD operations but that doesn’t take us very far. Spring Data makes it easy to include basic searches but it’s important to have other standard options. One of the most important is JPA criteria queries.

A good introduction to this material is Spring Data JPA tutorial – JPA Criteria Queries [http://www.petrikainulainen.net].
 

Design Decisions

JPA criteria – I’m using JPA criteria searches instead of querydsl. I’ll come back to querydsl later.

Limitations

Violation of Encapsulation – this design requires breaking the architectural goal of making each layer completely unaware of the implementation details of the other layers. This is a very small violation – only the JPA specifications – and we still have to deal with pagination. Put those together and I feel it’s premature optimization to worry about this too much at this time.

Webservices – the webservice client and server are not updated. Again we still have to deal with pagination and anything we do now will have to be changed anyway.

Refactoring Prior Work

I have three changes to prior work.

findCoursesByTestRun()

I had defined the method:

List findCoursesByTestRun(TestRun testRun);

in the Course repository. That doesn’t have the intended effect. What I needed was

List findCoursesByTestRun_Uuid(String uuid);

with the appropriate changes to the calling code. Or you can just use the JPA criteria query discussed below.

FinderService and ManagerService

This comes from research on the Jumpstart site. The author splits the standard service interface into two pieces:

  • FinderService – read-only operations (searches)
  • ManagerService – read-write operations (create, update, delete)

This makes a lot of sense, e.g., it will be a lot easier to add behavior via AOP when we can operate at the class vs. method level. I’ve made the appropriate changes in the existing code.

FindBugs

I’ve fixed a number of issues identified by FindBugs.

Metadata

We begin by enabling access to metadata access to our persistent objects. This allows us to create queries that can be optimized by the JPA implementation.

import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;

@StaticMetamodel(Course.class)
public class Course_ {
    public static volatile SingularAttribute<Course, TestRun> testRun;
}

and

@StaticMetamodel(TestRun.class)
public class TestRun_ {
    public static volatile SingularAttribute<TestRun, String> uuid;
}

The name of the class is required due to convention over configuration.

Specifications

We can now create the query specification using the metadata now available. This is a slightly more complex query since we need to drill into the structure. (This shouldn’t require an actual join since the testrun uuid is used as the foreign key.)

public class CourseSpecifications {

    /**
     * Creates a specification used to find courses with the specified testUuid.
     * 
     * @param testRun
     * @return
     */
    public static Specification<Course> testRunIs(final TestRun testRun) {

        return new Specification<Course>() {
            @Override
            public Predicate toPredicate(Root<Course> courseRoot, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate p = null;
                if (testRun == null || testRun.getUuid() == null) {
                    p = cb.isNull(courseRoot.<Course_> get("testRun"));
                } else {
                    p = cb.equal(courseRoot.<Course_> get("testRun").<TestRun_> get("uuid"), testRun.getUuid());
                }
                return p;
            }
        };
    }
}

Some documentation suggests I could use get(Course_.testRun) instead of get(“testRun”) but eclipse was flagging it as a type violation on the get() method. Your mileage may vary.

Spring Data Repository

We must tell Spring Data that we’re using JPA Criteria queries. This is done by extending the JpaSpecificationExecutor interface.

@Repository
public interface CourseRepository extends JpaRepository<Course, Integer>,
        JpaSpecificationExecutor<Course> {

    Course findCourseByUuid(String uuid);

    List findCoursesByTestRunUuid(String uuid);
}

FinderService Implementation

We can now use the JPA specification in our service implementations. As mentioned above using the JPA Criteria Specification violates encapsulation.

import static com.invariantproperties.sandbox.student.specification.CourseSpecifications.testRunIs;

@Service
public class CourseFinderServiceImpl implements CourseFinderService {
    @Resource
    private CourseRepository courseRepository;

    /**
     * @see com.invariantproperties.sandbox.student.business.FinderService#
     *      count()
     */
    @Transactional(readOnly = true)
    @Override
    public long count() {
        return countByTestRun(null);
    }

    /**
     * @see com.invariantproperties.sandbox.student.business.FinderService#
     *      countByTestRun(com.invariantproperties.sandbox.student.domain.TestRun)
     */
    @Transactional(readOnly = true)
    @Override
    public long countByTestRun(TestRun testRun) {
        long count = 0;
        try {
            count = courseRepository.count(testRunIs(testRun));
        } catch (DataAccessException e) {
            if (!(e instanceof UnitTestException)) {
                log.info("internal error retrieving classroom count by " + testRun, e);
            }
            throw new PersistenceException("unable to count classrooms by " + testRun, e, 0);
        }

        return count;
    }

    /**
     * @see com.invariantproperties.sandbox.student.business.CourseFinderService#
     *      findAllCourses()
     */
    @Transactional(readOnly = true)
    @Override
    public List<Course> findAllCourses() {
        return findCoursesByTestRun(null);
    }

    /**
     * @see com.invariantproperties.sandbox.student.business.CourseFinderService#
     *      findCoursesByTestRun(java.lang.String)
     */
    @Transactional(readOnly = true)
    @Override
    public List<Course> findCoursesByTestRun(TestRun testRun) {
        List<Course> courses = null;

        try {
            courses = courseRepository.findAll(testRunIs(testRun));
        } catch (DataAccessException e) {
            if (!(e instanceof UnitTestException)) {
                log.info("error loading list of courses: " + e.getMessage(), e);
            }
            throw new PersistenceException("unable to get list of courses.", e);
        }

        return courses;
    }

    ....
}

Unit Testing

Our unit tests require a small change to use a Specification.

public class CourseFinderServiceImplTest {
    private final Class<Specification<Course>> sClass = null;

    @Test
    public void testCount() {
        final long expected = 3;

        final CourseRepository repository = Mockito.mock(CourseRepository.class);
        when(repository.count(any(sClass))).thenReturn(expected);

        final CourseFinderService service = new CourseFinderServiceImpl(repository);
        final long actual = service.count();

        assertEquals(expected, actual);
    }

    @Test
    public void testCountByTestRun() {
        final long expected = 3;
        final TestRun testRun = new TestRun();

        final CourseRepository repository = Mockito.mock(CourseRepository.class);
        when(repository.count(any(sClass))).thenReturn(expected);

        final CourseFinderService service = new CourseFinderServiceImpl(repository);
        final long actual = service.countByTestRun(testRun);

        assertEquals(expected, actual);
    }

    @Test(expected = PersistenceException.class)
    public void testCountError() {
        final CourseRepository repository = Mockito.mock(CourseRepository.class);
        when(repository.count(any(sClass))).thenThrow(new UnitTestException());

        final CourseFinderService service = new CourseFinderServiceImpl(repository);
        service.count();
    }

    @Test
    public void testFindAllCourses() {
        final List<Course> expected = Collections.emptyList();

        final CourseRepository repository = Mockito.mock(CourseRepository.class);
        when(repository.findAll(any(sClass))).thenReturn(expected);

        final CourseFinderService service = new CourseFinderServiceImpl(repository);
        final List<Course> actual = service.findAllCourses();

        assertEquals(expected, actual);
    }

    @Test(expected = PersistenceException.class)
    public void testFindAllCoursesError() {
        final CourseRepository repository = Mockito.mock(CourseRepository.class);
        final Class<Specification<Course>> sClass = null;
        when(repository.findAll(any(sClass))).thenThrow(new UnitTestException());

        final CourseFinderService service = new CourseFinderServiceImpl(repository);
        service.findAllCourses();
    }

    @Test
    public void testFindCourseByTestUuid() {
        final TestRun testRun = new TestRun();
        final Course course = new Course();
        final List<Course> expected = Collections.singletonList(course);

        final CourseRepository repository = Mockito.mock(CourseRepository.class);
        when(repository.findAll(any(sClass))).thenReturn(expected);

        final CourseFinderService service = new CourseFinderServiceImpl(repository);
        final List actual = service.findCoursesByTestRun(testRun);

        assertEquals(expected, actual);
    }

    @Test(expected = PersistenceException.class)
    public void testFindCourseByTestUuidError() {
        final TestRun testRun = new TestRun();

        final CourseRepository repository = Mockito.mock(CourseRepository.class);
        when(repository.findAll(any(sClass))).thenThrow(new UnitTestException());

        final CourseFinderService service = new CourseFinderServiceImpl(repository);
        service.findCoursesByTestRun(testRun);
    }

    @Test
    public void testFindCoursesByTestUuid() {
        final TestRun testRun = new TestRun();
        final Course course = new Course();
        final List<Course> expected = Collections.singletonList(course);

        final CourseRepository repository = Mockito.mock(CourseRepository.class);
        when(repository.findAll(any(sClass))).thenReturn(expected);

        final CourseFinderService service = new CourseFinderServiceImpl(repository);
        final List<Course> actual = service.findCoursesByTestRun(testRun);

        assertEquals(expected, actual);
    }

    @Test(expected = PersistenceException.class)
    public void testFindCoursesByTestUuidError() {
        final TestRun testRun = new TestRun();

        final CourseRepository repository = Mockito.mock(CourseRepository.class);
        when(repository.findAll(any(sClass))).thenThrow(new UnitTestException());

        final CourseFinderService service = new CourseFinderServiceImpl(repository);
        service.findCoursesByTestRun(testRun);
    }

    ....
}

I could eliminate a lot of duplicate code by using a @Begin method but decided against it to support parallel testing.

Integration Testing

We finally come to our integration tests. We know we did something right because the only is one line to test additional functionality – counting the number of courses in the database.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { BusinessApplicationContext.class, TestBusinessApplicationContext.class,
        TestPersistenceJpaConfig.class })
@Transactional
@TransactionConfiguration(defaultRollback = true)
public class CourseServiceIntegrationTest {

    @Resource
    private CourseFinderService fdao;

    @Resource
    private CourseManagerService mdao;

    @Resource
    private TestRunService testService;

    @Test
    public void testCourseLifecycle() throws Exception {
        final TestRun testRun = testService.createTestRun();

        final String name = "Calculus 101 : " + testRun.getUuid();

        final Course expected = new Course();
        expected.setName(name);

        assertNull(expected.getId());

        // create course
        Course actual = mdao.createCourseForTesting(name, testRun);
        expected.setId(actual.getId());
        expected.setUuid(actual.getUuid());
        expected.setCreationDate(actual.getCreationDate());

        assertThat(expected, equalTo(actual));
        assertNotNull(actual.getUuid());
        assertNotNull(actual.getCreationDate());

        // get course by id
        actual = fdao.findCourseById(expected.getId());
        assertThat(expected, equalTo(actual));

        // get course by uuid
        actual = fdao.findCourseByUuid(expected.getUuid());
        assertThat(expected, equalTo(actual));

        // get all courses
        final List<Course> courses = fdao.findCoursesByTestRun(testRun);
        assertTrue(courses.contains(actual));

        // count courses
        final long count = fdao.countByTestRun(testRun);
        assertTrue(count > 0);

        // update course
        expected.setName("Calculus 102 : " + testRun.getUuid());
        actual = mdao.updateCourse(actual, expected.getName());
        assertThat(expected, equalTo(actual));

        // delete Course
        mdao.deleteCourse(expected.getUuid(), 0);
        try {
            fdao.findCourseByUuid(expected.getUuid());
            fail("exception expected");
        } catch (ObjectNotFoundException e) {
            // expected
        }

        testService.deleteTestRun(testRun.getUuid());
    }
}

Source Code

 

Reference: Project Student: JPA Criteria Queries from our JCG partner Bear Giles at the Invariant Properties blog.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ricardo
Ricardo
10 years ago

Hi! I’ve seen your blog, but I can’t find the project’s source code on github. You point to “https://github.com/beargiles/project-student” but the project doesn’t exist anymore. Have you moved it? Can you please point us to the new location? Thanks a lot!

Ricardo
Ricardo
10 years ago

Bah! I’ve seen you have the new link on this post! :) Thanks anyway!

Back to top button