How to write this SQL query as a JPA query - mysql

I have this query that is running successfully in mysql but I am trying to write it as a JPA query and I keep getting errors. Here are my tables.
Table 1: business_accounts{id, business_name}
Table 2: work_locations{location_id, name, contractor_id }
//contractor_id on Table2 is the foreign key matched to id on table 1.
My sql query is that I want to return all values of business_name where id from table 1 equals contractor_id from table 2 and where name="Dublin" Here is my sql query that is working in mysql:
SELECT b.business_name FROM work_locations w
inner join business_accounts b on b.id=w.contractor_id where name="Carlow"
And here is the approach that I am taking in JPA that isn't working. Any suggestions are appreciated. Thanks
String countyName="Dublin";
Query myQuery2 = em.createQuery("SELECT b FROM business_accounts b join "
+ "w where b.id=w.contractor_id and w.name=:countyName");
myQuery2.setParameter("countyName", countyName);

You need to create correct entities corresponding to the table.
a. Business_Account entity
b. Work_Location is the other
c. You may choose to create separate a separate join table for the join between a. and b. I would suggest that, but its your preference.
Based on the a. and b. Try something on these lines -
String countyName="Dublin";
final TypedQuery<String> query = entityManager
.createQuery(
"Select distinct b.business_name from Business_Account b, IN(b.id) location where b.id=location and location.name =:countyName", String.class); //$NON-NLS-1$
query.setParameter("countyName", countyName); //$NON-NLS-1$

Try the below code:
Use createNativeQuery
SELECT b.business_name instead of SELECT b
Add the ENTITY CLASS with the query that will be the return type.
String QUERY = "SELECT b.business_name FROM business_accounts b join w where b.id=w.contractor_id and w.name=?)";
List list = em.createNativeQuery(QUERY, ENTITY_CLASS_HERE.class)
.setParameter(1, countyName)
.getResultList();

Related

Using results of one query into the next with unlike column names

My Platform is MySql
I have two queries that I need to combine, using the first query as a type of filter for the second query.
Query 1:
SELECT * FROM INVENTORY
WHERE INV_ID = 1
AND FSCL_YR = 2017
From this query we will get results back that includes a column named STR_NBR.
Which we then want to use in the second query as 'If the store number appears in the first query, give me the results where it shows in the second'. The second query tables use the column name SND_LOC_NBR instead of STR_NBR.
Query 2:
SELECT * FROM Transfer A
LEFT JOIN Transfer_Detail B
ON A.XFER_NBR = B.XFER_NBR
WHERE A.XFER_NBR = B.XFER_NBR
AND A.XFER_STAT_IND IN ('S','C')
AND (where the SND_LOC_NBR needs to match STR_NBRs found from Query 1)
Try this:
SELECT * FROM Transfer A
LEFT JOIN Transfer_Detail B
ON A.XFER_NBR = B.XFER_NBR
WHERE A.XFER_STAT_IND IN ('S','C')
AND SND_LOC_NBR IN
(SELECT STR_NBR FROM INVENTORY
WHERE INV_ID = 1 AND FSCL_YR = 2017 )

how to write hql join query

I'm new from HQL any one Please tell me how to write this Query in HQL.
My SQL Method is
public Integer validateEditDate(int id, String date);
My SQL Query is
SELECT
count(a.activity_task_id)
FROM activity_task_details AS a
JOIN milestone_activity_details AS b
ON a.milestone_activity_id = b.milestone_activity_id
WHERE a.milestone_activity_id = 17
AND DATE(a.task_end_date) > '20161229';
Where id and date is dynamic
Please convert this sql query in Hql query
To convert a SQL query in HQL you must define, as first, classes about db table mapping.
You have these two tables:
activity_task_details
milestone_activity_details
So you must have two classes, as follow:
ActivityTaskDetails
MilestoneActivityDetails
So, you must map your fields as properties. Suppose you have done this, your query will became:
SELECT
count(a.activity_task_id)
FROM ActivityTaskDetails a, MilestoneActivityDetails b
WHERE a.milestone_activity_id = b.milestone_activity_id
AND a.milestone_activity_id = :paramId
AND a.task_end_date > :paramDate;
Pay attention, if possible, your task_end_date in class ActivityTaskDetails declare as date
To execute your query:
String hql = "Your HQL query write upper";
Query q = session.createQuery(hql);
q.setString("paramId", id);
q.setDate("paramDate", date);
q.list();
session is a variable to get session factory object

SQL Query Assistance - Left join unexpected result

