I am using Hibernate and want to query multiple entities using a composite index (a,b,c,d). The SQL statement could look like this:
SELECT *
FROM my_table
WHERE a = 2 AND b = '2001' AND c = 'xx' AND d = 23
OR a = 2 AND b = '2002' AND c = 'xx' AND d = 23
-- OR ...
;
Is there a chance to pass hibernate just a list for such a query? What I don't want is to use a StringBuffer to concatenate a statement depending on the length of my list.
Criterai it´s the best for this tutorial
I hope help you
Related
I'm using MySQL and fetching a few different values from a table and then perform some basic math on it. Currently three seperate SELECT statements are in use and afterwards I perform some simple addition and subtraction with the outputs I get in Java.
I'm trying to optimize my code but sadly I gotta admit I'm a complete SQL noob. I'm pretty sure there's a way to join these select querys and the calculations so that I actually only get one output but I've not been able to find it.
My table looks something like this:
ID | value | inc | timestamp
--------------------------------------
0 | 5 | 4 | 2018-02-01 10:28:21
1 | 8 | 3 | 2018-02-01 10:28:47
...
My code currently looks like this:
int maxValue = MySQL.executeQuery("SELECT MAX(`value`) AS value FROM `table` where ID = idvalue AND `timestamp` >= TIMESTAMPADD(DAY,-3,NOW())");
int minValue = MySQL.executeQuery("SELECT MIN(`value`) AS value FROM `table` where ID = idvalue AND `timestamp` >= TIMESTAMPADD(DAY,-3,NOW())");
int minInc = MySQL.executeQuery("SELECT `inc` FROM `table` where ID = id AND value = minValue");
int output = maxValue - minValue + minInc;
Is there a way to shorten it to a single
int output = MYSQL.executeQuery( ??? );
?
Simply do select (select ...) - (select ...) + (select ...)
In your case, you can do( not tested in real environment )
select (SELECT MAX(`value`) AS value FROM `table` where ID = idvalue AND `timestamp` >= TIMESTAMPADD(DAY,-3,NOW())) - ( SELECT MIN(`value`) AS value FROM `table` where ID = idvalue AND `timestamp` >= TIMESTAMPADD(DAY,-3,NOW())) + (SELECT `inc` FROM `table` where ID = id AND value = minValue)
First off, there's something funky going on with the maxValue and minValue selects. The Max() and Min() operators will give you the max and min values of a given column of a given set of rows. Using one of these operators with such a specific where (by what seems to be a table's primary key) is probably not what you want to be doing.
Now, answering your question, I think you could do something along the lines of:
SELECT MAX('value') as max, MIN('value') as min
FROM `table` as t
WHERE ...
to "join" (careful with this word) the first 2 queries. This is simple select syntax: usually, there's no problem with selecting more than a column or an aggregate function at a time. Or, something like:
SELECT `inc`
FROM `table`
WHERE ID = id AND
value = (SELECT MIN('value') FROM 'table' WHERE ...)
to "join" the last two.
Single statement is possible using INNER JOIN since you are using a single able. Try this
SELECT MAX(`a.value`)-(MIN(`a.value`)+b.`inc`) AS Output
FROM `table` a
INNER JOIN `table` b ON a.ID=b.ID
AND a.ID = idvalue AND `a.timestamp` >= TIMESTAMPADD(a.DAY,-3,NOW())
AND b.value=(select MIN(value) from table WHERE ID=id);
Can you please share me code snippet to be written via JPA in order to generate the below sql query
SELECT COUNT(*) FROM Customer c
WHERE c.countryId ='Canada' AND
c.lanuguage ='ENG' AND
ROW_NUM <=10;
Because I tried in the below way. But MaxResults is not getting applied it seems as I can able to recieve the count more than 10.
Query query = em.createQuery("SELECT COUNT(c) FROM Customer c where c.countryId ='Canada' and c.lanuguage ='ENG'");
query.setMaxResults(10);
long customerCount = (Long)query.getSingleResult();
Select on count will always return a single value. If you want to have a count lower than 10, add HAVING.
SELECT COUNT(c) AS
FROM Customer c
WHERE c.countryId='Canada' and c.language='END'
HAVING COUNT(c)<=10
I have an entity named Item in which i have declared a property
#Column(name="ITEM_CODE", unique = true, length=30)
private String itemCode
while inserting a new item in the corresponding table i am trying to generate a unique code by prefixing it PRO- and then concatenating a random number generated by using Random class.
I am also trying to get the last item id inserted in the database and add 1 with the id and then add it to the product code as suffix.
My code to fulfill my purpose is
public String generateItemCode() {
String query = "SELECT max(i.id) FROM ITEM i";
List list = sessionFactory.getCurrentSession().createQuery(query).list();
int nextInsertId = ((Integer) list.get(0)).intValue() + 1;
Random random = new Random();
int number = random.nextInt(9999 - 1 + 1) + 1;
return "" + number+nextInsertId;
}
I have also tried by using this line of code in the method body.
int maxId= (Integer)sessionFactory.getCurrentSession().createQuery("select max(id) from items").uniqueResult();
the above code is not working.
How can i get the last inserted id. Is there any simpler way to do it?
Thanks in advance.
It appears your issue may likely be because of your query syntax mimicing that of native SQL when in reality you aren't asking Hibernate to execute a native query but instead a HQL/JPQL query.
If we assume your entity is named Item with an identifier property named id, you would use:
SELECT max(i.id) FROM Item i
You'll notice I use the property name id and the entity name Item (case is important here).
To put the pieces together, the following should work:
// be sure to check for null lastId in case you have no items.
final String sql = "SELECT max( i.id ) FROM Item i";
Integer lastId = (Integer) session.createQuery( sql ).uniqueResult();
I'm trying to call the query:
UPDATE questions
SET 1 = 4
WHERE questionid = 4;
But I keep receiving an SQL syntax error. I have a column in my table called '1', and I want to set that columns value to the integer 4. I tried some other queries(below), but I still the same error.
UPDATE questions
SET '1' = 4
WHERE questionid = 4;
UPDATE questions
SET '1' = 4
WHERE 'questionid' = 4;
UPDATE questions
SET "1" = 4
WHERE questionid = 4;
UPDATE questions
SET "1" = 4
WHERE "questionid" = 4;
I'm trying to perform this query in java using the executeUpdate() method from the Statement java API.
I know some of you would advise me using a PerformedStatement rather than a regular Statement for building queries, and I will do, once I can figure out why my query isn't accepting that 1 is a column name and not an integer.
Use backticks arround the column name:
UPDATE questions
SET `1` = 4
WHERE questionid = 4;
Think about renaming your column.
Try the following:
UPDATE questions
SET [1] = 2 -- int
WHERE QuestionID = 1;
For optimization purpose, I want to fetch first N results in a subquery (I'm getting first N ID values) and in the main query fetch full rows for the ID values in the subquery and order them. What I have now is
// This just adds params to the subquery
Expression managedEmp = generateExpression(p_upravljackaFilter);
ReportQuery subQuery = new ReportQuery(CustomDocument.class,
managedEmp);
subQuery.addAttribute("m_id");
Expression exp = new ExpressionBuilder().get("m_id").in(subQuery);
ReadAllQuery testQuery = new ReadAllQuery(CustomDocument.class,
exp);
testQuery.addAscendingOrdering("m_creationDate");
List documentList = (List)getTopLinkTemplate().executeQuery(testQuery, true);
What I'm trying so far is using a user defined function, like this:
ExpressionOperator fetchFirst = new ExpressionOperator();
fetchFirst.setSelector(1);
Vector s = new Vector();
s.addElement("FETCH FIRST 5 ROWS ONLY");
fetchFirst.printsAs(s);
fetchFirst.bePostfix();
fetchFirst.setNodeClass(FunctionExpression.class);
ExpressionOperator.initializeOperators();
ExpressionOperator.addOperator(fetchFirst);
expression = expression.and(builder.get("m_datumKreiranja").getFunction(fetchFirst);
This is literally where I stopped so this won't work but it can show you which way I'm heading. Is something like this even possible? I'm using Java 1.4 and toplink 10g.
Really simple, just insert into second line:
managedEmp = managedEmp.postfixSQL("FETCH FIRST 5 ROWS ONLY");
My mistake was in the fact that I tried it like this:
managedEmp.postfixSQL("FETCH FIRST 5 ROWS ONLY");
because I didn't read what postfixSQL does.