crudrepository findBy method signature for list of tuples - java

I have an Entity Class like this:
#Entity
#Table(name = "CUSTOMER")
class Customer{
#Id
#Column(name = "Id")
Long id;
#Column(name = "EMAIL_ID")
String emailId;
#Column(name = "MOBILE")
String mobile;
}
How to write findBy method for the below query using crudrepository spring data jpa?
select * from customer where (email, mobile) IN (("a#b.c","8971"), ("e#f.g", "8888"))
I'm expecting something like
List<Customer> findByEmailMobileIn(List<Tuple> tuples);
I want to get the list of customers from given pairs

I think this can be done with org.springframework.data.jpa.domain.Specification. You can pass a list of your tuples and proceed them this way (don't care that Tuple is not an entity, but you need to define this class):
public class CustomerSpecification implements Specification<Customer> {
// names of the fields in your Customer entity
private static final String CONST_EMAIL_ID = "emailId";
private static final String CONST_MOBILE = "mobile";
private List<MyTuple> tuples;
public ClaimSpecification(List<MyTuple> tuples) {
this.tuples = tuples;
}
#Override
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
// will be connected with logical OR
List<Predicate> predicates = new ArrayList<>();
tuples.forEach(tuple -> {
List<Predicate> innerPredicates = new ArrayList<>();
if (tuple.getEmail() != null) {
innerPredicates.add(cb.equal(root
.<String>get(CONST_EMAIL_ID), tuple.getEmail()));
}
if (tuple.getMobile() != null) {
innerPredicates.add(cb.equal(root
.<String>get(CONST_MOBILE), tuple.getMobile()));
}
// these predicates match a tuple, hence joined with AND
predicates.add(andTogether(innerPredicates, cb));
});
return orTogether(predicates, cb);
}
private Predicate orTogether(List<Predicate> predicates, CriteriaBuilder cb) {
return cb.or(predicates.toArray(new Predicate[0]));
}
private Predicate andTogether(List<Predicate> predicates, CriteriaBuilder cb) {
return cb.and(predicates.toArray(new Predicate[0]));
}
}
Your repo is supposed to extend interface JpaSpecificationExecutor<Customer>.
Then construct a specification with a list of tuples and pass it to the method customerRepo.findAll(Specification<Customer>) - it returns a list of customers.

It is maybe cleaner using a projection :
#Entity
#Table(name = "CUSTOMER")
class CustomerQueryData {
#Id
#Column(name = "Id")
Long id;
#OneToOne
#JoinColumns(#JoinColumn(name = "emailId"), #JoinColumn(name = "mobile"))
Contact contact;
}
The Contact Entity :
#Entity
#Table(name = "CUSTOMER")
class Contact{
#Column(name = "EMAIL_ID")
String emailId;
#Column(name = "MOBILE")
String mobile;
}
After specifying the entities, the repo :
CustomerJpaProjection extends Repository<CustomerQueryData, Long>, QueryDslPredicateExecutor<CustomerQueryData> {
#Override
List<CustomerQueryData> findAll(Predicate predicate);
}
And the repo call :
ArrayList<Contact> contacts = new ArrayList<>();
contacts.add(new Contact("a#b.c","8971"));
contacts.add(new Contact("e#f.g", "8888"));
customerJpaProjection.findAll(QCustomerQueryData.customerQueryData.contact.in(contacts));
Not tested code.

Related

Spring JPA Specification filtering

