How to use projection and where clause in JPA criteria? - java

I have entity Person
#Entity(name = "Person")
public class Person {
#Id
#GeneratedValue
private Long id;
private String name;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "person")
private Set<Phone> phones=new HashSet<Phone>();
public Person() {
}
public Person(String name) {
this.name = name;
}
Ad entity Phone :
#Entity(name = "Phone")
public class Phone {
#Id
#GeneratedValue
private Long id;
#Column(name = "`number`")
private String number;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "person_id", nullable = false)
private Person person;
public Phone() {
}
They have one-to-many relation.
Now I want to build in jpa criteria such query:
select p.phones from person p join phone ph where p.name = :name;
So I want to extract Set<Phone> phones from Person entity where person's name is parameter.
I've written this jpa criteria query:
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Person> query = builder.createQuery(Person.class);
Root<Person> root = query.from(Person.class);
CriteriaQuery<Person> where = query.where(builder.equal(root.get("name"), "Mary Dick"));
CompoundSelection<Set> projection = builder.construct(Set.class, root.get("phones"));
where.select(projection); //compile error: The method select(Selection<? extends Person>) in the type CriteriaQuery<Person> is not applicable for the arguments (CompoundSelection<Set>)
}
But it gives compile error:
The method select(Selection<? extends Person>) in the type CriteriaQuery<Person> is not applicable for the arguments (CompoundSelection<Set>)
How is it correct? Do I need metamodel classes?

CompoundSelection<Y> construct(Class<Y> result, Selection<?>... terms)
This method is useful only when the query would involve certain projections which are not entirely encapsulated by a single entity class. If that is the case, first parameter would be the custom POJO class (with suitable constructor) with fields which corresponding to the select clause of the query.
In this case, the selection is already a part of the entity class. So, you can simply choose the fields you need.
CriteriaQuery<Person> query = builder.createQuery(Person.class);
Root<Person> root = query.from(Person.class);
query.where(builder.equal(root.get("name"), "Mary Dick"));
query.select(root.get("phones"));
Above query will return a list of person. But if you are looking for just an iterable list of phones, try with a slightly different query.
select ph from phone ph join ph.person p where p.name = :name;
And its equivalent CriteriaQuery:
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Phone> query = builder.createQuery(Phone.class);
Root<Phone> root = query.from(Phone.class);
Join<Phone, Person> join = root.join(root.get("person"))
query.where(builder.equal(join.get("name"), "Mary Dick"));

Related

JPA Criteria multiselect with fetch

