DTO Projection of Query with #ElementCollection causes 'Unable to locate appropriate constructor on class' error - spring

I'm writing custom query using projection to reduce amount of queries in one session, when couple of field from antity are needed and using Fetch join.
Unfortunately got stuck into a problem when one types in returned dto is a collection.
I have following class with #ElementCollection (siplified version for this purpose):
#Entity
class MyClass(
val someString: String,
#ElementCollection
#Enumerated(EnumType.STRING)
var enums: MutableSet<Enum>,
#ManyToOne
var condition: Condition
//And so on...
)
And DTO used for projection:
data class ProjectionDTO(
val aString: String,
val enumList: List<Enum>
)
But when using query:
fun query(condition: Condition): List<ProjectionDTO> =
entityManager.createQuery(
"""SELECT NEW com.xxx.ProjectionDTO( m.someString, e ) FROM MyClass m
INNER JOIN FETCH m.enums e
WHERE m.condition = :condition""", ProjectionDTO::class.java)
.setParameter("condition", condition)
.resultList
}
I get following exception:
Exception:[org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate appropriate constructor on class [com.xxx.ProjectionDTO]. Expected arguments are: com.xxx.String, com.xxx.Enum [SELECT NEW com.xxx.ProjectionDTO( m.someString, e ) FROM MyClass m
INNER JOIN FETCH m.enums e
WHERE m.condition = :condition]]
Already tried different types of collection, additional constructors and calling field of given #ElementCollection like e.enum in query params.
Is it possible to return a list (or other collection) from this kind of query? If so, how do I tackle it?

It is not allowed to use collection path expressions in constructor query. link
Put just root entity into constructor:
SELECT NEW com.xxx.ProjectionDTO(m) WHERE m.condition = :condition
In constructor assign m.enums, m.someString to fields.

Related

How to INNER JOIN a jsonb column with CriteriaBuilder

I've been researching a while about how can I implement an Inner Join using CriteriaBuilder, but the thing is that one of the arguments which both tables have in commons is located inside a jsonb column, so the question is:
How can I INNER JOIN 2 tables by an argument that is located inside a jsonb column called "data" with criteria?
I'll drop down the example code of what I currently have.
public final CriteriaQuery<TutenBookingMacarena> createRatedBookings(
MacarenaBookingSearchFilter filters,
Integer page,
Integer pageSize,
Security security
) {
final CriteriaBuilder builder = entityManager.getCriteriaBuilder();
final CriteriaQuery<TutenBookingMacarena> criteria = builder.createQuery(TutenBookingMacarena.class);
final Root<TutenBookingMacarena> root_Booking = criteria.from(TutenBookingMacarena.class);
Join<TutenBookingMacarena, TutenCaseMacarena> rootJoin = root_Booking.join(String.valueOf(
builder.function("jsonb_extract_path_text",
String.class,
root_Booking.<String>get("data"),
builder.literal("caseId")
)
));
...
}
But when executing those lines of code I get an error message that says the named attribute can not be found. Any idea what's wrong here?

spring jpa query SQLGrammarException on join #ManyToMany