I'm trying to filter parent entity by intersection of children property and inputed list.
My entities:
#Entity
#Table(name = "recipes")
public class Recipe {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<Ingredient> ingredientsList = new ArrayList<>();
//other fields and methods
}
#Entity
#Table(name = "ingredients")
public class Ingredient {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "product")
private String product;
//other fields and methods
}
As result i want get list of Recipes. Each recipe must have all products from user's inputed list.
I was trying smth like this:
public static Specification<Recipe> containsProducts(List<String> products) {
return (root, query, criteriaBuilder) -> {
if (Objects.isNull(products) || products.isEmpty()) {
return criteriaBuilder.conjunction();
}
List<Predicate> predicates = new ArrayList<>();
Join<Recipe, Ingredient> ingredientRecipeJoin = root.join("ingredientsList", JoinType.INNER);
for (String product : products) {
if (product.isBlank()) {
continue;
}
predicates.add(criteriaBuilder.equal(ingredientRecipeJoin.get(Ingredient_.PRODUCT), product));
}
return criteriaBuilder.and(predicates.toArray(Predicate[]::new));
};
}
But it works only when products list size=1.
Finally i got answer. My miss is that i was trying to search recipes by only one join. For every item in user's inputed list i should create a new join and create on it a new prediction. Jpa logic prevent reusing columns from old joins.
So my containsProducts method now looks like:
public static Specification<Recipe> containsProducts(List<String> products) {
return (root, query, criteriaBuilder) -> {
if (Objects.isNull(products) || products.isEmpty()) {
return criteriaBuilder.conjunction();
}
List<Predicate> predicates = new ArrayList<>();
Join<Recipe, Ingredient> ingredientRecipeJoin;
for (String product : products) {
if (product.isBlank()) {
continue;
}
ingredientRecipeJoin = root.join(Recipe_.INGREDIENTS_LIST, JoinType.INNER);
predicates.add(criteriaBuilder.equal(ingredientRecipeJoin.get(Ingredient_.PRODUCT), product));
}
return criteriaBuilder.and(predicates.toArray(Predicate[]::new));
};
}

Spring JPA Criteria API Query on OneToMany List Field

I want to load all the CustomerRequests for a specific Customer with the JPA/Hibernate Criteria API.
In specific: I want to load all the CustomerRequest for which a CustomerRequest2Customer entry with a specific customerId exists.
#Entity
public class CustomerRequest {
#Id
private int id;
private int priority;
#OneToMany(mappedBy = "customerRequestId")
private List<CustomerRequest2Customer> listCustomerRequestToCustomer; // <- Query this field
}
#Entity
public class CustomerRequest2Customer {
#Id
private int id;
#ManyToOne
private Customer customer; // <- Query this field
#ManyToOne
private CustomerRequest customerRequest;
}
#Entity
public class Customer {
#Id
private int id; // <- Query this field
private String name;
}
How I currently query other fields:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<CustomerRequest> cq =
cb.createQuery(CustomerRequest.class);
Root<CustomerRequest> root = cq.from(CustomerRequest.class);
cq.where(cb.equal(root.get("priority"), 1));
return entityManager.createQuery(cq).getResultList();
You have to join the entities like this:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<CustomerRequest> cq = cb.createQuery(CustomerRequest.class);
Root<CustomerRequest> root = cq.from(CustomerRequest.class);
Join<CustomerRequest, CustomerRequest2Customer> customerRequest2Customer = root.join("listCustomerRequestToCustomer");
Join<CustomerRequest2Customer, Customer> customer = customerRequest2Customer .join("customer");
cq.where(cb.equal(customer .get("id"), 1));
return entityManager.createQuery(cq).getResultList();

Query on parent's collection - Hibernate Specification

I have three tables created with Hibernate. Product is the parent while barcodes is a collection end price is a child (one to many) of products.
#NotBlank
private String ref;
#ElementCollection(fetch = FetchType.EAGER)
#CollectionTable(name = "products_barcodes")
#Fetch(FetchMode.SELECT)
private List<String> barcodes;
#OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<PriceEntity> prices;
I'm trying to query starting from the child (Price). I was able to query on a string but now i would like to query on the collection s element.
Specifications<PriceEntity> specifications = where(hasTenant(tid));
if (isNotBlank(ref)) {
specifications = specifications.and(hasRef(ref));
}
if (isNotBlank(barcode)) {
specifications = specifications.and(hasBarcode(barcode));
}
/*********************************/
public static Specification<PriceEntity> hasRef(final String ref) {
return new Specification<PriceEntity>() {
#Override
public Predicate toPredicate(Root<PriceEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
return criteriaBuilder.equal(root.<PriceEntity>get("parent").get("ref"), ref);
}
};
}
public static Specification<PriceEntity> hasBarcode(final String barcode) {
return new Specification<PriceEntity>() {
#Override
public Predicate toPredicate(Root<PriceEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
return criteriaBuilder.equal(root.<PriceEntity>get("parent").get("barcodes"), barcode);
}
};
}
how would you write the specification? The one above is not working, i get this exception at runtime:
"IllegalArgumentException: Parameter value [8003921360408] did not match expected type [java.util.Collection (n/a)]"
Thanks
Question solved by Thomas s comment.
For collections criteriaBuilder.isMember should be used.

