Hibernate Query for equivalent sql - java

Can someone help me in writing equivalent hql for this query
SELECT IFNULL(oea.`organization_name`,'') FROM `consultation_appointment` ca
JOIN `organization_employee_association` oea ON ca.`consultation_id` = oea.id
JOIN professional_profile pp ON oea.`employee_profile_id` = pp.profile_id
I could able to join the first JOIN like this
select ca.name from ConsultationAppointment ca join ca.consultation oea
Because the ConsultationAppointment class having organization_employee_association variable so it easier to join, difficulty is organization_employee_association not having direct mapping to organization_employee_association class.
Even GORM criteria Query is helpful.

HQL does not allow joining two unassociated entity, you should use cartesian product instead.
String query = "SELECT ca.name FROM consultation_appointment ca JOIN organization_employee_association oea, professional_profile pp WHERE oea.employee_profile_id = pp.profile_id";
List<String> caNames = session.createQuery(query).list();
One another possibility is to use the method createSQLQuery(). It provides more flexibility to execute an arbitrary join.
String query = "SELECT ca.name FROM consultation_appointment ca JOIN organization_employee_association oea ON ca.consultation_id = oea.id JOIN professional_profile pp ON oea.employee_profile_id = pp.profile_id";
List<String> caNames = session.createSQLQuery(query).list();

Related

Get data from join table hibernate many to many

I have this diagram:
table diagram
and I want to filter by the employees that have a project.
In normal SQL I will go like this
select * from employees e
join employee_projects ep on ep.employee_id = e.id
How can I achieve the same with Hibernate?
I tried using criteria builder and specifications but I can't get the data from the join table.
You can select all employees that have a project like this
em.createQuery(
"SELECT e FROM Employee e JOIN e.projects p WHERE p IS NOT NULL", Employee.class).getResultList()
You can join tables using join method of root object.
try something like this below
I have used it for one to many relation
Join<Post, Tag> join = root.join("tags", JoinType.INNER);
Predicate tagPredicate = criteriaBuilder.like(join.get("name"), "%" + search + "%");
for many to many relation,
Join<Post, Tag> postTagsTable = root.join("tags", JoinType.INNER);
return postTagsTable.<String>get("name").in(tagNames);
here I have tags field in Post entity, which is used inside join

Convert SQL Query to Criteria Query in Spring Boot

I'm relatively new to Spring JPA CriteriaQuery. Im trying to convert my old native query in my program to criteria query and haven't been successful on join query for multiple table with conditions. I need help converting native SQL query into Criteria Query for these query below :
select * from student s inner join (
select distinct on (student_id) * from class where status = 'Active' order by
student_id,date_register desc) c on s.id = c.user_id
inner join teacher t on t.subject_id = c.subject_id
where t.status = 'Active' and s.status='Active' order by s.name desc
Update :
Below code is as far as I can go cause I dont really know much. Am i in the right direction? I'm opting for Expression because i dont know how to use Join.
CriteriaQuery<Student> query = cb.createQuery(Student.class);
Root<Student> sRoot= query.from(Student.class);
query.select(sRoot);
Subquery<Integer> subquery = query.subquery(Integer.class);
Root<Class> cRoot= subquery.from(CLass.class);
Expression<Integer> max = cb.max(cRoot.get("dateRegister"));
subquery.select(max);
subquery.groupBy(cRoot.get("student"));
query.where(
cb.and(
cb.in(cRoot.get("dateRegister")).value(subquery)
)
);
Thanks in advance!

JPA Criteria Query for Left joins

