EBean inner join on the same table - java

I need to execute an inner join on the same table. Below is the raw query I am currently executing.
String tagValueRowsSQL = "SELECT itv1.ItemTagValueID,itv1.FkItemID," +
"itv1.FkTagID,itv1.TagIndex,itv1.ValueIndex,itv1.Value,itv1.LastUpdateDateTime" +
" FROM tag.ItemTagValue itv1" +
" INNER JOIN tag.ItemTagValue itv2" +
" on itv1.fkTagID=" + tagIDsAndValues.get(LOCATION_STORE_CONFIG_TAG_NAME).getTagID() +
" and itv1.Value=" + storeId +
" and itv2.fkTagID = " + tagIDsAndValues.get(SENSOR_TYPE_TAG_NAME).getTagID() +
" and itv2.Value=" + sensorType;
RawSql rawSqlForSensorsInStoreAndOfType = RawSqlBuilder.parse(tagValueRowsSQL)
.columnMapping("itv1.ItemTagValueID", "ItemTagValueID")
.columnMapping("itv1.FkItemID", "FkItemID")
.columnMapping("itv1.FkTagID", "FkTagID")
.columnMapping("itv1.TagIndex", "TagIndex")
.columnMapping("itv1.ValueIndex", "ValueIndex")
.columnMapping("itv1.Value", "Value")
.columnMapping("itv1.LastUpdateDateTime", "LastUpdateDateTime")
.create();
Query<ItemTagValueModel> query = Ebean.find(ItemTagValueModel.class);
List<ItemTagValueModel> sensorsTagValueData = query.setRawSql(rawSqlForSensorsInStoreAndOfType).findList();
Executing the above using RawSQL seems pretty clumsy. How can I execute the above without using RawSQL? I checked this question Ebeans where columnA equals columnB in same table but I'm not sure how to apply that answer to my situation. Any help would be much appreciated.

Related

Map a result of an SQL to a field using Hibernate

