How to show Result from combined two tables by hibernate? - java

I have two tables in mysql.
Table tabA: { id, column1, column2}
Table tabB: {id, column1, column2}
Sql query: SELECT a.column1, a.column2, b.column2 FROM tabA a, tabB b WHERE a.id = b.id
How can I process the query result to display the values in the console?

Related

JQPL select inside select

just switched to spring boot from .NET Core, in .NET core we can easily nest a select inside a select like this:
var result = from c in context.Cars
join br in context.Brands
on c.BrandId equals br.Id
join col in context.Colors
on c.ColorId equals col.Id
select new CarDetailDto
{
Id = c.Id,
BrandName = br.Name,
CarName = c.Name,
ColorName = col.Name,
DailyPrice = c.DailyPrice,
ModelYear = c.ModelYear,
CarImages = (from cimg in context.CarImages
where cimg.CarId == c.Id
select new CarImage
{
Id = cimg.Id,
ImagePath = cimg.ImagePath,
CarId = c.Id,
Date = cimg.Date
}).ToList()
};
I want to do that in JPQL as well but didnt manage to solve
#Query( select column1, column2, column3 from tablename1 where coluname=(select columname from tablename2 where columnname=abcd) )
Your JPQL query should look like above.
Whatever subquery you write with condition.
If your query is fetching 3 column you need to create a DTO with same column name.
If your query is fetching list of rows then your actual jpql will look like this.
#Query( select column1, column2, column3 from tablename1 where coluname=
(select columname from tablename2 where columnname=abcd) )
List<ResultDTO> findAllResultList(Parameter value);
Above it is mapping the result to list of DTO objects to result rows.
If your query is fetching single row then your actual jpql will look like this.
#Query( select column1, column2, column3 from tablename1 where coluname=
(select columname from tablename2 where columnname=abcd) )
ResultDTO findResult(Parameter value);
The single result is mapped to one DTO object.
Make sure your result column name and DTO column name matches
Using the JPA repository call the names of the method which you used for the particular query.

Inserting value in middle table in sqlite

