Java Reference
In-Depth Information
User user = dao.getUserById(id);
commitTransaction(true);
assertUserWithTelephone(user);
}
Running the test case after this change fails because of the same exception our poor
user faced in the real application. The solution then is to fix the JPA query to eagerly
fetch the telephones, as shown here:
public User getUserById(long id) {
String jql = "select user from User user left join fetch " +
"user.telephones where id = ?";
Query query = entityManager.createQuery(jql);
query.setParameter(1, id);
return (User) query.getSingleResult();
}
Such a change allows testGetUserByIdWithTelephone() to pass, but now testGet-
UserByIdOnNullDatabase() and testGetUserByIdUnknownId() fail:
javax.persistence.NoResultException: No entity found for query
at org.hibernate.ejb.QueryImpl.getSingleResult(QueryImpl.java:83)
at com.manning.jia.chapter18.dao.UserDaoJpaImpl.
getUserById(UserDaoJpaImpl.java:45)
Let's change the method again, using getResultList() instead of getSingle-
Result() :
public User getUserById(long id) {
String jql = "select user from User user left join fetch " +
"user.telephones where id = ?";
Query query = entityManager.createQuery(jql);
query.setParameter(1, id);
@SuppressWarnings("unchecked")
List<User> users = query.getResultList();
// sanity check
assert users.size() <= 1 : "returned " + users.size() + " users";
return users.isEmpty() ? null : (User) users.get(0);
}
Although the change itself is simple, this issue illustrates the importance of negative
tests. If we didn't have these tests, the lazy-initialization fix would have introduced a
regression bug!
Once these two fixes are in place, the application will run fine for awhile, until a
user has two or more telephones, which would cause the following exception:
java.lang.AssertionError: returned 2 users
at com.manning.jia.chapter18.dao.UserDaoJpaImpl.getUserById
(UserDaoJpaImpl.java:49)
at com.manning.jia.chapter18.dao.UserDaoJpaImplTest.
testGetUserByIdWithTelephones(UserDaoJpaImplTest.java:114)
What's happening now is that a query that was supposed to return one user is return-
ing two—weird!
 
 
Search WWH ::




Custom Search