Spring: combine JPA Derived query methods and query by example - spring

Is it possible to use JPA derived methods and query by example at the same time?
Let's imagine i have two entities like this:
#Entity
#Data
public class Person {
#Id
#GeneratedValue
Long id
String name;
String surname;
#OneToMany
List<Dog> dogs;
}
#Entity
#Data
public class Dog{
#Id
#GeneratedValue
Long id
String name;
}
I'd like to be able to do something like this (just an example):
Person p = new Person ();
p.setName("Mario");
personRepository.findDistinctByDogsIsNotNull(Example.of(p));
The Example.of(p) only works if i do findAll, but it doesn't work if i define inside the repository a method like this
private interface PersonRepository extends JpaRepository<Person, Long>{
List<Person> findDistinctByDogsIsNotNull(Example<Person> example)
}
The error it gives me is something like this:
Failed to create query for method public abstract java.util.List dev.cele.test.repository.PersonRepository.findDistinctByDogIsNotNull(org.springframework.data.domain.Example)! At least 1 parameter(s) provided but only 0 parameter(s) present in query.
So my question is: is it possible to do a query by example in a JPA derived query method?
And if it's not possible how can i create some sort of parametrizable query that also has a predetermined condition?

Related

Spring hibernate orderBy on list element

#Entity
class Person{
private int id;
#OneToMany(mappedBy=owner)
private List<Pet> pets;
}
#Entity
class Pet{
private name;
private ZonedDateTime birthDate;
#ManyToOne
#JoinColumn(name="owner_id")
private Person owner;
}
I want to find all the persons and order them by their oldest pet birthday
The only way I can solve this is through #Formula , something like
#Entity
class Person{
private int id;
private List<Pet> pets;
#Formula("(SELECT p.birth_date FROM pet p WHERE p.owner_id = id order by p.birth_date ASC LIMIT 1)")
private ZonedDateTime oldestPetBirthday;
}
then
public List<Person> findPersonByOrderByOldestPetBirthdayAsc
But I don't want to touch raw sql, I am looking for something like
public List<Person> findPersonByOrderByPetsTop1OrderByBirthDateAsc
OR by using pageable something like:
PageRequest.of(page,pageSize,Sort.by(ASC, "pets.sort(BirthDateComparator).get(0)"))
is that possible?
Try to use #OrderBy annotation from #javax.persistence.OrderBy package on your one to many collection object.
#OrderBy("birthDate")
private List<Pet> pets;
Your solution with the formula is ok but suffers from some issues. Anyway, since you don't want to write SQL, you will have to use something like Blaze-Persistence Entity Views.
I created the library to allow easy mapping between JPA models and custom interface or abstract class defined models, something like Spring Data Projections on steroids. The idea is that you define your target structure(domain model) the way you like and map attributes(getters) via JPQL expressions to the entity model.
A DTO model for your use case could look like the following with Blaze-Persistence Entity-Views:
#EntityView(Person.class)
public interface PersonDto {
#IdMapping
Long getId();
#Limit(limit = "1", order = "birthDate desc)
#Mapping("pets")
OldestPetDto getOldestPet();
#EntityView(Pet.class)
interface OldestPetDto {
#IdMapping
Long getId();
ZonedDateTime getBirthDate();
}
}
Querying is a matter of applying the entity view to a query, the simplest being just a query by id.
PersonDto a = entityViewManager.find(entityManager, PersonDto.class, id);
The Spring Data integration allows you to use it almost like Spring Data Projections: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features
Page<PersonDto> findAll(Pageable pageable);
The best part is, it will only fetch the state that is actually necessary!
Also, you can add a Sort for oldestPet.birthDate and it will work just like you would like it to!

OneToMany in MappedSuperclass