I am trying to insert a value in a middle table, which is created by having two other tables relationship many to many. So this middle table has 2 foreign keys(idProduct and idWarehouse), one for each table and an additional row(storage). So I have trouble inserting in this third row.
It gives this error:
Result: near "SELECT": syntax error
At line 1:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
VALUES
(SELECT
This is my code:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
VALUES
(SELECT id FROM Products
WHERE nameProduct = 'cheese',
SELECT id FROM Warehouse
WHERE nameWarehouse = 'Vegas',
'10')
Each of the queries must be enclosed inside parantheses:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage) VALUES
(
(SELECT id FROM Products WHERE nameProduct = 'cheese'),
(SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'),
'10'
);
This will work if theses queries return always only 1 row, so both columns nameProduct and nameWarehouse must be unique.
The statement can also be written without the VALUES clause, with SELECT:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
SELECT
(SELECT id FROM Products WHERE nameProduct = 'cheese'),
(SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'),
'10';

Custom SQL query to insert results of a SELECT into a table in Spring Boot JPA Hibernate

I have a spring boot project using JPA hibernate.
I'm trying to make a custom query that inserts the results of a select into a table. How would I do that?
This is my SQL query:
INSERT INTO aggregateTable
(
SELECT
avgSalesA,
avgSalesB,
salesMade,
tableA.employeeid
FROM
(
SELECT
avg(sales) as avgSalesA,
count(salesMadeDaily) as SalesMadeTotal,
employeeid
FROM companyA
GROUP BY employeeid
) tableA
INNER JOIN
(
SELECT
avg(sales) as avgSalesB,
employeeid
FROM companyB
GROUP BY employeeid
) tableB
ON tableA.employeeid = tableB.employeeid
)
You could simply use JPA:
entityManager.executeUpdate("INSERT INTO aggregateTable (Select avgSalesA, avgSalesB,
salesMade, tableA.employeeid FROM
(SELECT avg(sales) as avgSalesA, count(salesMadeDaily) as
SalesMadeTotal, employeeid FROM companyA GROUP BY
employeeid) tableA INNER JOIN (SELECT
avg(sales) as avgSalesB, employeeid FROM companyB group
by employeeid)
tableB ON tableA.employeeid = tableB.employeeid)");
Or if you use Spring Data repositories
#Modifying
#Query("<your insert query", nativeQuery=true)
public int insert();

How to retrieve data and count of data at same time in hql?

I want to retrieve count and list of data in one query only which I want to write on JPA repository. I wrote it using a constructor and executed using entity manager, but it didn't work. It gave me a QuerySyntaxException. Here is my query:
String hql = "select new core.abc(select count(*) from abc as m where m.Id in :Ids and m.Type = :Type,"
+ "select max(m.modificationTime) from abc as m where m.Id in :Ids and m.Type = :Type )";
How can I write such kind of query in JPA repository?
I just figure out your use case senario is that you want to get all records from table as well as total-count of records and max value of a specific column , you named that column as modificationTime. So onething will be happen in this case, if you want to intract with table with single query, Than you will get useless data for both column named as max and count.
Try This for JPA,
#Query(value="SELECT cb from abc cd where cd.Id in (?1) and cd.Type=?2 , (SELECT MAX(m.modificationTime) as maxModificationTime , COUNT(*) as count FROM abc m where m.Id in (?3) and m.Type=?4) as m",nativeQuery=true)

Query for many to many relationship database table

I have list of data and a table like below.
Data : {ABC111,ABC112,ABC113,111111,111112,111113}
Table:
Column 1 Column 2
ABC111 ABC115
ABC115 111333
111111 ABC112
111111 111112
ABC123 111113
111113 ABC113
My result should be like below
Result : {ABC115,111333,111113,ABC113,ABC123,ABC112,111112}
Explanation:
Data - ABC111 is associated to ABC115 which is also associated to 111333. Hence the result is ABC115,111333.
Similarly, ABC113 is associated to 111113 which is also associated to ABC123. Result = 111113,ABC123.
Is it possible to implement the above using a query. Looking for Prepared statement to which I will pass the Data that I mentioned above.
Try this:-
/*CREATING RECORDS FOR THE MAIN TABLE*/
CREATE TABLE TABLES(Column1 text, Column2 text);
INSERT INTO TABLES VALUES('ABC111','ABC115');
INSERT INTO TABLES VALUES('ABC115','111333');
INSERT INTO TABLES VALUES('111111','ABC112');
INSERT INTO TABLES VALUES('111111','111112');
INSERT INTO TABLES VALUES('ABC123','111113');
INSERT INTO TABLES VALUES('111113','ABC113');
COMMIT;
/*CREATE LIST TO BE SUPPLIED*/
CREATE TABLE LIST(Column1 text);
INSERT INTO LIST VALUES('ABC111');
INSERT INTO LIST VALUES('ABC112');
INSERT INTO LIST VALUES('ABC113');
INSERT INTO LIST VALUES('111111');
INSERT INTO LIST VALUES('111112');
INSERT INTO LIST VALUES('111113');
COMMIT;
/*CODE TO GET THE RESULT*/
SELECT CONCAT('{',GROUP_CONCAT(RESULT),'}') AS RESULT FROM
(
SELECT DISTINCT COLUMN1 AS RESULT FROM
(
Select a.column2 as column1,b.column2
from
(
Select * from
tables
where column1 in (SELECT COLUMN1 FROM LIST)
) a
inner join
tables b
on a.column2=b.column1
UNION ALL
Select b.column2 as column1,b.column1 as Column2
from
(
Select * from
tables a
where column2 in (SELECT COLUMN1 FROM LIST)
) a
inner join
tables b
on a.column1=b.column2
) a
UNION ALL
SELECT DISTINCT COLUMN2 AS RESULT FROM
(
Select a.column2 as column1,b.column2
from
(
Select * from
tables
where column1 in (SELECT COLUMN1 FROM LIST)
) a
inner join
tables b
on a.column2=b.column1
UNION ALL
Select b.column2 as column1,b.column1 as Column2
from
(
Select * from
tables a
where column2 in (SELECT COLUMN1 FROM LIST)
) a
inner join
tables b
on a.column1=b.column2
) a
UNION ALL
SELECT DISTINCT COLUMN2 AS RESULT FROM
(
Select distinct a.Column1, a.column2
from
(
Select * from
tables a
where column2 in (SELECT COLUMN1 FROM LIST)
) a
inner join
(
Select * from
tables a
where column2 in (SELECT COLUMN1 FROM LIST)
) b
on a.column1=b.column1
where a.column2 not in
(
Select column1 from
(
Select b.column2 as column1,b.column1 as Column2
from
(
Select * from
tables a
where column2 in (SELECT COLUMN1 FROM LIST)
) a
inner join
tables b
on a.column1=b.column2
) a
)
) a
) a;
Hope this helps:-)

Categories

Resources