How to join two unrelated entities using JPA and Hibernate - java

I have two tables - one containing Address and another containing Photographs. The only common field between them is the PersonID. These were mapped to two POJO Classes Address and Photo. I was able to fetch details in these tables by creating criteria and adding restrictions on the fields . How should we write a join on the two tables. Is it possible to get the result as two objects -Address and Photo.
I want to do a left join so that i can get records of persons without photos as well.
I have read that this is possible only using hql but Can this be done using criterias as well?

You can easily write HQL query that will return result as two objects using Theta Join (as Adrian noted). Here is an example:
String queryText = "select address, photo from Address address, Photo photo "
+ " where address.personID=photo.personId";
List<Object[]> rows = session.createQuery(queryText).list();
for (Object[] row: rows) {
System.out.println(" ------- ");
System.out.println("Address object: " + row[0]);
System.out.println("Photo object: " + row[1]);
}
As you can see query returns list of Object[] arrays that represents each fetched row. First element of this array will contain one obejct and second element - another.
EDIT:
In case of left join I think you need to use native SQL query (not HQL query). Here how you can do this:
String queryText = "select address.*, photo.* from ADDRESS address
left join PHOTO photo on (address.person_id=photo.person_id)";
List<Object[]> rows = sess.createSQLQuery(queryText)
.addEntity("address", Address.class)
.addEntity("photo", Photo.class)
.list();
This should work for your case.

Basically, you have two options:
Since Hibernate 5.1, you can use ad-hoc joins for unrelated entities.
Tuple postViewCount = entityManager.createQuery(
"select p as post, count(pv) as page_views " +
"from Post p " +
"left join PageView pv on p.slug = pv.slug " +
"where p.title = :title " +
"group by p", Tuple.class)
.setParameter("title", "High-Performance Java Persistence")
.getSingleResult();
Prior to Hibernate 5.1, you could only use theta-style joins. However, a theta-style join is equivalent to an equijoin, hence you can only emulate INNER JOINs not OUTER JOINs.
List<Tuple> postViewCount = entityManager.createQuery(
"select p as post, count(pv) as page_views " +
"from Post p, PageView pv " +
"where p.title = :title and " +
" ( p.slug = pv.slug ) " +
"group by p", Tuple.class)
.setParameter("title", "Presentations")
.getResultList();

Finally after 12 years the Hibernate team has implemented such a feature
From Hibernate docs:
The FROM clause can also contain explicit relationship joins using the join keyword. These joins can be either inner or left outer style joins.
List<Person> persons = entityManager.createQuery(
"select distinct pr " +
"from Person pr " +
"join pr.phones ph " +
"where ph.type = :phoneType", Person.class )
.setParameter( "phoneType", PhoneType.MOBILE )
.getResultList();
List<Person> persons = entityManager.createQuery(
"select distinct pr " +
"from Person pr " +
"left join pr.phones ph " +
"where ph is null " +
" or ph.type = :phoneType", Person.class )
.setParameter( "phoneType", PhoneType.LAND_LINE )
.getResultList();
Or you can use WITH and ON keywords. A remark on those
The important distinction is that in the generated SQL the conditions
of the WITH/ON clause are made part of the ON clause in the generated
SQL, as opposed to the other queries in this section where the
HQL/JPQL conditions are made part of the WHERE clause in the generated
SQL.
Example
List<Object[]> personsAndPhones = session.createQuery(
"select pr.name, ph.number " +
"from Person pr " +
"left join pr.phones ph with ph.type = :phoneType " )
.setParameter( "phoneType", PhoneType.LAND_LINE )
.list();
I am currently eager to try the new feature.

Joining two unrelated entities are possible in Hibernate 5.1.
Eg :
select objA from ObjectA objA
JOIN ObjectB objB on objB.variable = objA.variable
where objA.id = 1

