Is it somehow possible to create a criteria query that performs an outer join on another entity if that entity is not mapped?
I know that an inner join is possible when you do a cross join and add the join condition manually. It would look like this:
CriteriaBuilder cb = getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<Car> car = cq.from(Car.class);
Root<Color> color = cq.from(Ccolor.class);
cq.where(cb.equal(car.get("colorUuid"), color.get("uuid")));
However I need the behaviour of an outer join in my case.
So let's say I have these entities:
class Car {
#Column(name="color_uuid")
private String colorUuid;
}
class Color {
private String uuid;
private String name;
}
Lets say Color is optional and that's why I need an outer join. The SQL would look like
SELECT * from car LEFT OUTER JOIN color ON car.color_uuid = color.uuid;
Can I do this with Criteria?
You can’t do this with criteria api without making the entities in relation, I’ve faced the same problem as you. Also a cross join can’t help. What I can suggest is:
make a view with the left outer join on the database and then map the view as an entity
make a jpql query
make a native query
I suggest you change the classes in order to have a relationship that logically already exists.
class Car {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "color_uuid", referencedColumnName = "uuid")
private Color color;
}
class Color {
private String uuid;
private String name;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "color")
private List<Car> cars;
}
Then you can build the left join using criteria:
CriteriaQuery<Car> criteriaQuery = criteriaBuilder.createQuery(Car.class);
Root<Car> root = criteriaQuery.from(Car.class);
root.join("color", JoinType.LEFT);
List<Car> cars = em.createQuery(criteriaQuery).getResultList();
Related
This is my entity:
public class Patrimony {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToMany(mappedBy = "patrimony")
#JsonManagedReference
private
List<Patrpos> positions;
}
My code is:
CriteriaBuilder cb = manager.getCriteriaBuilder();
CriteriaQuery<Patrimony> cq = cb.createQuery(Patrimony.class);
Root<Patrimony> root = cq.from(Patrimony.class);
Join<Patrimony, UserProfile> userprofile = root.join(Patrimony_.userprofile);
Join<Patrimony, Patrpos> joinPatrpos = root.join(Patrimony_.positions, JoinType.LEFT);
root.fetch(Patrimony_.positions);
joinPatrpos.on(cb.equal(joinPatrpos.get(Patrpos_.dtPatrpos), dateproc.minusDays(1)));
cq.select(root);
TypedQuery<Patrimony> query = manager.createQuery(cq);
List<Patrimony> list = query.getResultList();
The query that is being generated looks ok, and it's something like:
select
patrimony0_.id as id1_10_0_,
positions3_.id as id1_11_1_,
patrimony0_.category_id as categor15_10_0_,
patrimony0_.description as descript2_10_0_,
patrimony0_.vl_valuation_start as vl_valu14_10_0_,
positions3_.dt_patrpos as dt_patrp2_11_1_,
positions3_.vl_patrpos as vl_patrp6_11_1_,
from
patrimony patrimony0_
inner join
userprofile userprofil1_
on patrimony0_.userprofile_id=userprofil1_.id
left outer join
patrpos positions2_
on patrimony0_.id=positions2_.patrimony_id
and (
positions2_.dt_patrpos=?
)
inner join
patrpos positions3_
on patrimony0_.id=positions3_.patrimony_id
where userprofil1_.id=161
The query seems to be returning all the data that I need, the entity Patrimony is being returned with all the data ok, except the "List positions" attribute, which is always null.
Thank you.
Reviewing the unit test, I notice that I didn't call flush() and clear() after inserting the test data. I added flush and clear before calling the query and all the entities were populated correctly.
Thank you all for the comments.
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.
I am seeing a strange behavior in Hibernate 4.3.5 and 4.3.11, where I have a table with a self join that also load other objects here is my class
#Entity(name = "site")
#Table(name = "site")
public class Site implements Serializable
{
#OneToMany(mappedBy = "site", fetch = FetchType.EAGER)
private List<SiteAttribute> siteAttributes;
#Id
#GeneratedValue
#Column(name = "site_id")
private Integer siteID;
#OneToMany(mappedBy = "site", fetch = FetchType.EAGER)
private List<ContainerPage> containerPages;
#OneToMany(mappedBy = "site", fetch = FetchType.EAGER)
private List<UserTitle> userTitleList;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "parent_site_id")
private Site parentSite;
}
The table as a self join using the parent_site_id, and each site can have multiple son sites.
The code to retrieve the Site object is:
Query q = session.createQuery("from site where site_id=:siteID");
q.setParameter("siteID", currentSiteID.intValue());
s = (Site) q.uniqueResult();
When I open the logs from hibernate the query executed look like this:
select ...
from site site0_
left outer join containers_pages containerp2_ on site0_.site_id=containerp2_.site_id
left outer join containers container3_ on containerp2_.container_id=container3_.container_id
left outer join pages page4_ on containerp2_.page_id=page4_.page_id
left outer join widgets_containers widgetcont5_ on containerp2_.container_page_id=widgetcont5_.container_page_id
left outer join site site6_ on site0_.parent_site_id=site6_.site_id
left outer join site_attribute siteattrib7_ on site6_.site_id=siteattrib7_.site_id
left outer join user_title usertitlel10_ on site6_.site_id=usertitlel10_.site_id where site0_.site_id=?
From the moment we have a left join with site using parent hibernate stops using my site0_.site_id and uses site6.site_id. Is this behavior correct?
Looks like it is missing information for the current object and this select will return much more results than it should.
Is something wrong with my implementation, or do I need to get the Site and do another query to retrieve the parent site?
when i create a count query with hibernate - Criteria - add all the possible table from the entity class as left join which is bad performance .
The entity :
#Entity
#Table(name = "employees")
Public Class Employees {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "lz_job_stat_id")
private Integer id;
#ManyToOne
#JoinColumn(name = "departments_id")
private Departments departments;
#ManyToOne
#JoinColumn(name = "managers_id")
private Managers managers;
}
And the criteria :
public class EmployeeDao {
public List<EmpDao> findIt(){
.....
Criteria crit = createEntityCriteria().setFetchMode("departments", FetchMode.SELECT);
crit.add(Restrictions.eq("managers.deleted", false));
crit.setProjection(Projections.count("id"));
return crit.list();
}
}
And the produced SQL :
select count() as y0_
from employees this_
left outer join departments department3_
on this_.department_id=department3_.department_id
left outer join managers manager2_
on this_.manager_id=manager2_.manager_id
now when i try the crit.list - it create a left join for all the possible tables.
when its not supposed to create a join for all of them.
isnt Criteria smart enought to know i dont need this tables ? only the one i use the "WHERE CLAUSE"
is there a way to explicitly tell Criteria "DO NOT JOIN THIS TABLES !!!"
without SQL
Specify fetch type on ManyToOne annotation:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "departments_id")
private Departments departments;
or IMHO more preferably in criteria:
criteria.setFetchMode("departments", FetchMode.SELECT)
Using hibernate 3.6.10 with hibernate jpa 2.0.
My problem boils down to needing to set some criteria on a column of a child object during a somewhat complex joining query.
I have a set of objects similar to:
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
public class Ball
{
private String name;
//...getter and setter crud...
}
#Entity
public class BeachBall extend ball
{
private boolean atTheBeach;
//...getter and setter crud...
}
#Entity
public class SoccerBall extend ball
{
private int numberOfKicks;
//...getter and setter crud...
}
#Entity
public class Trunk
{
private Set<Ball> balls;
#OneToMany(mappedBy = "trunk", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<Ball> getBalls()
{
return balls;
}
}
#Entity
public class Car
{
private Trunk trunk;
private String carModel;
//...getter and setter crud...
}
Now i need to query how many soccer balls have 20 kicks in a car with a specific model.
Using JPA I tried to do something like:
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Car> criteriaQuery = criteriaBuilder.createQuery(Car.class);
Root<Car> car= criteriaQuery.from(Car.class);
Join<Car, Trunk> trunkJoin = car.join(Car_.trunk);
Join<Trunk, Ball> ballJoin = trunkJoin.join(Trunk_.Balls);
criteriaQuery.select(trunk);
Predicate [] restrictions = new Predicate[]{ criteriaBuiler.equal(car.get(carModel), "Civic"), criteriaBuilder.equal(ballJoin.get("numberOfKicks"), 20)};
criteriaQuery.where(restrictions);
TypedQuery<Car> typedQuery = entityManager.createQuery(criteriaQuery);
Car carWithSoccerBalls = typedQuery.getSingleResult();
At runtime the above code dies because numberOfKicks is only on soccerballs and due to how its typed in Trunk it only knows about ball. If i manually create a from on the soccerballs and setup criteria to join it i can query numberOfKicks, however i feel like there must be a way to inform the query that the set is in fact a set.
Please note i cannot post any of the actual code so all above examples are just examples.
Using JPA and hibernate like above is there a way to force hibernate to know that the set< ball > is actually set< soccerball >?
Due to time restrictions i'm taking the easy way out :(. If anyone can answer better then what i have i'll gladly choose their answer over mine.
To make the criteria api recognize that i'm looking for the inherited table i changed my query code to be:
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Car> criteriaQuery = criteriaBuilder.createQuery(Car.class);
Root<Car> car= criteriaQuery.from(Car.class);
Root<Soccerball> soccerballs = criteriaQuery.from(SoccerBall.class);
Join<Car, Trunk> trunkJoin = car.join(Car_.trunk);
Join<Trunk, Ball> ballJoin = trunkJoin.join(Trunk_.Balls);
criteriaQuery.select(trunk);
Predicate [] restrictions = new Predicate[]{ criteriaBuiler.equal(car.get(carModel), "Civic"), criteriaBuilder.equal(soccerball.get("numberOfKicks"),20), criteriaBuilder.equal(soccerball.get(SoccerBall_.id),car.get(Car_.id))};
criteriaQuery.where(restrictions);
TypedQuery<Car> typedQuery = entityManager.createQuery(criteriaQuery);
Car carWithSoccerBalls = typedQuery.getSingleResult();
The following retrieves all Cars with nested list attributes satisfying equality criteria for subclass type in a collection and equality on root element.
I've modified the query to work with the datamodel in the original question.
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Car> carQuery = criteriaBuilder.createQuery(Car.class);
Root<Car> carRoot = carQuery.from(Car.class);
Subquery<SoccerBall> ballQuery = carQuery.subquery(SoccerBall.class);
Root<SoccerBall> soccerBall = ballQuery.from(SoccerBall.class);
ballQuery.select(soccerBall);
ballQuery.where(criteriaBuilder.equal(soccerBall.get(SoccerBall_.numberOfKicks), 25));
Join<Car, Trunk> carTrunkJoin = carRoot.join(Car_.trunk);
SetJoin<Trunk, Ball> trunkBallJoin = carTrunkJoin.join(Trunk_.balls);
carQuery.select(carRoot);
carQuery.where(criteriaBuilder.and(
trunkBallJoin.in(ballQuery),
criteriaBuilder.equal(carRoot.get(Car_.carModel), "Civic")));
TypedQuery<?> typedQuery = entityManager.createQuery(carQuery);
List<?> result = typedQuery.getResultList();
The equivalent SQL is:
SELECT * FROM car JOIN trunk JOIN ball WHERE ball.id IN (SELECT soccerball.id FROM soccerball WHERE soccerball.numberOfKicks = 25)