Hibernate createSQLQuery and Toad SQL query return different results - parameter problems? - sql

I'm a newbie at Hibernate so excuse me if some of this is glaringly obvious but it's been a very, very long day. I am trying to create and execute a simple query in Hibernate and Toad/Oracle.
The Toad/Oracle sql reads:
select
count(*)
from
fpps_owner.fee_claim_payment_lines l,
fpps_owner.fee_claim_payments p
where
l.fee_claim_payment_id = p.fee_claim_payment_id and
p.claim_index = 87167895
The above returns 10 records, which is correct
The following Java code returns 0 records, which is NOT correct
String sLinesAvailable =
"select count(*) from " +
"fpps_owner.fee_claim_payment_lines l, fpps_owner.fee_claim_payments p " +
"where " +
"l.fee_claim_payment_id = p.fee_claim_payment_id and p.claim_index = :id";
Query qLinesAvailable = em.createNativeQuery(sLinesAvailable);
qLinesAvailable.setParameter("id", "87167895"); // fails
qLinesAvailable.setParameter("id", 87167895); // fails
List<Object> out = (List<Object>) qLinesAvailable.getResultList();
BigDecimal x = (BigDecimal) out.get(0);
Returns 0 records. Using .getSingleResult() also returns 0 records.
What am I missing here?
Any help would be GREATLY appreciated!

If you are not seeing any malformed query errors, it seems like the parameter is not binding correctly.
To debug, I'd print out that SQL statement the line after you set the parameter. This is the only way you can see the SQL after the parameter is set in order to compare it with Toad.
What does your binding file look like? Maybe you have a different name in there for the ID, so it's not able to find it based on the name. Trying binding with the parameter's order value, just as a test.
This might give some ideas: http://www.mkyong.com/hibernate/hibernate-parameter-binding-examples/
Best of luck! We've all been there :)

What happens when you try:
(Number) query.getSingleResult();
Your query isn't returning a list, but rather just a count.
Good luck.

Related

Is it possible to pass and use sql inside a sql parameter?

I'm working with a query that is used by multiple services but the number of results returned are different based on filtering.
To avoid copying and pasting the query, I was wondering if it was possible to pass in piece of sql into a sql parameter and it would work? I'm also open to alternative solutions.
EXAMPLE:
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("filter", "and color = blue");
namedParameterJdbcTemplate.query(“select * from foo where name = 'Joe' :filter”, parameters, new urobjRowMapper());
It is very dangerous and fragile to let callers pass SQL to your program, because it opens you up to SQL injection - the very problem the parameters are there to prevent.
A better approach is to pre-code the filters in your query, and protect them by a special "selector" parameter:
SELECT *
FROM foo
WHERE name='Joe' AND
(
(:qselect = 1 AND color='blue')
OR (:qselect = 2 AND startYear = 2021)
OR (:qselect = 3 AND ...)
)

cfsavecontent display double apostrophe in SQL statement

