Hibernate Exception on MySQL Cross Join Query - mysql

I'm trying to perform a bulk delete of an object, Feature, which has a birdirectional ManyToOne relationship with another class, FeaturesMetadata. I'm having a SQLGrammerException thrown.
The hql I'm using:
String hql = "delete from Feature F where F.featuresMetadata.stateGeoId = :stateGeoId";
Turning on show SQL, the following is generated:
delete from FEATURE cross join FEATURESMETADATA featuresme1_ where STATEGEOID=?
Running the SQL directly in the db client gives this exception:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'cross join FEATURESMETADATA featuresme1_ where stategeoid='01'' at line 1
Since the generated SQL is throwing the Exception, I tried changing dialects from MySQL5InnoDBDialect to MySQLInnoDBDialect, but no change.
Can anyone assist?

You may not have joins in such a HQL query. Quote from the reference documentation:
No joins, either implicit or explicit, can be specified in a bulk HQL
query. Sub-queries can be used in the where-clause, where the
subqueries themselves may contain joins.
So I guess something like this should work:
delete from Feature F where F.id in
(select f2.id from Feature f2 where f2.featuresMetadata.stateGeoId = :stateGeoId)

I had the same issue and struggled to find a sensible answer. It seems that, even if you get this approach to work, the SQL generated is highly inefficient (according to what I have read).
So I took a step back and did the following:
List<Properties> props = propDao.findPropertiesByHotelCode(hotel.getCode());
propDao.deleteInBatch(props);
propDao.flush();
Basically rather tan trying to 'delete where', I'm doing a select where and then deleting in batch the set that I retrieved.
Hope this helps.