It's best to have a class containing those classes you want to join to have them all together.
But if you are joining these tables just for some occasional purposes, you can use criteria and manually load data from each table and put them together. (and yes, you can have these tables' data separately if for Address and Photo there are two separate classes and tables)

What you are looking for is
HQL
Join on fields that you haven't modeled as relationships
Left Join
(During the time the question was first asked and this answer was given) Hibernate supports Theta Join which allows you to do 1 & 2. However, only inner join is available for theta join style.
Personally I would recommend you to model proper relationships, so you just need 1 & 3 which is well-supported in HQL.
(Another answer actually provided an update on new Hibernate feature that provides such feature, that you may simply refer to)

Related

Hibernate createNativeQuery - get more than one Entity

I am using following code to execute native SQL query with hibernate:
Query zonesQuery = session.createNativeQuery(
"Select * \n" +
"FROM dbo.Structure AS S\n" +
"JOIN dbo.StructureLocationType AS SLT ON SLT.StructureId = S.Id\n" +
"WHERE SLT.LocationTypeId = :lc").addEntity(StructureEntity.class);
zonesQuery.setParameter("lc", locationTypeID);
List<StructureEntity> zones = zonesQuery.list();
So it works and it gets me list of StructureEntity
now, because my sql query "join" from StructureLocationType table, is there possibility to get whole StructureLocationType row as well, still using single query?
Thank you.
It can be achieved with the following (notice curly braces in SQL and entities aliases):
Query query = session
.createNativeQuery(
"SELECT {S.*}, {SLT.*} " +
"FROM dbo.Structure AS S " +
"JOIN dbo.StructureLocationType AS SLT ON SLT.StructureId = S.Id " +
"WHERE SLT.LocationTypeId = :lc")
.unwrap(SQLQuery.class)
.addEntity("S", StructureEntity.class)
.addEntity("SLT", StructureLocationTypeEntity.class)
.setParameter("lc", locationTypeID);
List<Pair<StructureEntity, StructureLocationTypeEntity>> result = ((List<Object[]>) query.list())
.stream()
.map(p -> Pair.of((StructureEntity) p[0], (StructureLocationTypeEntity) p[1]))
.collect(Collectors.toList());
You can't get multiple Objects from one query.
But you could either select which columns you want and then iterate the returned Object array:
The query:
SELECT s.id, s.someColumn, slt.id, slt.structureId
FROM dbo.Structure AS s
JOIN dbo.StructureLocationType AS slt on slt.structureId = s.id
WHERE slt.locationTypeId = :lc
Then iterate over the Object array:
List<Object[]> result = query.getResultList();
Or you could create a view on your database and map it to a java entity using the Table annotation like it was a normal table:
#Entity
#Table(name = "STRUCTURE_LOCATION_TYPE_VIEW")
public class StructureAndLocationType {
// ...
}
I thought there is a way to map from a query to an Object without creating a DB view but couldn't find it right now.

Hibernate expecting "all", found '(' - what does this mean?

I'm getting this error and I can't find any reference to it:
org.hibernate.hql.internal.ast.QuerySyntaxException: expecting "all", found '(' near line 1, column 221 [select new EffectivePermissions(r.id, r.name, r.defaultValue, rc.value AS companyValue, ru.value AS userValue) from permissionsPackage.Entity.Permissions r left join permissionsPackage.Entity.CompanyPermissions rc fetch (r.id=rc.permissionId AND rc.companyId=2313 ) left join permissionsPackage.Entity.UserPermissions ru fetch (r.id=ru.permissionId AND ru.userId=1)]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:79)
Below is the Query I'm using.
this.hql = "select new EffectivePermissions(r.id, r.name, r.defaultValue, rc.value AS companyValue, ru.value AS userValue) "
+ "from "
+ Permissions.class.getName()
+ " r "
+ "left join "
+ CompanyPermissions.class.getName()
+ " rc "
+ "fetch (r.id=rc.permissionId AND rc.companyId="
+ user.getCompany().getId()
+ " ) "
+ "left join "
+ UserPermissions.class.getName()
+ " ru "
+ "fetch (r.id=ru.permissionId AND ru.userId="
+ user.getId()
+ ")";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
permissions = query.list();
I have a class called EffectivePermission with the properties in the constructor and I'd like to get a list based on it.
From the Hibernate Reference chapter 14.3. Associations and joins:
A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select ... See Section 19.1, “Fetching strategies” for more information.
You'll also see there that it must be used after the joinkeyword as in from e1 left join fetch e2. It can also be used as in from entity fetch all properties (this is why Hibernate is expecting the all keyword).
Regarding your specific query, and as far as I know, with HQL you can not specify the join conditions. Hibernate will automatically perform the join using the conditions configured in the mapping. This is why it is necessary to have relationships mapped in order to use a HQL join.
And most importantly, remember that joins in HQL are quite different. You don't join two entities, you join an entity with one of its collection-valued properties (associations). Notice you can always do cartesian-like joins (pay attention to performance and always look at the generated queries and execution plans).
As a side note, it can be considered bad practice to append parameter values directly into the query (due to potential injection vulnerabilities). You should be using named parameters instead.

Group by in HQL and Hibernate Criteria queries (ORA-00979: not a GROUP BY expression)

