Get data from join table hibernate many to many - java

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

Related

Spring Data JPA Specification FETCH JOIN Issue

I am trying to create below query using spring jpa specification but it is giving error.
SELECT x FROM Magazine x join fetch x.articles a join a.publishers p WHERE p.title = 'JDJ'
Invalid path: 'generatedAlias2.title'
problem here is I am trying to do something like below
return (r, cq, cb) -> {
Join join1 = (Join) root.fetch("articles");
Join join2 = join1.join("publisher");
return cb.equal(join2.get("title"), title);
};
Is it possible to create query. Please help.

How to add filter on second table parameter while doing left join using criteriaquery

I am stuck in a situation where I am not able to create a filter on left join between two table.
My query is something like this.
select count(*)
from orders o
left
join payments p
on o.id = p.o_id
where o.uid_id = 1
and p.name = "abc"
I am trying to do left join using criteria query. In criteria query.
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Orders> query = cb.createQuery(Orders.class);
Root<Orders> ordersRoot = query.from(Orders.class);
Join<Orders, Payments> join = ordersRoot.join(JOIN_COLUMN, JoinType.LEFT);
List<Predicate> predicates = new ArrayList<>();
predicates.addAll(getPredicates(cb, ordersRoot)); //this method gives other predicates on order table
query.where(predicates.toArray(new Predicate[predicates.size()]));
query.select(ordersRoot).distinct(true);
TypedQuery<Orders> query = entityManager.createQuery(criteriaQuery);
List<Orders> list = query.getResultList();
This is my criteria Java code.
In this I have not added for this check.
orders and payments table has one to many relationship.

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.

remove duplicate Data after Execute SelectQuery in mutliple Tables

i have Three tables [users,projects,scenarios] i need to get latest update projects details based on modified Date column with out duplicate values
the tables are:
users Table :
project table
scenario Table
and i try below query but its return duplicates values if am using group by then old values came but i need latest values
With out Group by query
SELECT
p.`PROJECT_NAME`,
p.`CREATED_DATE`,
s.`MODIFIED_DATE`
FROM
`projects` p
JOIN `scenarios` s ON
s.`PROJECT_ID` = p.`PROJECT_ID`
WHERE
P.`USER_ID` =(
SELECT
USER_ID
FROM
users
WHERE
EMAIL = 'test#gmail.com'
)
ORDER BY
s.`MODIFIED_DATE`
DESC
out put:
with Group by Query :
SELECT
p.`PROJECT_NAME`,
p.`CREATED_DATE`,
s.`MODIFIED_DATE`
FROM
`projects` p
JOIN `scenarios` s ON
s.`PROJECT_ID` = p.`PROJECT_ID`
WHERE
P.`USER_ID` =(
SELECT
USER_ID
FROM
users
WHERE
EMAIL = 'test#gmail.com'
)
group by p.PROJECT_NAME
ORDER BY
s.`MODIFIED_DATE`
DESC
output:
You can separately get the latest scenario per project using a subquery then the resulting rows will then be join again to get the other columns, if needed.
SELECT p.PROJECT_NAME,
p.CREATED_DATE,
s.MODIFIED_DATE
-- all columns in s.* will have the latest row
FROM projects p
INNER JOIN scenarios s
ON p.PROJECT_ID = s.PROJECT_ID
INNER JOIN
(
SELECT project_ID, MAX(modified_date) MAX_modified_date
FROM scenarios
GROUP BY project_ID
) t ON s.project_ID = t.project_ID
AND s.modified_date = t.MAX_modified_date
INNER JOIN users u
ON P.USER_ID = u.USER_ID
WHERE u.EMAIL = 'test#gmail.com'
ORDER BY s.MODIFIED_DATE DESC
However, if you don't need to get the other columns, you can directly use MAX() and GROUP BY.
SELECT p.PROJECT_NAME,
p.CREATED_DATE,
MAX(s.MODIFIED_DATE) AS MAX_MODIFIED_DATE
FROM projects p
INNER JOIN scenarios s
ON p.PROJECT_ID = s.PROJECT_ID
INNER JOIN users u
ON P.USER_ID = u.USER_ID
WHERE u.EMAIL = 'test#gmail.com'
GROUP BY p.PROJECT_NAME,
p.CREATED_DATE
ORDER BY MAX_MODIFIED_DATE DESC

Hibernate Query for equivalent sql

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();

Categories

Resources