Join Table condition - java

I have a query with columns (code, store, slotAvailable) in which results will be shown. As for the column "slotAvailable", it will contain the number of free slots for that particular "store". Now, to calculate how many free slots there are, I can only do this if I do a join with the table "TimeSlotInstanceReservation" because in this table there are a field "slotConsumed" that I need to perform the subtraction with the capacitytotal field of table "TimeSlotInstance" :
TimeSlotInstance as tsi
join TimeSlotInstanceReservation as tsir on {tsir. timeSlotInstance} = {tsi.pk}
However, when I do not have a reservation on a given TimeSlotInstance, no result is shown in the column "slotAvailable". How can I write a condition in the query that says "if there is no reservation then give me this value otherwise join with the reservation"? I hope I have explained myself well.
this query failed but not show error:
SELECT
{a.code} as 'Code',
{a.name} as 'Name',
({{
SELECT
{tsi.capacity} - IFNULL({tsir.slotsConsumedCount},0) as slot1820
FROM
{
TimeSlotInstance as tsi
join TimeSlotHour as tsh on {tsi.timeSlotHour} = {tsh.pk}
join StoreManager as sm on {sm.pk} = {tsi.store}
left Join TimeSlotInstanceReservation as tsir on {tsi.pk} = {tsir.timeslotinstance}
}
where {tsh.starttimelabel} = '18:00' and {tsh.endtimelabel} = '20:00' and {tsi.day} = '2022-07-26T22:00'
}}) as 'SLOT Available 18/20'
FROM
{
TimeSlotInstance as tsi
join TimeSlotHour as tsh on {tsi.timeSlotHour} = {tsh.pk}
}
where {tsi.day} = '2022-07-26T22:00'
but this work:
select
{tsi.capacity} - IFNULL({tsir.slotsConsumedCount}, 0) as SLOT1820
from
{
TimeSlotInstance as tsi
join TimeSlotHour as tsh on {tsi.timeSlotHour} = {tsh.pk}
left join TimeSlotInstanceReservation as tsir on {tsi.pk} = {tsir.timeslotinstance}
}
where {tsh.starttimelabel} = '18:00' and {tsh.endtimelabel} = '20:00' AND {tsi.day} = '2022-07-26T22:00'

You want a LEFT JOIN!
https://www.w3schools.com/sql/sql_join_left.asp
A LEFT JOIN between two tables returns all the records from the table on the left, plus any record from the table on the right that match the join condition. In the case where no record from the right table matches the join condition, nulls are returned for those columns, though the columns from the left table will be populated.
Hence your query would look something like
SELECT tsi.code, tsi.store,
tsi.capacitytotal - IFNULL(tsir.slotConsumed, 0) as slotAvailable
FROM TimeSlotInstance tsi
LEFT JOIN TimeSlotInstanceReservation tsir on tsi.pk = tsir. timeSlotInstance
Note that if the TimeSlotInstance -> TimeSlotInstanceReservation relationship is one-to-many you will need additional criteria in a WHERE clause to exclude dupe instances. If so, be aware that your conditions must allow for NULL values in the TimeSlotInstanceReservation table or you will exclude the unmatched records from TimeSlotInstance.

Related

For each order without invoice

i solve this task with 2 native query but want to solve this with one native query maybe will you show me the way if possible.
it's my first query:
select o.id as id,o.date as date,o.customer_id_id as customerId
from orders o left outer join
invoice i
on o.id = i.order_id_id
where i.order_id_id is null
intersect
select o.id as id,o.date as date,o.customer_id_id as customerId
from detail d join
orders o
on o.id = d.order_id_id
it's my second query and i use from first query o.id it's mean ?1=o.id:
select sum(d.quantity*p.price)
from product p join
detail d
on p.id=d.product_id_id
where d.order_id_id=?1
it is grafic of project
enter image description here
text of task:For each order without invoice, list its ID, the date it was placed and the total price of the
products in its detail, taking into account the quantity of each ordered product and its unit
price. Orders without detail must not be included in the answers.
If I understand correctly, this is an aggregation query after joining three tables (orders, detail, product). You can use NOT EXISTS or LEFT JOIN/WHERE to filter out the orders with no invoices:
select o.id, o.date, o.customer_id_id as customer_id,
sum(d.quantity*p.price)
from orders o join
detail d
on o.id = d.order_id_id join
product p
on p.id = d.product_id_id
where not exists (select 1
from invoices i
where o.id = i.order_id_id
)
group by o.id, o.date, o.customer_id_id;

Java -SQL query to extract data from two tables?

Select concat(substr(T_data,1,9),'001 ') AS Test_Data from DB1.T1 ;
Select * from DB1.T2 WHERE Test_Data = 'Test_Data';
I need to join the DB1.T1 and DB1.T2 based on Test_Data
Use an INNER JOIN (or, if you want nulls, an outer join)
Select t2.*
from DB1.T1 t1
INNER JOIN DB1.T2 t2 ON concat(substr(t1.T_data,1,9),'001 ') = t2.Test_Data
WHERE t2.Test_Data = 'Test_Data';

How to return multiple results in a unique mapped or not object JPA