I am new to new to hibernate and Java, so I apologize if these are ridiculously simply questions.
I don't understand why the following query gives me the error "ORA-00979: not a GROUP BY expression".
Query q = session.createQuery (
"select new tdata.Summary(tbForm.rYear, SUM(tbForm.pWaste)) "
+ "from TrForm tbForm "
+ "left join fetch tbForm.indKey "
+ "where tbForm.indKey.grpCode='999' "
+ "group by tbForm.rYear " );
The possible reasons for this error do not seem to apply to my query because I am including group by function SUM, and I do not have any expressions in the select that are not in the group by.
I also tried to write a criteria query to do what I need, and I could not get that to work either. In the criteria version, I am confused as to how to add restrictions to fetched data and how to get the data into the Summary object.
Criteria criteria = session.createCriteria(TrForm.class)
.setFetchMode("DimInd",FetchMode.JOIN)
.add(Restrictions.eq("indKey.indCode", "999"))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("rYear"))
.add(Projections.sum("pWaste")));
summaryList = (List<Summary>) criteria.list();
Any help would be greatly appreciated.
Thanks!
Update:
Thank you so much! I removed the "left join fetch tbForm.indKey" and the HQL version worked!
Generalized query is
select R_YEAR, sum(P_WASTE)
from TR_FORM tbForm
left join DIM_IND ind
on tbForm.IND_KEY = ind.IND_KEY
where ind.GRP_CODE='999'
group by tbForm.R_YEAR
tdata is the folder in which I have the java code for the data models.

Named Query, Native Query or Criteria API

I need to report data from 3 different tables in form of a report.
The various search combinations a user can search with are..
INS_USER_ID and DateRange
CUST_ACCT_ID
CUST_ACCT_ID and DateRange
Query..
select DISTINCT W.CUST_ACCT_ID, W.INS_USER_ID, WS.STTI_DATE, WS.STTI_AMT, WC.CMMT from T_WRK W
INNER JOIN T_WRK_STTI WS ON W.WRK_STTI_ID = WS.WRK_STTI_ID
INNER JOIN T_WRK_CMMT WC ON W.WRK_ID = WC.WRK_ID
WHERE W.CUST_ACCT_ID = 90610194 AND WS.STTI_DATE BETWEEN '01-JAN-12' AND '31-DEC-12'
select DISTINCT W.CUST_ACCT_ID, W.INS_USER_ID, WS.STTI_DATE, WS.STTI_AMT, WC.CMMT from T_WRKCS W
INNER JOIN T_WRKCS_STTI WS ON W.WRKCS_STTI_ID = WS.WRKCS_STTI_ID
INNER JOIN T_WRKCS_CMMT WC ON W.WRKCS_ID = WC.WRKCS_ID
WHERE W.INS_USER_ID = 231 AND WS.STTI_DATE BETWEEN '01-JAN-12' AND '31-DEC-12'
All are existing tables are already mapped using Hibernate/JPA.
I have read enough on the various approaches in google, can someone tell me which one of the following hibernate approaches is best suited for my scenario.
NamedQuery
NativeQuery
Criteria API
I am thinking NamedQuery, but have not seen a NamedQuery spanning across multiple tables, an example would be great. Thank you.
Example
#Entity
#NamedQuery(name="findSalaryForNameAndDepartment",
query="SELECT e.salary " +
"FROM Student e" +
"WHERE e.department.name = :deptName AND " +
" e.name = :empName")
You can as well put there an join to the department table and change the query a little bit
For date use parameters
em.createNamedQuery("xxx").setParameter("srtartDate", ...).setParameter("endDate",..)

Can I convert this Mysql query to JPA?

I'm fairly familiar with SQL but very new to the Java Persistence API. I'm using JPA through the Play Framework.
I have the following MySql query that I'd like to convert to pure JPA code if I can:
SELECT a.id, b.id
FROM Rankable a
INNER JOIN Rankable b on a.id < b.id
WHERE
a.category_id = ? AND b.category_id = ?
AND NOT EXISTS (
SELECT *
FROM Comparison c
WHERE c.lower in (a.id, b.id))
AND NOT EXISTS (
SELECT *
FROM Comparison c
WHERE c.higher IN (a.id, b.id))
ORDER BY a.id * rand()
LIMIT 1;
The purpose of this query is to select two rows from the Rankable table, but ensure that this specific pair is not present in the Comparison table.
What would be the best way to call a somewhat complicated query like this from Play/JPA?
It is possible to do a self join in JPA.
Take a look at this example
from the example
#NamedQuery(name="siblings", query="select distinct sibling1 "
+ "from Deity sibling1, Deity sibling2 where "
+ "sibling1.father = sibling2.father "
+ "and sibling1.mother = sibling2.mother "
+ "and sibling2 = ?1 and sibling1 <> ?1"),

Categories