I am looking for a way of mapping an SQL result of type bool to a field of an entity.
Here's the code I need to work with:
#Formula("next_erds_id is null \n" +
"and exists(\n" +
" select * from processes p\n" +
" where p.message_uuid = message_uuid \n" +
" and exists(select * from process_tasks t\n" +
" where t.process_uuid = p.process_uuid and t.task_name = 'MP_MESSAGE_PROCESSED')\n" +
" and not exists(select * from process_tasks t\n" +
" where t.process_uuid = p.process_uuid and t.task_name = 'CH_NOTIFICATION_CREATED') \n" +
")")
private boolean canNotifyOnStartDeliveryAfter;
(Please ignore the field name. I've got no idea what it is supposed to mean...)
Of course, it does not work because it's not a valid MSSQL syntax.
Any idea how to fix it?

Sqlite Android Optimization

I have an application that works well. But I suspect that I can improve it if I optimize queries to the database. And I need suggestions.
This is part of my "select query":
private static final String SELECT = "SELECT " +
"dz.first_id AS first_id, " +
"dz._id AS _id, " +
"dz.att1 AS att1, " +
"dz.att2 AS att2, " +
"dz.att3 AS att3, " +
"dz.att4 AS att4, " +
"dz.att5 AS att5, " +
"d.var1 AS var1, " +
"d.name AS name, " +
"d.last_update AS last_update, " +
"d.image_url AS image_url, " +
"d.image_highlighted_url AS image_highlighted_url, " +
"d.var2 AS var2, " +
"d.type AS type, " +
"d.state AS state, " +
"d.sync AS sync, " +
"d.var3 AS var3 " +
"FROM table1 dz INNER JOIN table2 d " +
"ON d._id = dz.first_id ";
Cursor result = conn.rawQuery(SELECT, null);
*table1 and table2 have simple creation: only one _id integer PRIMARY KEY AUTOINCREMENT NOT NULL
It is useful to use views? Any other suggestion?
Thanks.
This query looks as cut and dry and they can get, I think your options are really either to see if you can somehow leave some unnecessary columns out of your select or alternatively to see that both dz.first_id and d._id have indexes setup. Perhaps add a index to dz with the following
CREATE INDEX index1 ON table1 (first_id);

Mistake in HQL query while creating reports through hibernate projection

I had the following query working fine but then i had to convert it to hibernate projection for performance issues.
NamedQuery = " SELECT o FROM OrderJob o "
was converted to:-
String hqlQuery = "select "
+ "new JobAuditListVO( o.jobDate, o.jobType, customer.name, job.street, payment.description, p.paid,o.invoice) "
+ " from OrderJob o "
+ " join o.order ordr "
+ " join ordr.customer customer "
+ " join o.jobAddress job "
+ " join o.payment p"
+ " join p.paymentReceivedMethod payment";
getEntityManager().createQuery(hqlQuery).getResultList();
But the list is returning 0 results. While the name query return 2 results.
I have got the answer. Both the queries are absolutely equivalent.
The problem was that i had to use Left Join instead of Simple Join. Because some entities were returning null.

SQLite fails to find existing column in SELECT via JDBC and jOOQ

I experience some strange results working with SQLite and JDBC (via JOOQ actually, but this problem can be reproduced by executing the query string manually via JDBC). My database consists of a three tables including a many-to-many and one-to-many relationship. I try to select all values of the 'main' table and join all needed values out of the relationship tables:
SELECT location.name,
world.world,
player.player
FROM location
JOIN world
ON location."world-id" = world."world-id"
LEFT OUTER JOIN (location2player
JOIN player
ON location2player."player-id" = player."player-id")
ON location."location-id" = location2player."location-id"
Within JDBC this query fails:
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such column: player.player)
When I execute the query in an external SQLite editor such as SQLite Manager for Firefox it works as expected.
I work with sqlite-jdbc-3.7.2 which I cannot change. For reference, the JOOQ query is:
create.select(LOCATION.NAME,WORLD.WORLD_,PLAYER.PLAYER_)
.from(LOCATION
.join(WORLD)
.on(LOCATION.WORLD_ID.eq(WORLD.WORLD_ID)
)
.leftOuterJoin(LOCATION2PLAYER
.join(PLAYER)
.onKey()
)
.on(LOCATION.LOCATION_ID.eq(LOCATION2PLAYER.LOCATION_ID)
)
.fetch()
Why fails this query in JDBC and how am I supposed to fix it?
While I think that you wrote valid ANSI SQL, it may well be that SQLite interprets your statement slightly differently. But you don't really need to nest joins the way you do. Try this insted:
SELECT location.name,
world.world,
player.player
FROM location
JOIN world
ON location."world-id" = world."world-id"
LEFT OUTER JOIN location2player
ON location."location-id" = location2player."location-id"
LEFT OUTER JOIN player
ON location2player."player-id" = player."player-id"
I was able to recreate your issue under sqlite-jdbc-3.7.2 using
sql =
"SELECT location.name, " +
"world.world, " +
"player.player " +
"FROM " +
"location " +
"JOIN world " +
"ON location.\"world-id\" = world.\"world-id\" " +
"LEFT OUTER JOIN (location2player " +
"JOIN " +
"player " +
"ON location2player.\"player-id\" = player.\"player-id\") " +
"ON location.\"location-id\" = location2player.\"location-id\"";
The problem appears to be that the location2player and player tables are "hidden" inside the parentheses () of the sub-join and are unavailable to the initial column list and the final ON clause. The following statement avoids that problem by giving the subquery an alias and using the alias name in those two places:
sql =
"SELECT " +
"location.name, " +
"world.world, " +
"playerlocation.player " +
"FROM " +
"location " +
"JOIN " +
"world " +
"ON location.\"world-id\" = world.\"world-id\" " +
"LEFT OUTER JOIN " +
"( " +
"SELECT location2player.\"location-id\", player.player " +
"FROM " +
"location2player " +
"JOIN " +
"player " +
"ON location2player.\"player-id\" = player.\"player-id\"" +
") AS playerlocation " +
"ON location.\"location-id\" = playerlocation.\"location-id\"";

Trouble with a line of SQL in my java program

So the program is the connecting to a .mdb file as our data base. I have written all the other code to the program and know it works fine but I am now having trouble with a complex SQL statement being passed as a parameter to a createQuery(Sring, int) method.
There are two tables
Person, which has Name, Id, City, State
Classes, which has Id, Course, Grade
The intended purpose of this line is to print out "Name and Id" from a table of Persons and also print "Course and Grade" from the Classes table. The query only prints entries with matching Id's(Person.Id = Classes.Id), in a specific Course('CSC 225'), and that have a Grade > 70.
We never were taught the SQL statements in any depth so my basic understanding has concocted the following lines of code.
String s = "SELECT " + personTableTitle + ".Name, " + personTableTitle + ".Id, " +
classesTableTitle + ".Course, " + classesTableTitle + ".Grade FROM " +
personTableTitle + " " + classesTableTitle + " WHERE " +
personTableTitle + ".ID = " + classesTableTitle + ".Id AND " +
"Course = 'CIS 225' AND " + classesTableTitle + ".Grade > 70 AND " +
personTableTitle + ".Id = ? AND " + classesTableTitle + ".Id = ?";
System.out.print(s); // Double check of my SQL Statement before passing
db.createQuery(s, 4);
I have been playing with this SQL statement since Wednesday night and haven't been having much luck.
I only see two problems. Sql needs commas between the table names in the FROM clause, i.e. ...FROM table1, table2 WHERE.... So change your line to
personTableTitle + ", " + classesTableTitle + " WHERE " +
This next one might not be a problem, but it's a good idea to include the table name in front of every field reference.
classesTableTitle + ".Course = 'CIS 225' AND " + classesTableTitle + ".Grade > 70 AND " +
You should definitely try your query directly on the database (console or GUI). Once your query is valid, you'll be able to translate it very quickly back into Java.
Otherwise, it's good practice to add an alias to tables; for example:
select *
from Person P, Classes C
where P.Name = 'joe' and P.id = C.id
You may also need to do an outer join to get your data (look at how to do joins for your database).
Here's what I would suggest for SQL code
String s = "SELECT P.Name, P.Id, ";
s = s + "C.Course, C.Grade ";
s = s + "FROM Person P ";
s = s + "JOIN Classes C ";
s = s + "ON P.ID = C.ID ";
s = s + "WHERE Course = 'CIS 225' AND C.Grade > 70;";
I split up each assignment into its own line.
Solved it everyone, thanks for the help.
I started rewriting it using the suggestions posted and came up with this as the string:
String s = "SELECT Person2.Name, Person2.Id, Classes.Course, Classes.Grade FROM Person2, Classes WHERE Classes.Id = Person2.Id AND Classes.Course = 'CIS 225' AND Classes.Grade >70";
It works so I can make it more presentable now. The reason I am using my variable names from java in the original post was that is what the teacher wanted. She is very stubborn and has taken off points from my material for things as simple as writings += whatever; instead of s = s + whatever;

Categories

Resources