I have Way POJO in my Spring Boot application, here is what it looks like:
public class Way {
#Id
private Long wayID;
#ToString.Exclude
#JsonIgnore
#ManyToMany(fetch = FetchType.LAZY,cascade=CascadeType.ALL)
private List<Relation> relations=new ArrayList<>();
Now I want to select all the ways that has relationID of a given value.
relationID is a member of Relation POJO.
So here is my query
#Query("select w from Way w join Relation relations where relations.relationID=?1")
List<Way> selectAllWaysByRelationID(Long relationID);
But the error seems to be in my JOIN portion, it crashes and says:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; SQL [select way0_.wayid as wayid1_5_ from way way0_ inner join relation relation1_ on where relation1_.relationid=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
How can I resolve this ?
I also tried this:
#Query("select way from Way.relations full join Way.relations rel where rel.relationID=?1")
List<Way> selectAllWaysByRelationID(Long relationID);
This too:
#Query("select way from Way way join Way.relations rel where rel.relationID=?1")
List<Way> selectAllWaysByRelationID(Long relationID);
When using JOIN you need to use alias of Way with relations field like this, w.relations r instead of Way.relations.
The complete query is below:
#Query("select w from Way w join w.relations r where r.relationID=?1")
List<Way> selectAllWaysByRelationID(Long relationID);

QueryDSL Paging Sorting duplicates

I have got an Entity A say Car with a OneToMany relationship to an Entity B say CarProperty.
My Car Repository extends QueryDslPredicateExecutor to support paging and sorting:
Page<T> findAll(Predicate predicate, Pageable pageable);
I'm trying to execute a query where I sort the results, by a column of CarProperty, defining the sort on pageable variable.
However since it is a One To Many relationship between Car and CarProperty, I have returned duplicates of Car.
Is it possible to obtain distinct results on Car using this structure?
If it is not possible to use distinct on the Predicate, how could I represent the following query in the predicate (using exists to eliminate duplicates):
SELECT Car.*
FROM Car C LEFT JOIN CarProperty CP ON (C.ID = CP.CAR_ID)
WHERE EXISTS (SELECT 1
FROM CarProperty CP2
WHERE CP2.CAR_ID = C.ID AND CP2.ID = CP.ID)
ORDER BY CP.PROPERTY_NAME ASC;
Thanks in advance
You can use named entity graph to avoid duplicate records, in my case it worked.
#NamedEntityGraph(name = "Car.carProperty" ,attributeNodes = #NamedAttributeNode("carProperties"))
#Entity
public class Car {
#OneToMany
#JoinColumn(name = "carProperties")
private List<CarProperty> carProperties;
}
and then override findall method
#EntityGraph(value = "Car.carProperty" , type = EntityGraphType.LOAD)
Page<Car> findAll(Predicate predicate, Pageable pageable);

Filter with Spring-Data and QueryDSL on nullable reference attribute

I have following issue. I am using Jquery Datatable serverside and I am now implementing the search box. But I have an issue there in special case, when a dataset has an attribute, what is "null". So the dataset will not be found although it should found cos it matches on one attibute.
The situtation in beginning is like follows. You see there is a dataset with apprentice Fabio Bartels, who has not Fachrichtung. And a dataset with Viktoria.
Now when I search for Viktoria, the filter works as expected:
When I search for Fabio, then Dataset is not found:
=====
The problem I have is, that I don't know how to handle the filter, that a attribute will only be validated against the search string when the attribute is not null.
=====
Serverside Java Classes see like follows:
QueryClass:
class ContractSearchQuery {
private static QContract contract = QContract.contract;
static BooleanExpression getPredicate(final ContractSearch filter) {
BooleanExpression predicate;
if (filter == null || filter.isEmpty()) {
// SHOW ALL PREDICATE ...
} else {
final String search = filter.getSearch();
final List<BooleanExpression> expressions = new ArrayList<BooleanExpression>();
// EXPRESSIONS CURRENTLY ONLY ON AUSZUBILDENDER AND FACHRICHTUNG
// FOR SHOWCASE
expressions.add(containsApprenticeName(search)); // AUSZUBILDENDER
expressions.add(containsSpecialisation(search)); // FACHRICHTUNG
BooleanExpression expression = expressions.get(INTEGER_ZERO);
for (int i = 1; i < expressions.size(); i++) {
expression = expression.or(expressions.get(i));
}
predicate = expression;
}
return predicate;
}
private static BooleanExpression containsApprenticeName(final String search) {
final BooleanExpression expLastName = contract.apprentice.lastName.containsIgnoreCase(search);
final BooleanExpression expFirstName = contract.apprentice.firstName.containsIgnoreCase(search);
return expLastName.or(expFirstName);
}
private static BooleanExpression containsSpecialisation(final String search) {
return contract.companyOccupationCombination.occupationCombination.specialisation.name.containsIgnoreCase(search);
}
}
Spring-Data-Repository Call:
final PageRequest pageRequest = new PageRequest(firstResult / maxResults, maxResults, orderSort);
final Page<Contract> page = contractRepository.findAll(predicate, pageRequest);
return page.getContent();
=======
Database:
By the way I recognized when I do direct request against my db with joining Specialisation Table, then I only get Fabio as record, when not joining Specialisation, I get all three persons. Maybe somethings to do with my issue:
select a.first_name, a.last_name from contract c
join company_occupation_combination coc on c.company_occupation_combination = coc.id
join occupation_combination oc on coc.occupation_combination = oc.id
join apprentice a on c.apprentice = a.id
Result:
"Fabio";"Bartels"
"Viktoria";"Kruczek"
"Lina";"Ehleiter"
With Join:
select a.first_name, a.last_name from contract c
join company_occupation_combination coc on c.company_occupation_combination = coc.id
join occupation_combination oc on coc.occupation_combination = oc.id
join specialisation s on oc.specialisation = s.id
join apprentice a on c.apprentice = a.id
Result: "Viktoria";"Kruczek"
====
EDIT:
Okay, on db site I found out (with Hibernate and JPA I start forgetting SQL-Basices ;-)), that I need a left join for the nullable relation, so my query should result to an sql like:
select a.first_name, a.last_name from contract c
join company_occupation_combination coc on c.company_occupation_combination = coc.id
join occupation_combination oc on coc.occupation_combination = oc.id
left join specialisation s on oc.specialisation = s.id
join apprentice a on c.apprentice = a.id
====
So my question is, how can I manage left Join when I have a Query-Class using QueryDSL and Spring-Data-Repository like mentioned above?
If you really need left join, you can't achieve that via predicate (instead it is possible via sub-query)
To be able to do left-join, you will need JPAQuery.
Assuming you have already configured repositories, and able to use EntitiManager, implement ContractRepositoryCustom , so that in your implementation you can have
#PersistenceContext(unitName = "unitname")
protected EntityManager entityManager;
public List<Contract> findAllContracts() {
return new JPAQuery(entityManager, HQLTemplates.DEFAULT)
.from(QContract.contract)
.join(QContract.contract.companyOccupationCombination, QCompanyOccupationCombination.companyOccupationCombination)
.join(QCompanyOccupationCombination.companyOccupationCombination.occupationCombination, QOccupationCombination.occupationCombination)
.leftJoin(QOccupationCombination.occupationCombination.specialization, QSpecialization.specialization)
.join(QSpecialization.specialization.apprentice, QApprentice.apprentice)
.list(QContract.contract);
}
And for pagination you always apply limit(maxResults) and offset(firstResult)
I really like working with Spring-Data and Query-DSL, cos it makes my code really tidy. But I am really suprised, that for the case of nullable references there seems no solution. Sure you can use another solution like #vtorosyan mentioned and thank you again for that solution, but when you project is builded up with combination of QueryDSL and Spring-Data, you really don't want to bring a second style in your application.
But I needed a solution, so I did now the follows.
The point of the issue was, that when I used data from a nullable entity, a join has been executed what hided the datasets, who had a null reference on it, see examples above. What I now did and I hope I will not get another issue then with that solution on later time of that project. I did the null references to not null and defined something like null-record.
Example I added a record for specialisation like
ID NAME
0 Keine
Instead of null I now use that record what has until now following effects:
First my table shows now "Keine" (engl. "None") for all attributes what are not set. It looks more consistent when having a textoutput then empty string.
Now I can explicitly search for "Keine", when I am interested for data records what have no specialisation set.
And my searchbox works as expected for records, which have no speciafication set. (THAT WAS MY ISSUE FROM BEGINNING WHAT I WANTED TO SOLVE):
Additional to that searchbox I use a modal dialog for filtering. Now I can explicitly filter "Keine" for "nullable" records:
If you think there is another good solution for that issue without rebuild code using Spring-Data and QueryDSL konsequently, don't hesitate to post ;-)

JpaRepository: using repositories in #PostPersist

I have two entities
class A {
...
Integer totalSum;
Set<B> b;
}
class B {
...
Integer value;
A container;
}
I want a.totalSum to be sum of each a.b.value;
Maybe best solution is view in db, but I want listen changes in BRepository and update A-records.
I do:
#PostPersist
#PostUpdate
#PostRemove
private void recalculateSums(B b) {
AutowireHelper.autowire(this, this.aRepository);
AutowireHelper.autowire(this, this.bRepository);
A a = b.getContainer();
a.setTotalSum(bRepository.sumByA(s));
aRepository.save(s);
}
And in BRepository:
#Query("select sum(b.value) from B b where b.container = :a")
Long sumByA(#Param("a") A a);
And I have error: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["PRIMARY KEY ON PUBLIC.B(ID)"; SQL statement:
insert into b (VALUE, CONTAINER_ID, ID) values (?, ?, ?)
What I'm doing wrong?
If I do
a.setTotalSum(a.getTotalSum()+1);
aRepository.save(s);
All works, but if I do
a.setTotalSum(a.getTotalSum()+1);
aRepository.saveAndFlush(s);
I have the same error.
I can see why you might want to do this but I think it creates a whole load of potential issues around data integrity.
If you want to have the sum of B available for an A without having to load and iterate all B there are three other options which you could implement all of which would be more robust than your proposal.
As you noted, create a view. You can then Map an Entity say, SummaryData, to this view and map a one-to-one from A to SummaryData so that you can do a.getSummaryData().getTotalSum();
Alternatively, you could use the Hibernate specific #Formula annotation which will issue an inline select when the entity is loaded.
#Formula("(select sum(value) from B b inner join A a where b.a_id= a.id and a.id =id
private int totalSum;
Finally, and depending on the capabilities of your database, you could create a Virtual Column and Map a property as you would for any other field.
1 and 3 obviously require schema changes but your app would remain JPA compliant. 2 does not require any schema change but breaks strict JPA compliance if that was important.

Resources