I have following model:
#Entity
#Table(name = "SAMPLE_TABLE")
#Audited
public class SampleModel implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
private Long id;
#Column(name = "NAME", nullable = false)
#NotEmpty
private String name;
#Column(name = "SHORT_NAME", nullable = true)
private String shortName;
#ManyToOne(fetch = FetchType.LAZY, optional = true)
#JoinColumn(name = "MENTOR_ID")
private User mentor;
//other fields here
//omitted getters/setters
}
Now I would like to query only columns: id, name, shortName and mentor which referes to User entity (not complete entity, because it has many other properties and I would like to have best performance).
When I write query:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<SampleModel> query = builder.createQuery(SampleModel.class);
Root<SampleModel> root = query.from(SampleModel.class);
query.select(root).distinct(true);
root.fetch(SampleModel_.mentor, JoinType.LEFT);
query.multiselect(root.get(SampleModel_.id), root.get(SampleModel_.name), root.get(SampleModel_.shortName), root.get(SampleModel_.mentor));
query.orderBy(builder.asc(root.get(SampleModel_.name)));
TypedQuery<SampleModel> allQuery = em.createQuery(query);
return allQuery.getResultList();
I have following exception:
Caused by: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=generatedAlias1,role=com.sample.SampleModel.model.SampleModel.mentor,tableName=USER_,tableAlias=user1_,origin=SampleModel SampleModel0_,columns={SampleModel0_.MENTOR_ID ,className=com.sample.credential.model.User}}]
at org.hibernate.hql.internal.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:214)
at org.hibernate.hql.internal.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:991)
at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:759)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:675)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:311)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:259)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:262)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:190)
... 138 more
Query before exception:
SELECT DISTINCT NEW com.sample.SampleModel.model.SampleModel(generatedAlias0.id, generatedAlias0.name, generatedAlias0.shortName, generatedAlias0.mentor)
FROM com.sample.SampleModel.model.SampleModel AS generatedAlias0
LEFT JOIN FETCH generatedAlias0.mentor AS generatedAlias1
ORDER BY generatedAlias0.name ASC
I know that I can replace fetch with join but then I will have N+1 problem. Also I do not have back reference from User to SampleModel and I do not want to have..
I ran into this same issue, and found that I was able to work around it by using:
CriteriaQuery<Tuple> crit = builder.createTupleQuery();
instead of
CriteriaQuery<X> crit = builder.createQuery(X.class);
A little extra work has to be done to produce the end result, e.g. in your case:
return allQuery.getResultList().stream()
map(tuple -> {
return new SampleModel(tuple.get(0, ...), ...));
})
.collect(toList());
It's been a long time since the question was asked. But I wish some other guys would benefit from my solution:
The trick is to use subquery.
Let's assume you have Applicant in your Application entity (one-to-one):
#Entity
public class Application {
private long id;
private Date date;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "some_id")
private Applicant applicant;
// Other fields
public Application() {}
public Application(long id, Date date, Applicant applicant) {
// Setters
}
}
//...............
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Application> cbQuery = cb.createQuery(Application.class);
Root<Application> root = cbQuery.from(Application.class);
Subquery<Applicant> subquery = cbQuery.subquery(Applicant.class);
Root subRoot = subquery.from(Applicant.class);
subquery.select(subRoot).where(cb.equal(root.get("applicant"), subRoot));
cbQuery.multiselect(root.get("id"), root.get("date"), subquery.getSelection());
This code will generate a select statement for Application, and select statements for Applicant per each Application.
Note that you have to define an appropriate constructor corresponding to your multiselect.
I got the same problem using EclipseLink as the JPA provider : I just wanted to return the id of a mapped entity («User» in Gazeciarz's example).
This can be achieved quite simply by replacing (in the query.multiselect clause)
root.get(SampleModel_.mentor)
with something like
root.get(SampleModel_.mentor).get(User_.id)
Then, instead of returning all the fields of User, the request will only return the its id.
I also used a tuple query but, in my case, it was because my query was returning fileds from more than one entity.

JPA Criteria API join

Help me plz with one moment. I read about 10 articles already, but don't understand join moment. I have 2 tables:
public class News implements Serializable {
#Id
#GeneratedValue (generator = "increment")
#GenericGenerator (name = "increment", strategy = "increment")
private int id;
#Column
private String name;
#Column
private Date created;
#Column
private String data;
#ManyToOne (cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn (name = "category_id")
private NewsCategoryDict category;
// getters, setters
}
and
public class NewsCategoryDict implements Serializable {
#Id
#GeneratedValue (generator = "increment")
#GenericGenerator (name = "increment", strategy = "increment")
private int id;
#Column
private String name;
#OneToMany (mappedBy = "category", cascade = CascadeType.ALL)
private List<News> news = new ArrayList<>();
}
I want a query works like
SELECT * FROM news, categorynews WHERE news.category_id = categorynews.id;
And then get the result in jsp with
<div id="list_news">
<c:forEach items="${news}" var="news">
<h5>${news.id} : ${news.name} - ${news.created} ; ${news.data} (${news.category.name})</h5>
</c:forEach>
</div>
And I just can't understand this JOIN with Criteria API. Can you help me ?
Try to use this snippet, but get a error
public List<News> getAll() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<News> cq = cb.createQuery(News.class);
Root<News> rootFromNews = cq.from(News.class);
Join<NewsCategoryDict, News> join = rootFromNews.join("category");
cq.select(join);
return em.createQuery(cq).getResultList();
}
PropertyNotFoundException: Property 'created' not found on type ru.r1k0.spring.model.NewsCategoryDict
Assuming you want to return an instance of News associated to an instance of NewsCategoryDict, your criteria query should look as follows:
public List<News> getAll() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<News> cq = cb.createQuery(News.class);
Root<News> rootFromNews = cq.from(News.class);
Join<News, NewsCategoryDict> join = rootFromNews.join("category"); // #1
cq.select(rootFromNews); // #2
return em.createQuery(cq).getResultList();
}
The modified lines are marked with #1 and #2 comments.
The query should return all News which have a matching NewsCategoryDict; but News records which are not associated to aNewsCategoryDict record will not be returned.
Your error has nothing to do with the join! What is actually happening is that in the JSP fragment you are trying to access ${news.created} which does not exist in the NewsCategoryDict. I believe the error is in the JSP fragment, not in the Criteria query.
The way I understand it is that you want to list the News object, but in the query you are selecting the NewsCategoryDict and this is why at the end you end up with missing attribute because the NewsCategoryDict does not contain ${news.created}