This is indeed rather poor from Hibernate. But you can solve it like this in a repo: (at least in PostgreSQL, not sure if this syntax should be modified for MySql)
#Modifying
#Query(nativeQuery = true, value = """
DELETE FROM feature f
USING features_metadata fd
WHERE f.features_metadata_id = fd.id AND fd.state_geo_id = :stateGeoId
""")
void deleteByStateGeoIdId(#Param("stateGeoId") UUID stateGeoId);

Related

CodeIgniter fails Join Operation

I need to use a join operation. This is my code:
$this->db->from('d');
$this->db->where('id',$v);
$this->db->join('p', 'p.id = d.id');
$deal=$this->db->get();
The exception is:
Server returned HTTP response code: 500
The table is:
p(id,home) and d(id, p.id(this value is from p table),school);
What's wrong?
in your query
$this->db->from('d');
$this->db->where('id',$v);
$this->db->join('p', 'p.id = d.id');
$deal=$this->db->get();
where caluse is ambigeous, you have to put it like this
$this->db->where('d.id',$v);
also try
$this->db->join('p', 'p.id = d.id', 'inner' or 'left');
don't put both just put either inner or left in the join query,hopefully this will solve your problem and also make sure p, d are not synonyms they are actuall name of tables which exists in DB with same p, d names and have valid columns.
You have to try and check a few things in here:
1) Whether your database.php file contains the proper credentials. Look for any silly syntax errors as well.
2) Whether you are loading the database class?
3) Some times if you have installed the php package, the mysql driver would not have got installed. check whether you have installed mysql dirver php5-mysqlnd?

what is wrong with this line of SQL?

SELECT Batch.NumStud
FROM Batch
WHERE CourseID='$courseid'
INNER JOIN Course
ON Batch.CourseID=Course.CourseID"
an error that says mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>F:\AppServ\www\anNoECourse.php
is shown.This code was written to feed in data to a google chart.
You put SQL in wrong order (JOIN and WHERE are switched):
SELECT Batch.NumStud
FROM Batch INNER JOIN Course
ON Batch.CourseID = Course.CourseID
WHERE Course.CourseID = '$courseid'
It seems, that your query can be simplified (check your data):
select Batch.NumStud
from Batch
where Batch.CourseID = '$courseid'
I think the error is a bit more complex. Due to the fact that your SQL is invalid, you're not getting a result set. This case is not handled correctly by your PHP code!
So in addition to correcting your SQL as the others have suggested, please make sure to handle the case where you get no results or your query results in an error correctly in your PHP code!
The second part to your solution is as follows:
$result = mysql_query(...);
if ($result)
{
while (...)
...
}
This makes sure that mysql_query actually returned a result set and not false, which it does in case of errors (due to your invalid SQL code, but also in other cases). So just fixing your SQL is not enough to make your script error proof.
But again, do no longer use the mysql_.... functions! They are deprecated.

Codeigniter Active records complex query

> *1. I need to write this in Active records *
i need to join these 3 tables , but the condition for join is very very selective
$this->db->select(name);
$this->db->from('table0');
$this->db->join('table1','(table1.id=0 AND table0.feild1 = table1.feild1) OR (table1.id=1 AND table0.feild2 = table1.feild2)') // <--- how to write this is my question
i could do a simple join but the main problem is achieving the condition in the join that i have mentioned above.Also this is a small part of a very , very ! big query so i really cant change it back to the native sql query like :
$this->db->query('//entire sql query'); //cant do this, need to write ACTIVE RECORDS
when i write the active records , firebug throws me an error saying :
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ') OR
any suggestions ?
To be honest, I don't know that it is possible. CI doesn't use true Active Records, so each method has very rigid parameters, and I don't see any that can be tricked into performing the task you need.
What I would try is re-writing your query a bit:
$this->db->select(name);
$this->db->from('table0');
$this->db->join('table1','(table1.id=0 AND table0.feild1 = table1.feild1)', LEFT);
$this->db->join('table1','(table1.id=1 AND table0.feild2 = table1.feild2)', LEFT);
$this->db->where('(table1.id=0 AND table0.feild1 = table1.feild1)');
$this->db->or_where('(table1.id=1 AND table0.feild2 = table1.feild2)');
I believe this query would return the correct values, but you'll certainly want to thoroughly test it. Hope this at least points you in the right direction.

how to use string left function in hql

I have a sql query like this
select column from table where path = left('INPUTSTRING', length(path));
and trying to accomplish it in hql like this,
return session.createQuery("from Table where Path = left(:input, length(Path))").
query.setParameter("input", inputPath).
.list();
and getting an error like this
Caused by: org.hibernate.hql.ast.QuerySyntaxException: unexpected token: left near line 1
how to get this done? What is the corresponding string function in hql? Is there a solution for this using criteria query apis?
Yes, left() is not supported by the MySQLDialect. See the list of HQL supported functions on API docs.
Now you have left with 2 options.
Use session.createSQLQuery() method.
Create Your own Dialect class by extending the MySQLDialect and register the function there. This is told at hibernate forum here explained well in a blog post here.
I'm not sure if HQL does this for you , but you can use IQuery/session.CreateSQLQuery() to use a raw SQL query to populate a mapped entity. I've never used it for substrings, but have used it for aggregate functions. Check chapter 13 of the NHibernate docs and see if that does it for you. You can check the query substitution available in Nhibernate - here

How does linq-to-sql generate sql for collection pseudoqueries?

My understanding is that the LinqToSql pseudolanguage describes a set using a syntax very similar to SQL and this will allow you to efficiently update a property on a collection of objects:
from b in BugsCollection where b.status = 'closed' set b.status = 'open'
This would update the underlying database using just one SQL statement.
Normally an ORM needs to retieve all of the rows as separate objects, update attributes on each of them and save them individually to the database (at least that's my understanding).
So, how does linq-to-sql avoid having to do this when other orms are not able to avoid it?
The syntax shown in your question is incorrect. LINQ is not intended to have side-effects; it is a query language. The proper way to accomplish what you're looking for is
var x = from b in dataContext.BugsCollection where b.status == "closed";
foreach (var y in x)
y.status = "open";
dataContext.SubmitChanges();
This would generate the single SQL statement that you're talking about. The reason it is able to accomplish this is because of deferred execution - the L2S engine doesn't actually talk to the database until it has to - in this case, because SubmitChanges() was called. L2S then sends the generated SQL statement to the database for execution.
Because LINQ to SQL uses Expression Trees to convert your Query Syntax to actual SQL...it then executes the SQL against the database (rather than pulling all of the data, executing against the in-memory data, and then writing the changes back to the database).
For example, the following Query Syntax:
var records = from r in Records
where r.Property == value
select r
Gets translated first to Lamda Syntax:
Records.Where(r => r.Property == value).Select();
And finally to SQL (via Expression Trees):
SELECT Property, Property2, Property3 FROM Record WHERE Property = #value
...granted, the example doesn't update anything...but the process would be the same for an update query as opposed to a simple select.