I am new to JPA and I have a Left Join scenario.
I have my native sql query as below and I am using left join to fetch the complete records from V_MONITORING table for st.id = 10001.
I have some null values for id_legislature which also needs to be selected and hence using a left join
select distinct
mv.id_set, mv.id_travel, mv.id_legislature
from
V_MONITORING mv
left join v_set st on mv.id_set = st.id
left join v_travel fg on mv.id_travel = fg.id
left join v_legislature gg on mv.id_legislature = gg.id;
The same thing I am implementing using the JPA criteria query, I am unable to fetch the null records
Below is the code
Predicate predicate = cb.conjunction();
Root<MonitoringBE> mvRoot = criteriaQuery.from(MonitoringBE.class);
mvRoot.fetch(MonitoringBE.id_set, JoinType.LEFT);
mvRoot.fetch(MonitoringBE.id_travel, JoinType.LEFT);
mvRoot.fetch(MonitoringBE.id_legislature, JoinType.LEFT);
final Path<Object> serieneinsatzterminPath= mvRoot.get(MonitoringBE.id_set);
predicate = cb.and(predicate, cb.EqualTo(serieneinsatzterminPath.get(SetBE.GUELTIG_VON_DATUM), startSetDate));
criteriaQuery.multiselect(
mvRoot.get(MonitoringBE.id_travel).alias("id_travel"),
mvRoot.get(MonitoringBE.id_set).alias("id_set"),
mvRoot.get(MonitoringBE.id_legislature).alias("id_legislature"))
.distinct(true).where(predicate);
Can some one guide me.
You have to replace the mvRoot.get(MonitoringBE.id_travel) and others in the multiselect-statement with mvRoot.join(MonitoringBE.id_travel, JoinType.LEFT). Otherwise they will end up in a inner join.

MYSQL Slow Query

Our Java Application is running very slowly.
This is the case for various reasons, one of the main maybe being that the MySQL code within the application uses two different tables to get this data, doing joins. Is anyone able to advise how this Query could be written better for performance?
SELECT DISTINCT uniqueId
FROM advertisementmodule
JOIN advertisement ON advertisementmodule.idAdvertisement = advertisement.idAdvertisement
JOIN advertisementschedule ON advertisement.idAdvertisementSchedule = advertisementschedule.idAdvertisementSchedule
JOIN adschedulegroup ON advertisementschedule.idAdScheduleGroup = adschedulegroup.idAdScheduleGroup
WHERE adschedulegroup.publisherCode = 'ABC';
SELECT *
FROM taurustour
JOIN searchthemestaurus
WHERE uniqueId IN (
'18538'
,'17142'
,'11248'
,'18458'
)
AND air IS true;
Which table isuniqueId in?
A little more readable:
SELECT DISTINCT uniqueId
FROM advertisementmodule AS m
JOIN advertisement AS a
ON m.idAdvertisement = a.idAdvertisement
JOIN advertisementschedule AS s
ON a.idAdvertisementSchedule = s.idAdvertisementSchedule
JOIN adschedulegroup AS g
ON s.idAdScheduleGroup = g.idAdScheduleGroup
WHERE g.publisherCode = 'ABC';
Do you have an index starting with publisherCode ?

complex query to equivalent criteriabuilder query(EntityManager)

My Query is this:
query1 = select a.id from entity1 a where a.id in (:List1)
and not exists (select ex2 from entity2 ex2 where ex2.assignedId = a.id)
union
select ex.assignedId from entity2 ex ,entity3 pi
where ex.entity3Id = pi.id and ex.assignedId in (:List1)
and ex.assignedTypeId = :assignedTypeId and pi.processStatus = :status
and not exists
(select ex1.assignedId from entity2 ex1 , entity3 pi1
where ex1.entity3Id = pi1.id and ex1.assignedId = ex.assignedId
and ex1.assignedTypeId = :assignedTypeId
and pi1.processStatus <> :status);
and while trying to execute query,
Query existingIds=em.createQuery(query1); //With all parameters set
throws NullPointerException in line 87 of org.hibernate.hql.ast.ParameterTranslationsImpl
completely checked all the braces and parameters. The equivalent conversion works in mysql.
Can someone assist me in converting the query with CriteriaBuilder, finding it difficult to make the conversion.
Not sure if JPQL supports union operation at all. Are you putting this as NamedQuery or you are creating on the fly (entityManager.createQuery()) ?

Categories

Resources