Hibernate: separate sql query for every collection

I have a Person class that has a collection of Contacts. Everything works ok, I get the list of persons with their contacts. However, in log I see that a separate query is made to read collection of every person. That is too bad.
How to make hibernate make a join to read all the data in one query? I use JPA.
This is the person class:
#Entity
#Table(name = "tbl1")
public class PersonItem implements Serializable{
#Id
#Column(name="col1")
private String guid;
.....
#ElementCollection(targetClass = ContactItem.class,fetch=FetchType.EAGER)
#CollectionTable(name="tbl2",joinColumns=#JoinColumn(name="col2"))
private List<ContactItem> contacts;
....
}
This is the contact class
#Embeddable
#Table(name = "tbl2")
public class ContactItem implements Serializable {
#Column(name="col1")
private String guid;
#Column(name="col3")
private String info;
}
This is the way I get the list of persons:
Query query = em.createQuery("Select p from PersonItem p WHERE p.guid IN (:guids)");
query.setParameter("guids", guids);
List<PersonItem> list=query.getResultList();
And this what I see in log (I have three persons in DB):
Hibernate: select personitem0_.col1 as col1_0_, personitem0_.col4 as col2_0_, personitem0_.col2 as col3_0_, personitem0_.col3 as col4_0_ from tbl1 personitem0_ where personitem0_.col1 in (? , ? , ?)
Hibernate: select contacts0_.col2 as col1_1_0_, contacts0_.col1 as col2_1_0_, contacts0_.col3 as col3_1_0_ from tbl2 contacts0_ where contacts0_.col2=?
Hibernate: select contacts0_.col2 as col1_1_0_, contacts0_.col1 as col2_1_0_, contacts0_.col3 as col3_1_0_ from tbl2 contacts0_ where contacts0_.col2=?
Hibernate: select contacts0_.col2 as col1_1_0_, contacts0_.col1 as col2_1_0_, contacts0_.col3 as col3_1_0_ from tbl2 contacts0_ where contacts0_.col2=?
Please, begin from a more simple mapping. Use plural names, and column prefixes.
#Entity
#Table(name = "persons")
public class Person {
#Id
#Column(name = "f_guid")
private String guid;
#OneToMany(mappedBy = "person", fetch = FetchType.EAGER)
private List<Contact> contacts;
}
#Entity
#Table(name = "contacts")
public class Contact {
#Id
#Column(name = "f_guid")
private String guid;
#Column(name = "f_info")
private String info;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "fk_person")
private Person person;
}
Person is associated to contacts by a foreign key fk_person in the contacts table.
Update
Looks like JPQL overrides a default fetching strategy. You need to specify a fetch explicitly
select p from PersonItem p left join fetch p.contacts WHERE p.guid IN (:guids)
If you have duplicates, cause of joins, you can use distinct
select distinct p from PersonItem p left join fetch p.contacts WHERE p.guid IN (:guids)
Try #Fetch on your relation.
Also i would suggest to use #OneToMany relation int this case
#OneToMany(mappedBy = "person", fetch = FetchType.EAGER)
#Fetch(FetchMode.JOIN) //You can use SUBSELECT as well
private List<ContactItem> contacts;
You can read more about fetching strategies here
fetch-“join” = Disable the lazy loading, always load all the collections and entities.
fetch-“select” (default) = Lazy load all the collections and entities.
batch-size=”N” = Fetching up to ‘N’ collections or entities, Not record.
fetch-“subselect” = Group its collection into a sub select statement.