I was trying to use #MappedSuperclass to share the same table between two entities following this article here (How to map multiple JPA entities to one database table with Hibernate),
So I have these 3 classes:
#MappedSuperclass
abstract class UserDao {
#Id
#Column(name = "username", nullable = false, unique = true)
var username: String? = null
#OneToMany(fetch = FetchType.EAGER)
var groups: Set<GroupDao>? = null
}
then:
#Entity(name = "basic_user_auth")
#Table(name = "users")
class BasicUserDao : UserDao() {
}
and:
#Entity(name = "full_auth_user")
#Table(name = "users")
class FullUserDao : UserDao() {
#OneToOne
#PrimaryKeyJoinColumn
var profileJpa: ProfileDao? = null
}
what I was trying is to save some queries overhead of loading the user profile when its not needed, but now when i try to run the app i get the following error:
could not execute statement; SQL [n/a]; constraint [full_auth_user_username" of relation "users_groups];
not sure why Hibernate creates this relation since they both share the same table.
I would recommend you don't share types on the entity level. Sharing a one-to-many association will probably not work as you expect with respect to flushing/synchronization when multiple such entities are involved. IMO you should try out a DTO approach instead.
I think this is a perfect use case for Blaze-Persistence Entity Views.
I created the library to allow easy mapping between JPA models and custom interface or abstract class defined models, something like Spring Data Projections on steroids. The idea is that you define your target structure(domain model) the way you like and map attributes(getters) via JPQL expressions to the entity model.
A DTO model for your use case could look like the following with Blaze-Persistence Entity-Views:
#EntityView(User.class)
public interface BasicUserDao {
#IdMapping
String getUsername();
Set<GroupDao> getRoles();
#EntityView(Group.class)
interface GroupDao {
#IdMapping
Long getId();
String getName();
}
}
#EntityView(User.class)
public interface FullUserDao extends BasicUserDao {
#Mapping("profileJpa")
ProfileDao getProfile();
#EntityView(Profile.class)
interface ProfileDao {
#IdMapping
Long getId();
String getName();
}
}
Querying is a matter of applying the entity view to a query, the simplest being just a query by id.
BasicUserDao a = entityViewManager.find(entityManager, BasicUserDao.class, id);
The Spring Data integration allows you to use it almost like Spring Data Projections: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features
#Repository
interface UserRepository {
List<BasicUserDao> findAll();
}
The best thing about it is, that it will only fetch the data that is actually needed.

how to write the JpaRepository for tables which has composite keys