I have several OR in my SQL statement so I want to save a chuck of it in a cfsavecontent. Here is that part:
<cfsavecontent variable="checkDepartment">
<cfif #wrkDept# EQ #dept[2][1]#>
Department = 'Health' AND
<cfelse>
Department = '#wrkDept#' AND
</cfif>
</cfsavecontent>
But the error I get on the page shows 2 sets of apostrophes around the word Health.
SQL
SELECT COUNT(*) AS numItems
FROM IT_PROJECTS
WHERE
Department = ''Health'' AND
status = 'Cancelled'
Can anyone help me to only get a single apostrophe? Thanks
So this answer seems a lot more complicated than it really is. And without knowing specifically what your query looks like (re:OR conditions), I'm not really sure how to structure it. It can be better. The goal should be to make one single trip to your SQL server with the query that makes the most sense for the data you're trying to get. I'm not sure what you are trying to do with cfsavecontent, but I don't think you need it.
The bulk of my example query (https://trycf.com/gist/4e1f46bfa84a6748aced0f9ee8221c6d/acf2016?theme=monokai) is setup. I chose to go with a cfscript format, because as Redtopia said, I also find it much easier to build a dynamic query in cfscript.
After initial setup, I basically just script out the variables I'll use in my final queryExecute().
// Base query.
qry = "SELECT count(*) AS theCount FROM IT_PROJECTS WHERE 1=1 " ;
// This is our dynamic filter that we build below.
qfilter = {} ;
// Query options.
opts = { "dbtype":"query" } ;
After we have our base, I build up the dynamic part of the query. This is the part that will likely change quite a bit depending on your current needs and setup.
For the first part, I basically replaced your cfif with a ternary evaluation. I'm not sure how your data plays into the evaluation of dept or where that array comes from. But from there I build a basic included statement of the query and set up the queryparam values for it. Then I add a second check that will pick a different set of values for the query (currently based on even/odd seconds). Again, I'm not sure of the intent of your query here, so I just made something dynamic.
//////////// BUILD DYNAMIC FILTER ////////////
qdept = ( wrkDept == dept[2][1] ) ? 'Health' : wrkDept ;
/// This one is an included filter:
qry &= " AND department = :dpt AND status = :sts " ;
qfilter.dpt = {"value":qdept,"cfsqltype":"CFSQLVARCHAR"} ;
qfilter.sts = {"value":"Cancelled","cfsqltype":"CFSQLVARCHAR"} ;
/// Adding Dynamic ORs
// Dynamically set status based on even/odd seconds.
qStatus = ( now().second()%2==0) ? "Cancelled" : "Active" ;
qry &= " OR ( department = :dpt2 AND status = :sts2 ) " ;
qfilter.dpt2 = {value:"IT",cfsqltype:"CFSQLVARCHAR"} ;
qfilter.sts2 = {value:qStatus,cfsqltype:"CFSQLVARCHAR"} ;
This gives us a SQL string that looks like:
SELECT count(*) AS theCount
FROM IT_PROJECTS
WHERE 1=1
AND department = :dpt AND status = :sts
OR
( department = :dpt2 AND status = :sts2 )
With a SQL statement, the placement of AND and OR conditions can greatly impact the results. Use parenthesis to group conditions how you need them.
After we've built the query string, we just have to plug it and our queryparams into the queryExecute().
result = queryExecute( qry , qfilter , opts ) ;
And if we want to output our data, we can go:
writeOutput("There are " & result.theCount & " records." ) ;
Which gives us:
There are 8 records.
Again, I don't know what your main conditions look like. If you can give me an example of a query with a bunch of ORs and ANDs, I'll try to modify this for you.

UPDATE QUERY - Sum up a value from form with value from table

I've just started using microsoft access so I don't really know how to solve this. I would like to use an update query to add a value from a form to a value on a table.
I originally used the SUM expression which gave me an error saying it was an aggregate function.
I also tried to add the two values together (e.g [field1] + [field2]) which as a result gave me a value with both numbers together instead of adding them together.
The following is the SQL I'm using:
UPDATE Votes
SET Votes.NumVotes = [Votes]![NumVotes]+[Forms]![frmVote]![txtnumvotes]
WHERE (((Votes.ActID) = [Forms]![frmVote]![combacts])
AND ((Votes.RoundNum) = [Forms]![frmVote]![combrndnum]))
I want to add a value [txtnumvotes] a form to a field [NumVotes] from the table [Votes].
Could someone please help me?
You can specify the expected data type with parameters:
PARAMETERS
[Forms]![frmVote]![txtnumvotes] Short,
[Forms]![frmVote]![combacts] Long,
[Forms]![frmVote]![combrndnum] Long;
UPDATE
Votes
SET
Votes.NumVotes = [Votes]![NumVotes]+[Forms]![frmVote]![txtnumvotes]
WHERE
(((Votes.ActID) = [Forms]![frmVote]![combacts])
AND
((Votes.RoundNum) = [Forms]![frmVote]![combrndnum]))
Without the specification, Access has to guess, and that sometimes fails.

Using linQ to perform a simple select where

I am using VS2013 with SQL server 2012, VB.net. I am developing a web application.
Let me say before I ask the question that this will probably be extremely simple for this board but I have not been able to find this through googling.
I have an SQL table that holds some data, two columns (settingName (nvarchar) and settingValue (float)). I want to do the following but using LinQ.
SELECT Settingvalue
FROM Settings
WHERE settingName = 'Name1'
I have the following so far in VB.
Dim db As New GMConnectionDataContext
Dim result = From a In db.Settings
Where a.SettingName = "Name1"
Select a.SettingValue
txtEgdon.Text = result
This doesn't work as result is a double but if I add .tostring to result then the output in the text box is the full linq query not the result I am looing for.
I just need to understand this simple query so I can build on it but I just cant get it and any help offered would be great.
This is because your result is an IQueryable and not a single value(even if you expect it to be). This is also why ToString will get you the SQL that will be run against your DB.
You need to get either the First or if you are really sure this would be a single value get Single. The OrDefaults are used in the case that no value is returned so the result will be null.
A Few options:
// You expect 1 to many results and get the first
txtEgdon.Text = result.First().ToString()
// You expect 0 to many results and get the first or null in case of zero results
txtEgdon.Text = result.FirstOrDefault().ToString()
// You expect exactly 1 result and get it (you will get an exception if no results are returned)
txtEgdon.Text = result.Single().ToString()
// You expect exactly 0 or 1 results and get null or the result
txtEgdon.Text = result.SingleOrDefault().ToString()
I would prefer the FirstOrDefault()

SQL Update on joined tables with calculated fields

First of all, I know there are already questions and answers about it, this thread being the one that is closest to what I need:
SQL Update to the SUM of its joined values
However, I get a syntax error (operator missing) that seems to occur close to the FROM clause. However I can't see it. Does it not like the FROM itself ? I am not used to using FROM in an update statement but it seems like it's valid from the QA I just linked :|
Any idea why there would be a syntax error there ?
I am using Access 2007 SP3.
Edit:
Wow, I forgot to post the query...
UPDATE r
SET
r.tempsmoy_requete_min = tmm.moy_mob_requete
FROM
rapports AS r INNER JOIN
(SELECT
id_fichier,
Round(Sum(temps_requete_min)/3,0) As moy_mob_requete,
Round(Sum(temps_analyse_min)/3,0) As moy_mob_analyse,
Round(Sum(temps_maj_min)/3,0) As moy_mob_maj,
Round(Sum(temps_rap_min)/3,0) As moy_mob_rap,
Round(Sum(temps_ddc_min)/3,0) As moy_mob_ddc
FROM maintenances
WHERE
periode In (10,9,8) And
annee=2011
GROUP BY id_fichier) AS tmm ON rapports.id_rapport = tmm.id_fichier
WHERE
1=0
The WHERE 1=0 part is because I want to test further the subquery before running it.
Edit: This is some simpler query I am trying. I get a different error this time. It now tells me that tempsmoy_requete_min (and probably all other left operands) are not part of an aggregate function... which is the point of my query. Any idea ?
UPDATE
rapports INNER JOIN maintenances ON rapports.id_rapport = maintenances.id_fichier
SET
rapports.tempsmoy_requete_min = Round(Sum(temps_requete_min)/3,0),
rapports.tempsmoy_analyse_min = Round(Sum(temps_analyse_min)/3,0),
rapports.tempsmoy_maj_min = Round(Sum(temps_maj_min)/3,0),
rapports.tempsmoy_rap_min = Round(Sum(temps_rap_min)/3,0),
rapports.tempsmoy_ddc_min = Round(Sum(temps_ddc_min)/3,0)
WHERE
maintenances.periode In (10,9,8) And
maintenances.annee=2011 AND
1=0
I tried adapting your first query sample, and was able to make your error go away. However then I encountered a different error ('Operation must use an updateable query').
It may be possible to overcome that error, too. However, I found it easier to use a domain function instead of a join to retrieve the replacement value.
UPDATE rapports
SET tempsmoy_requete_min = Round(DSum("temps_requete_min",
"maintenances",
"periode In (10,9,8) AND annee=2011 "
& "AND id_fichier='" & id_rapport
& "'")/3, 0);
If this suggestion works for tempsmoy_requete_min with your data, you will have to extend it to the other fields you want to replace. That won't be pretty. You could make it less ugly with a saved query which you then use as the "Domain" parameter for DSum() ... that could allow you to use a simpler "Criteria" parameter.
UPDATE r
should be
UPDATE rapports
You can't reliably use an alias in the update target.