fix jpa querydsl test

This commit is contained in:
DOHA 2015-01-26 17:41:32 +02:00
parent 05e2e58aa0
commit f04a800ac9
8 changed files with 157 additions and 99 deletions

View File

@ -1,23 +0,0 @@
package org.baeldung.persistence.dao;
import org.baeldung.persistence.model.QMyUser;
import com.mysema.query.types.expr.BooleanExpression;
public class MyUserPrdicates {
public static BooleanExpression firstNameIsLike(final String term) {
final QMyUser user = QMyUser.myUser;
return user.firstName.containsIgnoreCase(term);
}
public static BooleanExpression lastNameIsLike(final String term) {
final QMyUser user = QMyUser.myUser;
return user.lastName.containsIgnoreCase(term);
}
public static BooleanExpression ageIsGreaterThan(final int minAge) {
final QMyUser user = QMyUser.myUser;
return user.age.goe(minAge);
}
}

View File

@ -0,0 +1,62 @@
package org.baeldung.persistence.dao;
import org.baeldung.persistence.model.MyUser;
import org.baeldung.web.util.SearchCriteria;
import com.mysema.query.types.expr.BooleanExpression;
import com.mysema.query.types.path.NumberPath;
import com.mysema.query.types.path.PathBuilder;
import com.mysema.query.types.path.StringPath;
public class MyUserPredicate {
private SearchCriteria criteria;
public MyUserPredicate() {
}
public MyUserPredicate(final SearchCriteria criteria) {
this.criteria = criteria;
}
public BooleanExpression getPredicate() {
final PathBuilder<MyUser> entityPath = new PathBuilder<MyUser>(MyUser.class, "myUser");
if (isNumeric(criteria.getValue().toString())) {
System.out.println("Nuumber");
final NumberPath<Integer> path = entityPath.getNumber(criteria.getKey(), Integer.class);
final int value = Integer.parseInt(criteria.getValue().toString());
if (criteria.getOperation().equalsIgnoreCase(":")) {
return path.eq(value);
} else if (criteria.getOperation().equalsIgnoreCase(">")) {
return path.goe(value);
} else if (criteria.getOperation().equalsIgnoreCase("<")) {
return path.loe(value);
}
} else {
final StringPath path = entityPath.getString(criteria.getKey());
if (criteria.getOperation().equalsIgnoreCase(":")) {
return path.containsIgnoreCase(criteria.getValue().toString());
}
}
return null;
}
public SearchCriteria getCriteria() {
return criteria;
}
public void setCriteria(final SearchCriteria criteria) {
this.criteria = criteria;
}
public static boolean isNumeric(final String str) {
try {
Integer.parseInt(str);
} catch (final NumberFormatException e) {
return false;
}
return true;
}
}

View File