Joining tables without relation using JPA criteria

I have two tables with no modeled relation:
Table comm with columns:
name
date
code
Table persondesc with columns:
code
description
Relationship between the two tables is many to one (many comm to one persondesc):
com.code = persondesc.code
These two tables are mapped with annotations but I have no relation declared.
What I'm trying to is to select comm table ordered by persondesc.description.
How can I do this JPA and Hibernate?
So if your classes have no "relation", then you do a query like
SELECT a FROM A a
CROSS JOIN B b
WHERE a.someField = b.otherField
ORDER BY b.anotherField
Which can be achieved using JPA Criteria, something like
CriteriaBuilder cb = emf.getCriteriaBuilder();
CriteriaQuery<A> query = cb.createQuery(A.class);
Root<A> aRoot = query.from(A.class);
Root<B> bRoot = query.from(B.class);
aRoot.alias("a");
bRoot.alias("b");
query.select(aRoot)
.where(cb.equal(aRoot.get(A_.someField), bRoot.get(B_.otherField))
.orderBy(cb.asc(bRoot.get(B_.anotherField)));
... Or just redesign your classes and do your developers a favour.
Hibernate 5.1 introduced explicit joins on unrelated entities for JPQL. So now you can just write a JOIN like native SQL:
List<Comm> results = entityManager
.createQuery("""SELECT c FROM Comm c
JOIN PersonDesc pd ON c.code = pd.code
ORDER BY pd.description""", Comm.class)
.getResultList();
Click here for more detailed example.
In case you need to sort by column which is in another table, you can create "fake" dependency with disabled insertable and updatable attributes. Domain model would looks like this:
Primary entity:
#Entity
public class Comm {
#Id
private Long id;
#Column(name = "name")
private String name;
#Column(name = "date")
private Date date;
#Column(name = "code")
private String code;
#OneToOne(fetch = FetchType.LAZY) // #ManyToOne is also possible
#JoinColumn(name = "code", referencedColumnName = "code", insertable = false, updatable = false)
private PersonDesc personDesc;
}
Entity with required data for sorting:
#Entity
public class PersonDesc {
#Id
private String code;
#Column(name = "description")
private String description;
}
After you define your domain model, it possible to create criteria query:
CriteriaBuilder cb = emf.getCriteriaBuilder();
CriteriaQuery<Comm> cq = cb.createQuery(Comm.class);
Root<Comm> root = cq.from(Comm.class);
Join<Comm, PersonDesc> leftJoin = root.join("personDesc", JoinType.LEFT);
cq.select(root);
cq.orderBy(cb.asc(root.get("personDesc.description")));
One of the simplest solution is to create view.
Then create an Entity class for that view and execute query against view.
View:
create or replace view view_comm_persondesc as select c.name, c.date, c.code, p.description from comm c inner join persondesc p on c.code = p.code;
Code
#Entity(name = "view_comm_persondesc")
public class ViewCommPerson{
#Id
private String code;
private String name;
private Date date;
private String description;
... All Getters/Setters ...
}
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<ViewCommPerson> query = cb.createQuery(ViewCommPerson.class);
Root<ViewCommPerson> root = query.from(ViewCommPerson.class);
// You can add your filter here
List<ViewCommPerson> result = entityManager.createQuery(query).getResultList();
Hope it servers your use case.

how to write JPA query

Learning how to write JPA query. Please advise me whether it possible to write the below queries more efficiently, may be in a single select statement. May be a join, but not sure how to do it.
class Relationship {
#ManyToOne
public String relationshipType; //can be MANAGER, CUSTOMER etc
#ManyToOne
public Party partyFrom; // a person who has a relation
#ManyToOne
public Party partyTo; // a group a person relate to
}
Queries:
String sql = "";
sql = "select rel.partyTo";
sql += " from Relationship rel";
sql += " where rel.partyFrom = :partyFrom";
sql += " and rel.relationshipType= :typeName";
Query query = Organization.em().createQuery(sql);
query.setParameter("partyFrom", mgr1);
query.setParameter("typeName", "MANAGER");
List<Party> orgList = query.getResultList();
String sql2 = "";
sql2 = "select rel.partyFrom";
sql2 += " from Relationship rel";
sql2 += " where rel.partyTo = :partyToList";
sql2 += " and rel.relationshipType = :typeName2";
Query query2 = Organization.em().createQuery(sql2);
query2.setParameter("partyToList", orgList);
query2.setParameter("typeName2", "CUSTOMER");
List<Party> personList2 = query2.getResultList();
Both the queries work. Query 1 returns a list of groups, where the person (mgr1) has a relation MANAGER with. Query 2 returns all the Persons they are CUSTOMER to the groups returned by query 1. In effect, I get a list of Person they are belong to (customer) the same group where the Person (mgr1) has a relation MANAGER with.
Is it possible to combine them into single sql statement so possibly only one db access?
You literally nest one query inside the other, and use a "where in" clause to specify that the outer query should fetch customers from the inner query.
select rel2.partyFrom
from Relationship rel2
where rel2.relationshipType = :typeName2 /* customer */
and rel2.partyTo.id in
(select rel.partyTo.id
from Relationship rel
where rel.partyFrom = :partyFrom
and rel.relationshipType = :typeName)
Your calling code passes typeName, typeName2, and partyFrom parameters as before. PartyTo parameter is not needed, since the data comes from the subselect (inner query.)
You can achieve the same thing using a self join, with a where clause that filters managers on the left side, and customers on the right side, but using an 'in' clause is semantically clearer.
EDIT: I addded .id to the subselect, which I think is needed.
This is not answer to question but helping other folks in case if someone looking into #OneToMany relation in Spring Data JPA using JPQL, because the question is related to JPA so thought to share my 2-cents, apologize in advance
#Entity
#Table(name = "MY_CAR")
public class MyCar {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "DESCRIPTION")
private String description;
#Column(name = "MY_CAR_NUMBER")
private String myCarNumber;
#Column(name = "RELEASE_DATE")
private Date releaseDate;
#OneToMany(cascade = { CascadeType.ALL })
#JoinTable(name = "MY_CAR_VEHICLE_SERIES", joinColumns = #JoinColumn(name = "MY_CAR_ID "), inverseJoinColumns = #JoinColumn(name = "VEHICLE_SERIES_ID"))
private Set<VehicleSeries> vehicleSeries;
public MyCar() {
super();
vehicleSeries = new HashSet<VehicleSeries>();
}
// set and get method goes here
#Entity
#Table(name = "VEHICLE_SERIES ")
public class VehicleSeries {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "SERIES_NUMBER")
private String seriesNumber;
#OneToMany(cascade = { CascadeType.ALL })
#JoinTable(name = "VEHICLE_SERIES_BODY_TYPE", joinColumns = #JoinColumn(name = "VEHICLE_SERIES_ID"), inverseJoinColumns = #JoinColumn(name = "BODY_TYPE_ID"))
private Set<BodyType> bodyTypes;
public VehicleSeries() {
super();
bodyTypes = new HashSet<BodyType>();
}
// set and get method goes here
#Entity
#Table(name = "BODY_TYPE ")
public class BodyType implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "NAME")
private String name;
// set and get method goes here
public interface MyCarRepository extends JpaRepository<MyCar, Long> {
public Set<MyCar> findAllByOrderByIdAsc();
#Query(value = "select distinct myCar from MyCar myCar "
+ "join myCar.vehicleSeries as vs join vs.bodyTypes as bt where vs.seriesNumber like %:searchMyCar% "
+ "or lower(bt.name) like lower(:searchMyCar) or myCar.bulletinId like %:searchMyCar% "
+ "or lower(myCar.description) like lower(:searchMyCar) "
+ "or myCar.bulletinNumber like %:searchMyCar% order by myCar.id asc")
public Set<MyCar> searchByMyCar(#Param("searchMyCar") String searchMyCar);
}
Some data in tables like
Select * from Vehicle_Series
ID SERIES_NUMBER
1 Yaris
2 Corolla
Select * from Body_Type
ID NAME
1 Compact
2 Convertible
3 Sedan

Categories