DetatchedCriteria without on clause - mysql

I'm relatively new to Hibernate. I have to use the 3.2 version and i need to use DetachedCriteria and obtain the following query:
select this_.ID as ID0_1_, this_.SNDG as SNDG0_1_
, this_.NDG as NDG0_1_, this_.T_GWR_PARTNER_ID as T4_0_1_
, table2x1_.ID as ID1_0_, table2x1_.T_GWR_PROPOSAL_ID as T2_1_0_
, table2x1_.GROUP_SNDG as GROUP3_1_0_, table2x1_.GROUP_NAME as GROUP4_1_0_
from t_gwr_proposals this_
inner join
t_gwr_proposal_ratings table2x1_
where table2x1_.T_GWR_PROPOSAL_ID=this_.ID
but I obtain the follwing
select this_.ID as ID0_1_, this_.SNDG as SNDG0_1_
, this_.NDG as NDG0_1_, this_.T_GWR_PARTNER_ID as T4_0_1_
, table2x1_.ID as ID1_0_, table2x1_.T_GWR_PROPOSAL_ID as T2_1_0_
, table2x1_.GROUP_SNDG as GROUP3_1_0_, table2x1_.GROUP_NAME as GROUP4_1_0_
from t_gwr_proposals this_
inner join t_gwr_proposal_ratings table2x1_
** on this_.ID=table2x1_.ID **
where table2x1_.T_GWR_PROPOSAL_ID=this_.ID
using this code:
Criteria c = session.createCriteria(T_gwr_proposals.class, "Table1");
c.createAlias("Table1.T_gwr_proposal_ratings", "Table2"); // inner join by default
c.add(Restrictions.eqProperty("Table2.t_gwr_proposal_id", "Table1.proposalsId"));
return c.list();
Can anyone help me, please?
Thank you very much,
Tommaso A.

Criteria doesn't work with tables, but with entities and their association. You can only join two entities via the associations that exist between them. And only one root entity can exist in a criteria query. So, you won't be able to create such a query in Criteria (HQL should do fine, though) unless an association exists between the entities that uses table2x1_.T_GWR_PROPOSAL_ID=this_.ID as its mapping.

Related

join results into new table?

I can successfully join two tables, but i'm trying to output the results of the join into a new table.
The following throws a syntax error, but works if the "into" line is omitted.
To be clear - not having problems w/ the join, but the "into" statement.
SELECT evictions.uniqueid_neighborhoods.id, evictions.uniqueid_neighborhoods.neighbor_1,
evictions.sanfrancisco_evictions_backup2.Breach,
evictions.sanfrancisco_evictions_backup2.NonPayment,
evictions.sanfrancisco_evictions_backup2.Nuisance,
evictions.sanfrancisco_evictions_backup2.IllegalUse
** This causes code to fail
into evictions_by_commArea
from evictions.uniqueid_neighborhoods
inner join evictions.sanfrancisco_evictions_backup2 on evictions.uniqueid_neighborhoods.id = evictions.sanfrancisco_evictions_backup2.id
MySQL uses CREATE TABLE AS:
CREATE TABLE evictions_by_commArea as
SELECT un.id, un.neighbor_1,
sfe.Breach,
sfe.NonPayment,
sfe.Nuisance,
sfe.IllegalUse
from evictions.uniqueid_neighborhoods un join
evictions.sanfrancisco_evictions_backup2 sfe
on un.id = sfe.id;
I also introduced able aliases so the query is easier to write and to read.

Magento - SQL query programmatically

I have a SQL query that i would like to write with Magento's collection methods but i don't know how to.
I know that i have to use the getSelect() and joinLeft() methods, but don't know how to put a select inside a left join.
The query is :
SELECT
p.photo_id,
p.photo_name,
s.step_id,
s.step_name
FROM Photo p
LEFT JOIN (
SELECT
photo_id, MAX(step_id) AS max_step_id
FROM photoStep
GROUP BY photo_id
) ps
ON ps.photo_id = p.photo_id
LEFT JOIN Steps s
ON s.step_id = ps.max_step_id
I think that your best option here would be to try to avoid using the subquery. So I would start by reworking the SQL query and then use the functions groupByField & addExpressionFieldToSelect.
->groupByField('photo_id')
->addExpressionFieldToSelect("max_step_id", 'MAX({{step_id}})', 'step_id')

Multiple joins involving same table produces "column doesn't exist" error - MySQL

I'm new to joins and I'm sure this is ridiculously simple. If I remove one join in the query the remainder of the query works regardless of which join I remove. But as shown it gives the error saying the column doesn't exist. Any pointers?
select
loc_carr.address1 as carr_addr1,
loc_cust.address1 as cust_addr1
from db_name.carrier, db_name.customer
join db_name.location as loc_carr on vats.carrier.location_id=loc_carr.location_id
join db_name.location as loc_cust on vats.customer.location_id=loc_cust.location_id
thanks
I'll take a guess that there is a column named something like carrier_id that can be used to join the carrier and customer tables. Given that assumption, try this:
select
loc_carr.address1 as carr_addr1
, loc_cust.address1 as cust_addr1
from vats.carrier as a
join vats.customer as b
on b.carrier_id=a.carrier_id
join vats.location as loc_carr
on loc_carr.location_id=a.location_id
join vats.location as loc_cust
on loc_cust.location_id=b.location_id
Notice the use of aliases for the table references to make things easier to read. Also note how I'm using explicit SQL join syntax (instead of listing tables separated by commas).
#Bob Duell has the solution for your problem. To understand better why this error is produced, notice that in the FROM clause, you "join" tables using both explicit JOIN syntax and the implicit joins with comma: , which is (almost) equivalent to a CROSS JOIN. The precedence however of JOIN is stronger than the comma , operator. So, that part is parsed like this:
FROM
( db_name.carrier )
,
( ( db_name.customer
JOIN db_name.location AS loc_carr
ON carrier.location_id = loc_carr.location_id -- this line
) -- gives the error
JOIN join db_name.location AS loc_cust
ON customer.location_id = loc_cust.location_id
)
In the mentioned line above, the vats.carrier.location_id throws the error, as there is no carrier table in that scope (inside that parenthesis).