@ -1,32 +1,25 @@
package org.baeldung.persistence.dao; package org.baeldung.persistence.dao;
import static org.baeldung.persistence.dao.MyUserPrdicates.ageIsGreaterThan;
import static org.baeldung.persistence.dao.MyUserPrdicates.firstNameIsLike;
import static org.baeldung.persistence.dao.MyUserPrdicates.lastNameIsLike;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import org.baeldung.web.util.SearchCriteria;
import com.mysema.query.types.expr.BooleanExpression; import com.mysema.query.types.expr.BooleanExpression;
public class MyUserPredicatesBuilder { public class MyUserPredicatesBuilder {
public static BooleanExpression buildUserPredicates(final Map<String, Object> params) { public static BooleanExpression buildUserPredicates(final List<SearchCriteria> params) {
if (params.size() == 0) if (params.size() == 0)
return null; return null;
final List<BooleanExpression> predicates = new ArrayList<BooleanExpression>(); final List<BooleanExpression> predicates = new ArrayList<BooleanExpression>();
String key, value; MyUserPredicate predicate;
for (final Map.Entry<String, Object> param : params.entrySet()) { for (final SearchCriteria param : params) {
key = param.getKey(); predicate = new MyUserPredicate(param);
value = param.getValue().toString(); final BooleanExpression exp = predicate.getPredicate();
if (key.equalsIgnoreCase("age")) { if (exp != null) {
predicates.add(ageIsGreaterThan(Integer.parseInt(value))); predicates.add(exp);
} else if (key.equalsIgnoreCase("firstName")) {
predicates.add(firstNameIsLike(value));
} else if (key.equalsIgnoreCase("lastName")) {
predicates.add(lastNameIsLike(value));
} }
} }

View File

@ -1,10 +1,11 @@
package org.baeldung.persistence.service.impl; package org.baeldung.persistence.service.impl;
import java.util.Map; import java.util.List;
import org.baeldung.persistence.dao.MyUserPredicatesBuilder; import org.baeldung.persistence.dao.MyUserPredicatesBuilder;
import org.baeldung.persistence.dao.MyUserRepository; import org.baeldung.persistence.dao.MyUserRepository;
import org.baeldung.persistence.model.MyUser; import org.baeldung.persistence.model.MyUser;
import org.baeldung.web.util.SearchCriteria;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -22,7 +23,7 @@ public class MyUserService {
super(); super();
} }
public Iterable<MyUser> search(final Map<String, Object> params) { public Iterable<MyUser> search(final List<SearchCriteria> params) {
final BooleanExpression predicate = MyUserPredicatesBuilder.buildUserPredicates(params); final BooleanExpression predicate = MyUserPredicatesBuilder.buildUserPredicates(params);
if (predicate == null) if (predicate == null)
return repository.findAll(); return repository.findAll();

View File

@ -1,9 +1,7 @@
package org.baeldung.web.controller; package org.baeldung.web.controller;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -65,13 +63,13 @@ public class UserController {
@RequestMapping(method = RequestMethod.GET, value = "/myusers") @RequestMapping(method = RequestMethod.GET, value = "/myusers")
@ResponseBody @ResponseBody
public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search", required = false) final String search) { public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search", required = false) final String search) {
final Map<String, Object> params = new HashMap<String, Object>(); final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
if (search != null) { if (search != null) {
final Pattern pattern = Pattern.compile("(\\w+?):(\\w+?),"); final Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
final Matcher matcher = pattern.matcher(search + ","); final Matcher matcher = pattern.matcher(search + ",");
while (matcher.find()) { while (matcher.find()) {
params.put(matcher.group(1), matcher.group(2)); params.add(new SearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3)));
} }
} }
return myService.search(params); return myService.search(params);

View File

@ -1,12 +1,14 @@
package org.baeldung.persistence.query; package org.baeldung.persistence.query;
import static org.junit.Assert.assertEquals; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIn.isIn;
import static org.hamcrest.core.IsNot.not;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.baeldung.persistence.dao.IUserDAO;
import org.baeldung.persistence.model.User; import org.baeldung.persistence.model.User;
import org.baeldung.persistence.service.impl.UserService;
import org.baeldung.spring.PersistenceConfig; import org.baeldung.spring.PersistenceConfig;
import org.baeldung.web.util.SearchCriteria; import org.baeldung.web.util.SearchCriteria;
import org.junit.Before; import org.junit.Before;
@ -26,7 +28,7 @@ import org.springframework.transaction.annotation.Transactional;
public class JPACriteriaQueryTest { public class JPACriteriaQueryTest {
@Autowired @Autowired
private UserService userService; private IUserDAO userApi;
private User userJohn; private User userJohn;
@ -39,14 +41,14 @@ public class JPACriteriaQueryTest {
userJohn.setLastName("Doe"); userJohn.setLastName("Doe");
userJohn.setEmail("john@doe.com"); userJohn.setEmail("john@doe.com");
userJohn.setAge(22); userJohn.setAge(22);
userService.saveUser(userJohn); userApi.save(userJohn);
userTom = new User(); userTom = new User();
userTom.setFirstName("Tom"); userTom.setFirstName("Tom");
userTom.setLastName("Doe"); userTom.setLastName("Doe");
userTom.setEmail("tom@doe.com"); userTom.setEmail("tom@doe.com");
userTom.setAge(26); userTom.setAge(26);
userService.saveUser(userTom); userApi.save(userTom);
} }
@Test @Test
@ -55,10 +57,10 @@ public class JPACriteriaQueryTest {
params.add(new SearchCriteria("firstName", ":", "John")); params.add(new SearchCriteria("firstName", ":", "John"));
params.add(new SearchCriteria("lastName", ":", "Doe")); params.add(new SearchCriteria("lastName", ":", "Doe"));
final List<User> result = userService.searchUser(params); final List<User> results = userApi.searchUser(params);
assertEquals(1, result.size()); assertThat(userJohn, isIn(results));
assertEquals(userJohn.getEmail(), result.get(0).getEmail()); assertThat(userTom, not(isIn(results)));
} }
@Test @Test
@ -66,8 +68,9 @@ public class JPACriteriaQueryTest {
final List<SearchCriteria> params = new ArrayList<SearchCriteria>(); final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
params.add(new SearchCriteria("lastName", ":", "Doe")); params.add(new SearchCriteria("lastName", ":", "Doe"));
final List<User> result = userService.searchUser(params); final List<User> results = userApi.searchUser(params);
assertEquals(2, result.size()); assertThat(userJohn, isIn(results));
assertThat(userTom, isIn(results));
} }
@Test @Test
@ -76,10 +79,10 @@ public class JPACriteriaQueryTest {
params.add(new SearchCriteria("lastName", ":", "Doe")); params.add(new SearchCriteria("lastName", ":", "Doe"));
params.add(new SearchCriteria("age", ">", "25")); params.add(new SearchCriteria("age", ">", "25"));
final List<User> result = userService.searchUser(params); final List<User> results = userApi.searchUser(params);
assertEquals(1, result.size()); assertThat(userTom, isIn(results));
assertEquals(userTom.getEmail(), result.get(0).getEmail()); assertThat(userJohn, not(isIn(results)));
} }
@Test @Test
@ -88,8 +91,9 @@ public class JPACriteriaQueryTest {
params.add(new SearchCriteria("firstName", ":", "Adam")); params.add(new SearchCriteria("firstName", ":", "Adam"));
params.add(new SearchCriteria("lastName", ":", "Fox")); params.add(new SearchCriteria("lastName", ":", "Fox"));
final List<User> result = userService.searchUser(params); final List<User> results = userApi.searchUser(params);
assertEquals(0, result.size()); assertThat(userJohn, not(isIn(results)));
assertThat(userTom, not(isIn(results)));
} }
@Test @Test
@ -97,9 +101,9 @@ public class JPACriteriaQueryTest {
final List<SearchCriteria> params = new ArrayList<SearchCriteria>(); final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
params.add(new SearchCriteria("firstName", ":", "jo")); params.add(new SearchCriteria("firstName", ":", "jo"));
final List<User> result = userService.searchUser(params); final List<User> results = userApi.searchUser(params);
assertEquals(1, result.size()); assertThat(userJohn, isIn(results));
assertEquals(userJohn.getEmail(), result.get(0).getEmail()); assertThat(userTom, not(isIn(results)));
} }
} }