JPA Criteria API Specification JOIN by condition and result isn't null

The code example:
#Entity
public class Event {
#Id
#GeneratedValue
private Long id;
private String name;
#OneToMany(...)
private List<Actions> actions;
}
#Entity
public class Action {
#Id
#GeneratedValue
private Long id;
private String name;
private Date date;
#ManyToOne
#JoinColumn(name = "event_id")
private Event event;
}
public class EventSpecification {
public static Specification<Event> findByCriteria(EventSearchCriteria criteria) {
return (root, criteriaQuery, criteriaBuilder) -> {
List<Predicate> predicates = new ArrayList<>();
criteria.getEventName().ifPresent(name ->
predicates.add(criteriaBuilder.equal(criteriaBuilder.lower(root.get(Event_.name)), name)));
criteria.getDate().ifPresent(date ->
// Need one more Predicat - event.has.actions.with.date.equals.criteria.date
);
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
};
}
}
The question is:
How to create the Predicate - only Events which have Actions with Action.date = searchCriteria.date. I think it's possible but I can't find a solution.
Maybe that will help you pointing out the right way
criteria.getDate().ifPresent(date -> {
Join join = root.join("actions");
predicates.add(criteriaBuilder.equal(join.get("date"), date);
});

Spring Data JPA Specification using CriteriaBuilder with a one to many relationship

I have a User entity, a UserToApplication entity, and an Application entity.
A single User can have access to more than one Application. And a single Application can be used by more than one User.
Here is the User entity.
#Entity
#Table(name = "USER", schema = "UDB")
public class User {
private Long userId;
private Collection<Application> applications;
private String firstNm;
private String lastNm;
private String email;
#SequenceGenerator(name = "generator", sequenceName = "UDB.USER_SEQ", initialValue = 1, allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator")
#Column(name = "USER_ID", unique = true, nullable = false)
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
#OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
public Collection<Application> getApplications() {
return applications;
}
public void setApplications(Collection<Application> applications) {
this.applications = applications;
}
/* Other getters and setters omitted for brevity */
}
Here is the UserToApplication entity.
#Entity
#Table(name = "USER_TO_APPLICATION", schema = "UDB")
public class Application {
private Long userToApplicationId;
private User user;
private Application application;
#SequenceGenerator(name = "generator", sequenceName = "UDB.USER_TO_APP_SEQ", initialValue = 0, allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator")
#Column(name = "USER_TO_APPLICATION_ID", unique = true, nullable = false)
public Long getUserToApplicationId() {
return userToApplicationId;
}
public void setUserToApplicationId(Long userToApplicationId) {
this.userToApplicationId = userToApplicationId;
}
#ManyToOne
#JoinColumn(name = "USER_ID", referencedColumnName = "USER_ID", nullable = false)
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#ManyToOne
#JoinColumn(name = "APPLICATION_ID", nullable = false)
public Application getApplication() {
return application;
}
}
And here is the Application entity.
#Entity
#Table(name = "APPLICATION", schema = "UDB")
public class Application {
private Long applicationId;
private String name;
private String code;
/* Getters and setters omitted for brevity */
}
I have the following Specification that I use to search for a User by firstNm, lastNm, and email.
public class UserSpecification {
public static Specification<User> findByFirstNmLastNmEmail(String firstNm, String lastNm, String email) {
return new Specification<User>() {
#Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
final Predicate firstNmPredicate = null;
final Predicate lastNmPredicate = null;
final Predicate emailPredicate = null;
if (!StringUtils.isEmpty(firstNm)) {
firstNmPredicate = cb.like(cb.lower(root.get(User_.firstNm), firstNm));
}
if (!StringUtils.isEmpty(lastNm)) {
lastNmPredicate = cb.like(cb.lower(root.get(User_.lastNm), lastNm));
}
if (!StringUtils.isEmpty(email)) {
emailPredicate = cb.like(cb.lower(root.get(User_.email), email));
}
return cb.and(firstNmPredicate, lastNmPredicate, emailPredicate);
}
};
}
}
And here is the User_ metamodel that I have so far.
#StaticMetamodel(User.class)
public class User_ {
public static volatile SingularAttribute<User, String> firstNm;
public static volatile SingularAttribute<User, String> lastNm;
public static volatile SingularAttribute<User, String> email;
}
Now, I would like to also pass in a list of application IDs to the Specification, such that its method signature would be:
public static Specification<User> findByFirstNmLastNmEmailApp(String firstNm, String lastNm, String email, Collection<Long> appIds)
So, my question is, if I add the #OneToMany mapping to the User_ metamodel for the Collection<Application> applications field of my User entity, then how would I reference it in the Specification?
My current Specification would be similar to the following SQL query:
select * from user u
where lower(first_nm) like '%firstNm%'
and lower(last_nm) like '%lastNm%'
and lower(email) like '%email%';
And what I would like to achieve in the new Specification would be something like this:
select * from user u
join user_to_application uta on uta.user_id = u.user_id
where lower(u.first_nm) like '%firstNm%'
and lower(u.last_nm) like '%lastNm%'
and lower(u.email) like '%email%'
and uta.application_id in (appIds);
Is it possible to do this kind of mapping in the metamodel, and how could I achieve this result in my Specification?
I found a solution. To map a one to many attribute, in the metamodel I added the following:
public static volatile CollectionAttribute<User, Application> applications;
I also needed to add a metamodel for the Application entity.
#StaticMetamodel(Application.class)
public class Application_ {
public static volatile SingularAttribute<Application, Long> applicationId;
}
Then in my Specification, I could access the applications for a user, using the .join() method on the Root<User> instance. Here is the Predicate I formed.
final Predicate appPredicate = root.join(User_.applications).get(Application_.applicationId).in(appIds);
Also, it is worth noting that my Specification as it is written in the question will not work if any of the input values are empty. A null Predicate passed to the .and() method of CriteriaBuilder will cause a NullPointerException. So, I created an ArrayList of type Predicate, then added each Predicate to the list if the corresponding parameter was non-empty. Finally, I convert the ArrayList to an array to pass it to the .and() function of the CriteriaBuilder. Here is the final Specification:
public class UserSpecification {
public static Specification<User> findByFirstNmLastNmEmailApp(String firstNm, String lastNm, String email, Collection<Long> appIds) {
return new Specification<User>() {
#Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
final Collection<Predicate> predicates = new ArrayList<>();
if (!StringUtils.isEmpty(firstNm)) {
final Predicate firstNmPredicate = cb.like(cb.lower(root.get(User_.firstNm), firstNm));
predicates.add(firstNmPredicate);
}
if (!StringUtils.isEmpty(lastNm)) {
final Predicate lastNmPredicate = cb.like(cb.lower(root.get(User_.lastNm), lastNm));
predicates.add(lastNmPredicate);
}
if (!StringUtils.isEmpty(email)) {
final Predicate emailPredicate = cb.like(cb.lower(root.get(User_.email), email));
predicates.add(emailPredicate);
}
if (!appIds.isEmpty()) {
final Predicate appPredicate = root.join(User_.applications).get(Application_.applicationId).in(appIds);
predicates.add(appPredicate);
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
}
}

Categories

Resources