Hibernate native query with multiple joins on same table returning wrong results

I am using a native sql query where I have a players table to which I join three times, first to get the batsman name, then to get bowler name and then to get the fielder name. Now the first join works, but the next two also return the same name i.e the batsman name.
Here is the sql query
select
del.over_no ,
del.delivery_no ,
batsman.sname ,
outType.name ,
outBy.sname ,
fielder.sname ,
bep.runs,
bep.deliveries,
bep.fours,
bep.sixes
from delivery del
INNER JOIN batsman_performance bep ON del.innings_id=bep.innings_id
INNER JOIN ref_player batsman ON del.batsman_id = batsman.id
INNER JOIN ref_player outBy ON del.bowler_id = outBy.id
LEFT OUTER JOIN ref_player fielder ON del.fielder_id1= fielder.id
INNER JOIN ref_out_type outType ON del.out_type_id=outType.id
and del.out_type_id IS NOT NULL
and del.innings_id=:innings_id
and bep.player_id = del.batsman_id
order by over_no, delivery_no;
I am not using aliases for the selected columns because when i did, hibernate threw an exception for whichever column I use an alias
Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query] with root cause
java.sql.SQLException: Column 'over_no' not found.
This query is working when I run it on my mysql client and returns the correct dataset but when I run it in my code, the result set somehow overrides the two subsequent joins on ref_player table, leaving me with the batsman name in all three columns, i.e same name in batsman.sname, outBy.sname and fielder.sname columns.
I am stuck here for the last two days, Please any help would be great.
Try to wrap your select in another select statement and it should work.
I am using stored procedures but it should not make any difference
SELECT * FROM (
SELECT
del.over_no ,
del.delivery_no ,
batsman.sname ,
outType.name ,
outBy.sname ,
fielder.sname ,
bep.runs,
bep.deliveries,
bep.fours,
bep.sixes
from delivery del
INNER JOIN batsman_performance bep ON del.innings_id=bep.innings_id
INNER JOIN ref_player batsman ON del.batsman_id = batsman.id
INNER JOIN ref_player outBy ON del.bowler_id = outBy.id
LEFT OUTER JOIN ref_player fielder ON del.fielder_id1= fielder.id
INNER JOIN ref_out_type outType ON del.out_type_id=outType.id
and del.out_type_id IS NOT NULL
and del.innings_id=:innings_id
and bep.player_id = del.batsman_id
order by over_no, delivery_no
) AS subselection;
In the above you actually should use aliases otherwise you will have two columns with the same name which will throw an error
its a pending issue on the Hibernate bug tracking.
See this ticket
also in hibernate forums. This clearly shows this is bug a hibernates end.
See Hibernate Forum Discussion
did you try changing
order by over_no, delivery_no;
to
order by del.over_no, del.delivery_no;
Discovered the same issue.
Another workaround is to use org.hibernate.Session#doWork and perform the query on the JDBC connection:
entityManager.unwrap(Session.class).doWork(new Work() {
void execute(Connection c) throws SQLException {
PreparedStatement stmt = c.prepareStatement("SELECT ... JOIN ... JOIN ...");
try {
...
} finally {
stmt.close()
}

Symfony2, JOINS with doctrine2 or sql

I have a question about symfony2.
I have a project and I am using databases with it. I use for the most part Doctrine2 and entity classes. I like the entity class object database stuff, very handy etc.
My question is, is there a way to perform normal SQL in symfony? I always get an exception when I try to use standard SQL. I am having trouble with joins in doctrine2, so i would rather use normal SQL for that.
My join would look like this in SQL:
SELECT DISTINCT Document . *
FROM Document
INNER JOIN DocumentGruppe ON Document.id = DocumentGruppe.dokId
INNER JOIN UserGruppe ON DocumentGruppe.gruppenId = UserGruppe.gruppenId
WHERE UserGruppe.userId =9
The where clause at the end is just for testing. If I use doctrine with it's DQL it always says that there is an exception: The Variable DocumentGruppe was not defined before.
Here is my DQL query:
$test = $em->createQuery(
'SELECT DISTINCT d
FROM AcmeDocumentBundle:Document d
INNER JOIN DocumentGruppe dg ON d.id = dg.dokId
INNER JOIN UserGruppe ug ON dg.gruppenId = ug.gruppenId
WHERE ug.userId =9
'
);
Does anyone know a workaround or a way to use this doctrine2 stuff to work with joins?
Every JOINED tables must be declared as associations in mapping... How is your entity defined ? Show us your mapping file (Document.php if annotation, or Resources/config/doctrine/document;xml or yml if XMl or YAML).
Your request will be something like that :
$test = $em->createQuery(
'SELECT DISTINCT d
FROM AcmeDocumentBundle:Document d
INNER JOIN d.documentGruppen dg
INNER JOIN d.userGruppen ug
WHERE ug.userId =9
'
);