I have these 2 queries:
$sql = "SELECT *
FROM ultrait_wpl_properties
LEFT JOIN ultrait_wpl_property_types
ON ultrait_wpl_properties.property_type = ultrait_wpl_property_types.id
ORDER BY ultrait_wpl_properties.id ";
$sql2 = "SELECT *
FROM ultrait_wpl_properties, ultrait_wpl_property_types
WHERE ultrait_wpl_properties.property_type = ultrait_wpl_property_types.id
ORDER BY ultrait_wpl_properties.id";
For some odd reason when the IDs are output some are duplicated? By my reseaning these queries should get everything from the table in the first part and join the second table based on the WHERE condition.
<property><id>13</id></property>
<property><id>6</id></property>
<property><id>6</id></property>
<property><id>6</id></property>
<property><id>6</id></property>
<property><id>7</id></property>
This may be slightly unclear but for some reason I'm getting duplicate IDs, all i want really is to be able to access the property type which links to the ID in the second table.
I have tested both queries in phpMyAdmin and they yeild the desired result, however when I use the queries in my php script they return unexpected results.
You are getting one row for each row in table ultrait_wpl_properties. What else do you expect? If it is just one record per type, then you would have to re-write your query accordingly. You select * from both tables. But is it only the type ID you need? Then why join the tables at all?
Get all type IDs:
select id from ultrait_wpl_property_types;
Get all type IDs in table ultrait_wpl_properties:
select distinct property_type from ultrait_wpl_properties;
Get all type data for types in ultrait_wpl_properties:
select * from ultrait_wpl_property_types
where id in (select property_type from ultrait_wpl_properties);
You are getting a Cartesian result in the case the ultrait_wpl_property_types table has multiple records for a single property. Such as a property type could be Type A, Type B, Type C which might be descriptive "types". So a single property would be accounted for each entry.
You might just need to do SELECT DISTINCT, or GROUP BY ultrait_wpl_properties.id to make sure only one record per ID, but with generic "Select * ", I would first try with GROUP BY.

How do I convert this SQL query into hibernate

Can someone please tell me how to convert this SQL query into hibernate?
SELECT * FROM sys_quote_master AS g1
INNER JOIN
(SELECT order_base_id, order_id FROM sys_quote_master
GROUP BY order_base_id, order_date_last_revised
ORDER BY order_date_last_revised desc) AS g2
ON g2.order_id = g1.order_id;
Basically,
I have tried this and it doesn't work:
DetachedCriteria crit1 = DetachedCriteria.forClass(QuoteMaster.class);
ProjectionList pList = Projections.projectionList();
pList.add(Projections.groupProperty("orderBaseId"));
session = HibernateSessionFactory.currentSession();
Criteria crit = session.createCriteria(QuoteMaster.class);
Criteria c = crit.createCriteria("QuoteMaster", CriteriaSpecification.INNER_JOIN);
c.setProjection(pList);
I get this error:
org.hibernate.QueryException: could not resolve property: this of:
QuoteMaster
And I think it has to do with this line of code were I am trying to create an inner join to the same table:
Criteria c = crit.createCriteria("QuoteMaster", CriteriaSpecification.INNER_JOIN);
So basically, my question is 'How to create a join to the same table using Criteria.createCriteria or Criteria.createAlias?' The doc for Criteria class states the first parameter is a dot-separated property path, but what the heck does that mean? :)
Every example I found so far shows how to do this with 2 or 3 tables but not to the same table and I have no idea what to use for the first argument.
I dont know how your entities are, this should give rough idea.
from SystQuoteMasterEntity sqm join ( select sqm1.orderbaseid, sqm1.orderId from SystQuoteMasterEntity sqm1 group by orderbaseid,orderdatelastrev order by orderdatelast desc) g2

Correct MySQL JOIN format to avoid nested SELECT

I have two separate SELECT statements:
SELECT VCe.VId FROM `VCe` WHERE `YId` = 9007 AND `MaId` =76 AND `MoId` = 2851
SELECT r_pts.p_id FROM r_pts WHERE r_pts.v_id IN (57202, 57203, 69597, 82261, 82260, 69596, 69595, 82259)
When they are run separately they both complete in under .05sec however when I nest the first one within the second, it dramatically increases to 3.3sec.
I would like to do a join so that I can get the output from the second SELECT using the first select as the result set for the IN() but I cannot figure out how to include WHERE conditions in a JOIN.
Edit: Also what is the correct syntax to do a join as I am requesting?
Thanks for your help, its appreciated!
Equivalent to MattMcKnight's query whilst illustrating "how to include WHERE conditions in a JOIN":
SELECT r.p_id
FROM r_pts r
INNER JOIN VCe v
ON v.VId = r.v_id
AND
v.YId = 9007
AND
v.MaId = 76
AND
v.MoId = 2851
SELECT r_pts.p_id FROM r_pts, 'VCe' WHERE r_pts.v_id = VCe.VId AND VCe.YId = 9007 AND VCe.MaId =76 AND VCe.MoId = 2851
The basic goal of a join is to describe how the two tables relate. I inferred from your example that the v_id column in the r_pts table was a foreign key pointing to the VId primary key in the VCe table. When you add a term in the query (such as "r_pts.v_id = VCe.VId") that has a field from each table you wish to join, that tells the database how to match up the rows between the tables to make "virtual rows" that contain the columns from both tables. Your other query terms limit which rows are included in the result set.