View File

@ -1,17 +1,18 @@
package org.baeldung.persistence.query; package org.baeldung.persistence.query;
import static org.baeldung.persistence.dao.MyUserPrdicates.ageIsGreaterThan;
import static org.baeldung.persistence.dao.MyUserPrdicates.firstNameIsLike;
import static org.baeldung.persistence.dao.MyUserPrdicates.lastNameIsLike;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsEmptyIterable.emptyIterable; import static org.hamcrest.collection.IsEmptyIterable.emptyIterable;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNot.not;
import org.baeldung.persistence.dao.MyUserRepository; import java.util.ArrayList;
import java.util.List;
import org.baeldung.persistence.model.MyUser; import org.baeldung.persistence.model.MyUser;
import org.baeldung.persistence.service.impl.MyUserService;
import org.baeldung.spring.PersistenceConfig; import org.baeldung.spring.PersistenceConfig;
import org.baeldung.web.util.SearchCriteria;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -29,7 +30,7 @@ import org.springframework.transaction.annotation.Transactional;
public class JPAQuerydslTest { public class JPAQuerydslTest {
@Autowired @Autowired
private MyUserRepository repository; private MyUserService service;
private MyUser userJohn; private MyUser userJohn;
@ -42,49 +43,67 @@ public class JPAQuerydslTest {
userJohn.setLastName("Doe"); userJohn.setLastName("Doe");
userJohn.setEmail("john@doe.com"); userJohn.setEmail("john@doe.com");
userJohn.setAge(22); userJohn.setAge(22);
repository.save(userJohn); service.save(userJohn);
userTom = new MyUser(); userTom = new MyUser();
userTom.setFirstName("Tom"); userTom.setFirstName("Tom");
userTom.setLastName("Doe"); userTom.setLastName("Doe");
userTom.setEmail("tom@doe.com"); userTom.setEmail("tom@doe.com");
userTom.setAge(26); userTom.setAge(26);
repository.save(userTom); service.save(userTom);
} }
@Test @Test
public void givenLast_whenGettingListOfUsers_thenCorrect() { public void givenLast_whenGettingListOfUsers_thenCorrect() {
final Iterable<MyUser> result = repository.findAll(lastNameIsLike("doe")); final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
assertThat(result, containsInAnyOrder(userJohn, userTom)); params.add(new SearchCriteria("lastName", ":", "Doe"));
final Iterable<MyUser> results = service.search(params);
assertThat(results, containsInAnyOrder(userJohn, userTom));
} }
@Test @Test
public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() { public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() {
final Iterable<MyUser> result = repository.findAll(lastNameIsLike("doe").and(firstNameIsLike("john"))); final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
params.add(new SearchCriteria("firstName", ":", "John"));
params.add(new SearchCriteria("lastName", ":", "Doe"));
assertThat(result, contains(userJohn)); final Iterable<MyUser> results = service.search(params);
assertThat(result, not(contains(userTom)));
assertThat(results, contains(userJohn));
assertThat(results, not(contains(userTom)));
} }
@Test @Test
public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() { public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() {
final Iterable<MyUser> result = repository.findAll(lastNameIsLike("doe").and(ageIsGreaterThan(25))); final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
params.add(new SearchCriteria("lastName", ":", "Doe"));
params.add(new SearchCriteria("age", ">", "25"));
assertThat(result, contains(userTom)); final Iterable<MyUser> results = service.search(params);
assertThat(result, not(contains(userJohn)));
assertThat(results, contains(userTom));
assertThat(results, not(contains(userJohn)));
} }
@Test @Test
public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() { public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() {
final Iterable<MyUser> result = repository.findAll(lastNameIsLike("Adam").and(firstNameIsLike("Fox"))); final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
assertThat(result, emptyIterable()); params.add(new SearchCriteria("firstName", ":", "Adam"));
params.add(new SearchCriteria("lastName", ":", "Fox"));
final Iterable<MyUser> results = service.search(params);
assertThat(results, emptyIterable());
} }
@Test @Test
public void givenPartialFirst_whenGettingListOfUsers_thenCorrect() { public void givenPartialFirst_whenGettingListOfUsers_thenCorrect() {
final Iterable<MyUser> result = repository.findAll(firstNameIsLike("jo")); final List<SearchCriteria> params = new ArrayList<SearchCriteria>();
params.add(new SearchCriteria("firstName", ":", "jo"));
assertThat(result, contains(userJohn)); final Iterable<MyUser> results = service.search(params);
assertThat(result, not(contains(userTom)));
assertThat(results, contains(userJohn));
assertThat(results, not(contains(userTom)));
} }
} }