Please refer attached screenshot to understand the table structure.
Empd_Id is the primary key in 'Employee' table which in turn becomes as a part of composite key along with 'product_id' in table called 'product'.
Any employee can have multiple products so in that case it becomes 'One-to-Many' relationship between 'Employee-Product' tables. Now I'm confused whether I need to write just 1 JpaRepository interface i.e. for employee or 2 JpaRepository interfaces (1 for Employee and another for Product). My gut feeling is just 1 interface for Employee table but how???
Following is my code snippet:-
1st JPA repository interface
public interface MyRepository extends JpaRepository<Product, EmpProd> {
}
Entity:-
#Entity
#Table(name="product")
public class Product{
#EmbeddedId
private EmpProd empProd;
#Column(name="product_name")
private String commerceUserId;
#Column(name="description")
private String description;
For composite keys:-
#Embeddable
public class EmpProd implements Serializable{
private static final long serialVersionUID = 1L;
#NotNull
#Column(name="emp_id")
private String empId;
#NotNull
#Column(name="product_id")
private String productId;
2nd Jpa repository interface
public interface MyMainDataRepository extends JpaRepository<Employee, String> {
}
Entity class:-
#Entity
#Table(name="employee")
public class Employee{
#Id
#NotNull
#Column(name="emp_id")
private String empId;
#Column(name="first_name")
private String firstName;
Though, I have written 2 separate JPA repositories, I strongly believe there will be need for just 1, the main one i.e.
public interface MyMainDataRepository extends JpaRepository {
}
But I do not know to related both entity classes and fetch data from using single Jpa repository as I'm new to Spring Data JPA. I would really appreciate if someone can help me here. Thanks
The two entities Product and Employee don't have any connection as far as JPA is concerned. Therefore you can't access both through a single repository.
If for example, Product would have an actual reference to an Employee you could use a ProductRepository to load Products and navigate from there to the referenced Employees.
But even if that might be feasible, I'd guess that Product and Employee should be considered different aggregates and therefore, should have their own repository each. See Are you supposed to have one repository per table in JPA? for more information on that question.
Given the entities, your repositories look just fine. Note that the entities do look atypical due to the use of String productId instead of Product product.
If you wanted to fetch the employee details, you need the following interface,
public interface MyMainDataRepository extends JpaRepository<Employee, String> {
}
If you wanted to fetch the product details, you need the following interface,
public interface MyRepository extends JpaRepository<Product, EmpProd> {
}
The employee is related to product table, the iteration happens via product and related employees. From this, you can not access the employee table directly and retrieve the employee results from MyRepository interface.

Spring Jpa Query by Example collection

Let's say I have an entity
public class Person {
private String id;
private String firstname;
private String lastname;
private Set<Car> ownedCars;
}
Is there a way I can use query by example to find any person named James having both a Ferrari and Lamborghini?
If I use:
Person p = new Person();
p.setName("James");
p.getOwnedCars.addCar(new Car("Lamborgnihi"));
p.getOwnedCars.addCar(new Car("Ferrari"));
Example<Person> exampleOfPerson = Example.of(p);
List<Person> foundPersons = personRepository.finaAll(exampleOfPerson);
it seems it queries only on person's attributes and ignores any child collections.
You can use a query method for that. Let's say your Car has a property name that can be "Lamborghini" or "Ferrari"
interface PersonRepository extends JpaRepository<Person, String> {
List<Person> findByOwnedCarsNameIn(Collection<String> names);
}
Then you use it like this:
personRepository.findByOwnedCarsNameIn(Arrays.asList("Ferrari","Lamborghini"));
Some gotchas:
The method parameter can take any subclass of Collection, or an array.
The property names on Person and Car must match the method signature and the parameter name as shown above for spring to know how to generate the query, i.e. Person must have a property called "cars", and Car must have a property called "name".
I used JpaRepository, but this works with any of the Repository interfaces provided with spring data JPA

Spring data query where column is null

Suppose I have entities (getters/setters and various details omitted for brevity):
#Entity
class Customer{
...
#OneToMany(cascade = CascadeType.ALL, mappedBy = "customer")
Collection<Coupon> coupons;
}
#Entity
class Coupon{
...
#Temporal(value = TemporalType.TIMESTAMP)
private Date usedOn;
#ManyToOne(fetch = FetchType.LAZY)
#NotNull
Customer customer;
}
I wish retrieve all Coupons for a given Customer having null usedOn.
I,'ve unsuccessfully defined a method in the CouponRepository as described in docs
#Repository
public interface CouponRepository extends CrudRepository<Coupon, Long> {
Collection<Coupon> findByCustomerAndUsedOnIsNull(Customer);
}
but this leads on a compiler error Syntax error, insert "... VariableDeclaratorId" to complete FormalParameterList.
My fault, the correct definition is
#Repository
public interface CouponRepository extends CrudRepository<Coupon, Long> {
Collection<Coupon> findByCustomerAndUsedOnIsNull(Customer customer);
}
I simply missed the parameter name :-(
You can use IsNull to check null columns in JPA query.
For example for any columnA you can write query like query like
findByColumnAIsNull
In this case you can write queries like
#Repository
public interface CouponRepository extends CrudRepository<Coupon, Long> {
Collection<Coupon> findByCustomerAndUsedOnIsNull(Customer customer);
List<Coupon> findByUsedOnIsNull();
}
Also you can check how this queries will be
Refer this Spring Data JPA Query creation this will help you lot to understand and create different type of JPA query variation.
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation
Try changing your method to this (assuming Customer.id is a long):
Collection<Coupon> findByCustomer_IdAndUsedOnIsNull(Long customerId);
then use like this:
repo.findByCustomer_IdAndUsedOnIsNull(customer.getId());

Resources