Spring JPA CriteriaQuery groupBy based on only one key in a Composite Primary Key (#EmbeddedId) - spring-boot

I am trying to write a criteriaQuery and group results based on emailId, which is one of the keys of a composite PK, embedded into one of my Entity classes.
The method that returns the specification is as follows :
public static Specification < User > getSpecification(Integer id) {
return (root, query, criteriaBuilder) - > {
var predicates = new ArrayList<Predicate()>;
predicates.add(criteriaBuilder.equal(root.get("indexId"), id));
query.groupBy(root.get("details").get("emailId"));
return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
};
}
The entity class:
public class User {
#EmbeddedId private Details details;
private String name;
private String status;
}
#Embeddable
public class Details {
private String emailId;
private Integer branchId;
}
I have skipped some annotations.
I want to group the results in a way where emailId remains unique, even if branchId changes. In essence for data where there are 3 rows of same emailId but different branchId, I should only fetch 1 result.
It seems it throws an error and asks for both components of the composite key to be passed in the query.groupBy statement.
If you could please help me figure out the issue.

Related

Order results based on count using spring boot specification API

Consider the entity below.
PS: The model has more fields but for the question to be short I have posted only the relevant fields
Class Employee {
private String name;
private String country;
private String region;
private String department
#OneToMany
private Set<Skill> skills;
}
Class Skill {
private name;
}
I am using spring boot Specification API to filter employees on different fields like region, country, and so on.
public class EmployeeSpec implements Specification<Employee> {
#Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
String fielName = //some field name
String fieldValue = //some field value
switch (fielName ) {
case "country":
return cb.equal(root.get("country"), fieldValue);
case "department":
return cb.equal(root.get("department"), fieldValue);
case "region":
return cb.equal(root.get("region"), fieldValue);
}
}
I want to order the results such that employee with maximum skills comes first. I am not sure how to implement this using Specification.
You can use CriteriaBuilder.size(..). For your case, the code will look like:
cq.orderBy(cb.desc(cb.size(root.get("skills"))));

spring-data-jdbc: query entity containing 1-n relation with JOOQ

I am trying to load entities containing a reference to another entity (1-n) with the help of JOOQ (based on spring-data-jdbc).
I'm started extending the spring-data-jdbc-jooq-example.
The adjusted model with the 1-n relation:
#Data
public class Category {
private #Id Long id;
private String name, description;
private AgeGroup ageGroup;
private Set<SubCategory> subCategories;
public Category() {}
public Category(Long id, String name, String description, AgeGroup ageGroup) {
this(id, name, description, ageGroup, new HashSet<>());
}
public Category(Long id, String name, String description, AgeGroup ageGroup, Set<SubCategory> subCategories) {
this.id = id;
this.name = name;
this.description = description;
this.ageGroup = ageGroup;
this.subCategories = subCategories;
}
}
#Data
#AllArgsConstructor
#NoArgsConstructor
public class SubCategory {
private #Id Long id;
private String title;
}
I wrote two queries, one via the #Query-Annotation in the CrudRepository and one with the help of JOOQ in the JooqRepository.
interface CategoryRepository extends CrudRepository<Category, Long>, JooqRepository {
#Query("SELECT * FROM category")
List<Category> findAllWithQuery();
}
public interface JooqRepository {
List<Category> findAllWithJooq();
}
public class JooqRepositoryImpl implements JooqRepository {
private final DSLContext dslContext;
public JooqRepositoryImpl(DSLContext dslContext) {
this.dslContext = dslContext;
}
#Override
public List<Category> findAllWithJooq() {
return dslContext.select()
.from(CATEGORY)
.fetchInto(Category.class);
}
}
(for me both methods should return the same result-set b/c they execute the same query?!)
But my unit-test fails:
#Test
public void exerciseRepositoryForSimpleEntity() {
// create some categories
SubCategory sub0 = new SubCategory(null, "sub0");
SubCategory sub1 = new SubCategory(null, "sub1");
Category cars = new Category(null, "Cars", "Anything that has approximately 4 wheels", AgeGroup._3to8, Sets.newLinkedHashSet(sub0, sub1));
// save category
repository.saveAll(asList(cars));
// execute
List<Category> actual = repository.findAllWithJooq();
List<Category> compare = repository.findAllWithQuery();
Output.list(actual, "JOOQ");
Output.list(compare, "Query");
// verify
assertThat(actual).as("same size of categories").hasSize(compare.size());
assertThat(actual.get(0).getSubCategories()).as("same size of sub-categories").hasSize(compare.get(0).getSubCategories().size());
}
with
java.lang.AssertionError: [same size of sub-categories]
Expecting actual not to be null
As you can see in the following output the sub-categories queried by JOOQ will not be loaded:
2019-11-26 16:28:00.749 INFO 18882 --- [ main] example.springdata.jdbc.jooq.Output : ==== JOOQ ====
Category(id=1,
name=Cars,
description=Anything that has approximately 4 wheels,
ageGroup=_3to8,
subCategories=null)
2019-11-26 16:28:00.749 INFO 18882 --- [ main] example.springdata.jdbc.jooq.Output : ==== Query ====
Category(id=1,
name=Cars,
description=Anything that has approximately 4 wheels,
ageGroup=_3to8,
subCategories=[SubCategory(id=1,
title=sub0),
SubCategory(id=2,
title=sub1)])
This is the used database-shema:
CREATE TABLE IF NOT EXISTS category (
id INTEGER IDENTITY PRIMARY KEY,
name VARCHAR(100),
description VARCHAR(2000),
age_group VARCHAR(20)
);
CREATE TABLE IF NOT EXISTS sub_category (
id INTEGER IDENTITY PRIMARY KEY,
title VARCHAR(100),
category INTEGER
)
In the JOOQ variant, JOOQ does the conversion from ResultSet to object instances. Since JOOQ doesn't know about the interpretation of aggregates as it is done by Spring Data JDBC it only hydrates the Category itself, not the contained Set of SubCategory.
Spring Data JDBC on the other hand interprets the structure of the Category and based on that executes another statement to load the subcategories.

Using Spring Data JPA - how to save ONLY UNIQUE items in child entity while saving parent entity and using CascadeType=PERSIST

I am preparing simple Spring app. I have 2 entities :
Book.class (parent) and Author.class (child): with #OneToMany from Author view and #ManyToOne(cascade=CascadeType.PERSIST) from Book view relations. While saving new Book - also Author is being saved and added to DB( mySql)- which is what I want. But I cannot understand why Spring adds Author - if such item already exists. How to change the code to make sure that only unique Authors will be added to DB and there will be no duplicates in author table in DB?
I've added hashCode and equals methods to Author class but it did not help.
I've tried to change also Cascade.Type but also did not help.
The Author.class(part of code):
#Entity
public class Author {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
#OneToMany(mappedBy = "author")
#JsonManagedReference(value = "book-author")
private Set<Book> books = new HashSet<Book>();
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Author author = (Author) o;
return Objects.equals(getFirstName(), author.getFirstName()) &&
Objects.equals(getLastName(), author.getLastName());
}
#Override
public int hashCode() {
return Objects.hash(getFirstName(), getLastName());
}
And the Book.class(part of code):
#Entity
public class Book {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String title;
#ManyToOne( cascade=CascadeType.PERSIST)
#JoinColumn(name = "author_id", unique = true)
#JsonBackReference(value="book-author")
private Author author;
Edit 1
BookServiceImpl.class
#Override
public BookDto addBookDto(BookDto bookDto) {
Book book = bookConverter.apply(bookDto);
bookRepository.save(book);
return bookDtoConverter.apply(book);
}
AuthorServiceImpl.class
#Override
public Author findAuthor(String firstName, String lastName) {
Optional<Author> authorByNameOptional = authorRepository.findByFirstNameAndLastName(firstName, lastName);
if (authorByNameOptional.isPresent()) {
return authorByNameOptional.get();
} else {
Author newAuthor = new Author();
newAuthor.setFirstName(firstName);
newAuthor.setLastName(lastName);
return newAuthor;
}
And BookWebController.class
#PostMapping("/addWebBook")
public String addBook(#ModelAttribute(name = "addedBook") BookDto addedBook, Model model) {
Author author1 = addedBook.getAuthor();
Author author = authorService.findAuthor(author1.getFirstName(), author1.getLastName());
addedBook.setAuthor(author);
bookService.addBookDto(addedBook);
return "redirect:/message?msg";
}
Would be greatful for any hint as I am quite new to this area :-)
Let me suggest that your Author object in Book has empty primary key field? Hibernate's logic in this case: empty id means new row to insert. It may work correctly if you set a primary key to author. For example, user can find author (with it's PK) or add new (without PK) and call save(book) method which will cascadely persists only new author. In most cases that usually works like that.
Another moment to pay attention, that if you wanna keep author's uniqueness in database, than you must to put constraint on the author's entity.
For example if each author must have unique first name and last name it may look something like this:
#Entity
#Table(uniqueConstraints= #UniqueConstraint(columnNames={"first_name", "last_name"}))
public class Author {
...
After that, DataIntegrityViolationException will be thrown on duplicating value insertion and your database will stay clean of duplicates.

Spring Data MongoDB #Indexed(unique = true) in inner field

For example, there are 2 classes:
#Document
public class WordSet {
#Id
private ObjectId id;
private Language language;
private ObjectId languageId;
}
#Document
public class Language {
#Id
private ObjectId id;
#Index(unique = true)
private String languageName;
}
Languages are stored in separate collection and WordSets are stored in another collection. BUT WordSet is stored only with languageId (language is always null when I save WordSet). language field in WordSet is needed, but it retrieved using aggregation
public Flux<WordSet> getAll() {
AggregationOperation[] joinLanguages = new AggregationOperation[] {
lookup(mongoTemplate.getCollectionName(Language.class), "languageId", "_id", "language"),
unwind("language")
};
Aggregation agg = newAggregation(joinLanguages);
return mongoTemplate.aggregate(agg, WordSet.class, WordSet.class);
}
So, WordSet in mongodb contains only languageId and language field is filled using aggregation (join from Language collection).
But if I want to add more than one WordSet to collection I have an error
com.mongodb.MongoWriteException: E11000 duplicate key error collection: langdope.wordSet index: language.language_name_index dup key: { : null }
How can I handle it? I need languageName to be unique, but also I want to save objects which contains Languages without this problems. I can't just mark language as #Transient (aggregation will not work).

Spring data jpa Specification: How to filter a parent object by its children object property

My entity classes are following
#Entity
#table
public class User {
#OneToOne
private UserProfile userProfile;
// others
}
#Entity
#Table
public class UserProfile {
#OneToOne
private Country country;
}
#Entity
#Table
public class Country {
#OneToMany
private List<Region> regions;
}
Now I want to get all the user in a particular region. I know the sql but I want to do it by spring data jpa Specification. Following code should not work, because regions is a list and I am trying to match with a single value. How to fetch regions list and compare with single object?
public static Specification<User> userFilterByRegion(String region){
return new Specification<User>() {
#Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
return criteriaBuilder.equal(root.get("userProfile").get("country").get("regions").get("name"), regionalEntity);
}
};
}
Edit: Thanks for the help. Actually I am looking for the equivalent criteria query for the following JPQL
SELECT u FROM User u JOIN FETCH u.userProfile.country.regions ur WHERE ur.name=:<region_name>
Try this. This should work
criteriaBuilder.isMember(regionalEntity, root.get("userProfile").get("country").get("regions"))
You can define the condition for equality by overriding Equals method(also Hashcode) in Region class
Snippet from my code
// string constants make maintenance easier if they are mentioned in several lines
private static final String CONST_CLIENT = "client";
private static final String CONST_CLIENT_TYPE = "clientType";
private static final String CONST_ID = "id";
private static final String CONST_POST_OFFICE = "postOffice";
private static final String CONST_INDEX = "index";
...
#Override
public Predicate toPredicate(Root<Claim> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<Predicate>();
// we get list of clients and compare client's type
predicates.add(cb.equal(root
.<Client>get(CONST_CLIENT)
.<ClientType>get(CONST_CLIENT_TYPE)
.<Long>get(CONST_ID), clientTypeId));
// Set<String> indexes = new HashSet<>();
predicates.add(root
.<PostOffice>get(CONST_POST_OFFICE)
.<String>get(CONST_INDEX).in(indexes));
// more predicates added
return return andTogether(predicates, cb);
}
private Predicate andTogether(List<Predicate> predicates, CriteriaBuilder cb) {
return cb.and(predicates.toArray(new Predicate[0]));
}
If you are sure, that you need only one predicate, usage of List may be an overkill.

Resources