org.hibernate
hibernate-core
4.3.8.Final
org.hibernate
hibernate-entitymanager
4.3.8.Final
My pom.xml
My Problem is: How to make a query like this...
SELECT
TABLE_D.*,
TABLE_A.NAME_A
FROM
TABLE_D
INNER JOIN
TABLE_E
ON TABLE_D.ID_TAB_E = TABLE_D.ID_TAB_D
LEFT JOIN
TABLE_C
ON TABLE_C.ID_TAB_C = TABLE_D.ID_TAB_D
INNER JOIN
TABLE_B
ON TABLE_B.ID_TAB_B = TABLE_C.ID_TAB_C
INNER JOIN
TABLE_A
ON TABLE_A.ID_TAB_A = TABLE_B.ID_TAB_B
WHERE
TABLE_A.NAME_A = "XXXX";
And Return the selected the values TABLE_D and TABLE_A ​​in a unique Object List(ex: Object that i create to take all this fields) (I could create 1 filter, whatever...) in the JPA ? Plz Help.
If you need to return a list of selected columns in HQL you can just write your hql query and return a List of Object array, i.e.:
List<Object[]> result = session.createQuery("select a.field1, b.field2 from EntityA a join a.entityB b").list();
then you can iterate and get values, based on their type (i.e. String):
for (Object[] arr : result) {
String col1 = (String)arr[0];
String col2 = (String)arr[1];
}

Count entities in multiple tables

I Have a non-entity class
public class CountryStatistics {
public CountryStatistics(Long numTowns, Long numVillages) {
...
}
}
For a given country i want to construct a statistics object.
Country, Village and City are the Entitys, so i tried things in line with code below.
String queryString =
"SELECT NEW mypackage.CountryStatistics(count(t), count(v))
FROM Town t, Village v WHERE t.country = :country AND v.country = :country"
TypedQuery<CountryStatistics> query =
em.createQuery(queryString ,CountryStatistics.class).setParameter("country", country);
query.getSingleResult()
Question: What is the correct way to count some entities in different tables in the same query?
With the above query i end up with way to high numbers if i put distinct like below, number of towns will be correct.
"SELECT NEW mypackage.CountryStatistics(count(distinct t), count(v))
FROM Town t, Village v WHERE t.country = :country AND v.country = :country"
But if I set it for villages also i get:
java.sql.SQLSyntaxErrorException: Multiple DISTINCT aggregates are not supported at this time.
The following query (not tested) should do what you want:
select count(distinct t.id), count(distinct v.id) from Country c
left join c.towns t
left join c.villages v
where c.id = :countryId

How to flatten the results of a Hibernate query

Say I executed a theoretical HQL query like FROM Customer. And in Customer is a getOrders() getter returning a ManyToOne collection of Order objects. This executes a SQL statement selecting from Customer with a left join to Order.
Through the object model, I can programmaticly iterate over Customers and then iterate over Orders.
However, I want to convert the hierarchical object model to a flat tabular result of the left join so that the results would look much like that of this SQL query:
SELECT *
FROM Customer
LEFT JOIN Order on Customer.customerId = Order.customerId
Sample result:
Customer.customerId ... Order.orderId Order.customerId ...
1 200 1
2 201 2
2 202 2
3 NULL NULL
Is there an easy way to do this with Hibernate?
Depends what you want at the "scalar" level which you control through using an explicitl select clause.
select c, o
from Customer c left join c.orders o
returns you List of (Customer, Order) tuples. Or:
select c.id, c.name, o.id, ...
from Customer c left join c.orders o
which returns you a scalar projection of the atomic pieces.
In both cases you get back a List. You can use "dynamic instantiation" in both cases (though really its more useful in the second case imho):
select new CustomerOrderSummary( c.id, c.name, o.id, ... )
from Customer c left join c.orders o
where CustomerOrderSummary is just a plain class with matching constructor.
Possible you can do this via expressing of result set. http://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/query_native.html
From the example:
#SqlResultSetMapping(name="GetNightAndArea", entities={
#EntityResult(name="org.hibernate.test.annotations.query.Night", fields = {
#FieldResult(name="id", column="nid"),
#FieldResult(name="duration", column="night_duration"),
#FieldResult(name="date", column="night_date"),
#FieldResult(name="area", column="area_id")
}),
#EntityResult(name="org.hibernate.test.annotations.query.Area", fields = {
#FieldResult(name="id", column="aid"),
#FieldResult(name="name", column="name")
})
})
I think you can try retrieving results in Object[] e.g. below:
EntityManager entityManager = EntityManager.getEntityManager();
Query query= entityManager.createQuery("select cust, ord from Customer cust left outer join cust.orders ord where cust.customerId = :customerId");
tradeQuery.setParameter("customerId", aCustomerId);
List<Object[]> resultList = (List<Object[]>)query.getResultList();
The retrieved resultsList will be list of Object array containing Customer and Order objects in flat.
if(!resultList.isEmpty()){
Iterator<Object[]> iter = resultList.iterator();
while(iter.hasNext()){
Object[] resultObj = (Object[])iter.next();
Customer customer= (Customer )resultObj[0];
Order order = (Order)resultObj[1];
}
}
Hope this helps!

Categories

Resources