View File

@ -1,6 +1,8 @@
package org.baeldung.persistence.query; package org.baeldung.persistence.query;
import static org.junit.Assert.assertEquals; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIn.isIn;
import static org.hamcrest.core.IsNot.not;
import java.util.List; import java.util.List;
@ -53,46 +55,48 @@ public class JPASpecificationsTest {
@Test @Test
public void givenLast_whenGettingListOfUsers_thenCorrect() { public void givenLast_whenGettingListOfUsers_thenCorrect() {
final UserSpecification spec = new UserSpecification(new SearchCriteria("lastName", ":", "doe")); final UserSpecification spec = new UserSpecification(new SearchCriteria("lastName", ":", "doe"));
final List<User> result = repository.findAll(spec); final List<User> results = repository.findAll(spec);
assertEquals(2, result.size()); assertThat(userJohn, isIn(results));
assertThat(userTom, isIn(results));
} }
@Test @Test
public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() { public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() {
final UserSpecification spec = new UserSpecification(new SearchCriteria("firstName", ":", "john")); final UserSpecification spec = new UserSpecification(new SearchCriteria("firstName", ":", "john"));
final UserSpecification spec1 = new UserSpecification(new SearchCriteria("lastName", ":", "doe")); final UserSpecification spec1 = new UserSpecification(new SearchCriteria("lastName", ":", "doe"));
final List<User> result = repository.findAll(Specifications.where(spec).and(spec1)); final List<User> results = repository.findAll(Specifications.where(spec).and(spec1));
assertEquals(1, result.size()); assertThat(userJohn, isIn(results));
assertEquals(userJohn.getEmail(), result.get(0).getEmail()); assertThat(userTom, not(isIn(results)));
} }
@Test @Test
public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() { public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() {
final UserSpecification spec = new UserSpecification(new SearchCriteria("age", ">", "25")); final UserSpecification spec = new UserSpecification(new SearchCriteria("age", ">", "25"));
final UserSpecification spec1 = new UserSpecification(new SearchCriteria("lastName", ":", "doe")); final UserSpecification spec1 = new UserSpecification(new SearchCriteria("lastName", ":", "doe"));
final List<User> result = repository.findAll(Specifications.where(spec).and(spec1)); final List<User> results = repository.findAll(Specifications.where(spec).and(spec1));
assertEquals(1, result.size()); assertThat(userTom, isIn(results));
assertEquals(userTom.getEmail(), result.get(0).getEmail()); assertThat(userJohn, not(isIn(results)));
} }
@Test @Test
public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() { public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() {
final UserSpecification spec = new UserSpecification(new SearchCriteria("firstName", ":", "Adam")); final UserSpecification spec = new UserSpecification(new SearchCriteria("firstName", ":", "Adam"));
final UserSpecification spec1 = new UserSpecification(new SearchCriteria("lastName", ":", "Fox")); final UserSpecification spec1 = new UserSpecification(new SearchCriteria("lastName", ":", "Fox"));
final List<User> result = repository.findAll(Specifications.where(spec).and(spec1)); final List<User> results = repository.findAll(Specifications.where(spec).and(spec1));
assertEquals(0, result.size()); assertThat(userJohn, not(isIn(results)));
assertThat(userTom, not(isIn(results)));
} }
@Test @Test
public void givenPartialFirst_whenGettingListOfUsers_thenCorrect() { public void givenPartialFirst_whenGettingListOfUsers_thenCorrect() {
final UserSpecification spec = new UserSpecification(new SearchCriteria("firstName", ":", "jo")); final UserSpecification spec = new UserSpecification(new SearchCriteria("firstName", ":", "jo"));
final List<User> result = repository.findAll(spec); final List<User> results = repository.findAll(spec);
assertEquals(1, result.size()); assertThat(userJohn, isIn(results));
assertEquals(userJohn.getEmail(), result.get(0).getEmail()); assertThat(userTom, not(isIn(results)));
} }
} }