NamedQueries in JPA - java

From what I know, UPDATE and DELETE can be done by NamedQueries.
However,
void updateName (int ID, String name) {
EntityManager entityManager =
Persistence.createEntityManagerFactory("uPU").createEntityManager();
Query query = entityManager.createNamedQuery("Users.updateName");
query.setParameter("name", name);
query.setParameter("id", ID);
}
isn't doing the update.
The named query is as follows:
#NamedQuery(name = "Users.updateName", query = "UPDATE Users u SET u.name = :name "
+ "WHERE u.id = :id "),
A similar thing going on with DELETE.
Nothing wrong with SELECT on Namedqueries.
Is there something more to altering the contents of an SQL table with NamedQueries?
//================================
ADD:
i'm using a namedquery.
From what I know, opening the transaction and commiting it is not necessary on namedQueries.
query.executeUpdate();
gives a runtime error.
//================================
ADD2:
The code is giving no compile or runtime errors except to that addition suggested by DataNucleus below. see my previous edition above regarding that suggestion.

Thought about actually executing the query? All you've done there is create it.
query.executeUpdate()
http://www.datanucleus.org/products/accessplatform/jpa/jpql.html#JPQL_UPDATE_Queries

Related

Different result running same query on same db(postgresql) with jpa and direct query

i think the title sums it up, i tried to run same query on both pgadmin and java springboot.
here is my query annotation on springboot
#Query(value = "SELECT column1, column FROM public.v_example where start_date = ?1 and end_date = ?2", nativeQuery = true)
public List<Object[]> getExample();
i was calling from database views but it had no problem when i run the query directly on the database using pgadmin, when i tried it on java, it called nothing.
i was putting it inside a List<Object[]>.
Before, i was using a different query that works on both platform, the query was without where condition. Putting it on the same List<Object[]>.
I'm surprised the repository method doesn't cause an exception.
In the query you are referencing 2 parameters, but in the repository you are providing none, by having a method without arguments.
#Query(value = "SELECT column1, column FROM public.v_example where start_date = ?1 and end_date = ?2", nativeQuery = true)
public List<Object[]> getExample(param1, param2);
In the repo call you missed the arguments.

How can I correctly implement an Hibernate SQL query starting from an SQL query that count the number of rows?

I am absolutly new in Hibernate and I have the following problem.
I have this standard SQL query:
SELECT count(*)
FROM TID003_ANAGEDIFICIO anagraficaEdificio
INNER JOIN TID002_CANDIDATURA candidatura
ON (candidatura.PRG_PAR = anagraficaEdificio.PRG_PAR AND candidatura.PRG_CAN = anagraficaEdificio.PRG_CAN)
INNER JOIN TID001_ANAGPARTECIPA anagPartecipa ON(anagPartecipa.PRG_PAR = candidatura.PRG_PAR)
INNER JOIN anagrafiche.TPG1029_PROVNUOIST provNuovIst ON (provNuovIst.COD_PRV_NIS = anagPartecipa.COD_PRV_NIS)
WHERE anagraficaEdificio.FLG_GRA = 1 AND provNuovIst.COD_REG = "SI";
This works fine and return an integer number.
The important thing to know is that in this query the only
parameter that can change (inserted by the user in the frontend of a webappplication) is the last one (this one: provNuovIst.COD_REG = "SI").
So, the application on which I am working use Hibernate and the requirement say that I have to implement this query using Hibernate Native SQL, I have found this tutorial:
http://www.tutorialspoint.com/hibernate/hibernate_native_sql.htm
that show this example:
String sql = "SELECT * FROM EMPLOYEE WHERE id = :employee_id";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Employee.class);
query.setParameter("employee_id", 10);
List results = query.list();
that, from what I have understand (correct me if I am doing wrong assertion), involves the use of an Employee model class. So th prvious query first define the query (using the :param_name syntax for the parameter), then create an SQLQuery Hibernate object, add the class used for the result, set the previous parameter neam and finally obtain a List (that I think Hibernate create as something like an ArrayList) with the retrieved object.
My problem is that I simply I have to obtain an integer value (because I have a SELECT count(*), so I will obtain an integer value and not a set of rows).
So how can I correctly use the Hibernate Native SQL to implement my SQL query into my Hibernate repository class?
Use SQLQuery.uniqueResult to retrieve a single value from the query:
String sql = "SELECT count(*) ...";
SQLQuery query = session.createSQLQuery(sql);
// set parameters...
int count = ((Number)query.uniqueResult()).intValue();

Creating inner query in hibernate

how to add a set parameter() metheod inside the inner query in hibernate?
I have try to do like this but already have a errors
this is my code
Query query=session.createQuery("select eq.euipmentName,eq.type from Euipment eq where eq.id in(select euipment from Quotation qt where qt. supQuotation=:ids)");
query.setParameter("ids",id);
list = (List<Euipment>)query.list();
I've done some corrections about your query:
1. qt. supQuotation has a space, I've removed
2. euipment in you sub query haven't alias, I add qt
String hql =
"select eq.euipmentName,eq.type " +
" from Euipment eq " +
" where eq.id in (select qt.euipment from Quotation qt where qt.supQuotation = :ids)";
Query query = session.createQuery(hql);
query.setParameter("ids",id);
list = (List<Euipment>)query.list();
Tell me, if it's OK
If not OK, please post here the error, and check if you have put in hibernate mappping file your classes
From Hibernate Documentation:
Execution of native SQL queries is controlled via the SQLQuery
interface, which is obtained by calling Session.createSQLQuery().
createQuery() creates Query object using the HQL syntax.
createSQLQuery() creates Query object using the native SQL syntax.
So replace createQuery with createSQLQuery for native SQL query.
Try with Criteria
Criteria c = getSession().createCriteria(Euipment.class, "e");
c.createAlias("e.quotation", "q"); // inner join by default
c.add(Restrictions.eq("q.supQuotation", id));
list = (List<Euipment>)c.list();

Kundera for Cassandra - Deleting record by row key

I'm trying to delete specific record from database by row key. But when I try to execute this query:
Query query = em.createQuery(
"DELETE FROM User u WHERE u.userId = :u");
query.setParameter("u", userID).executeUpdate();
I got this exception: "Condition = is not suported for query on row key!".
Is there any workaround, or I missing something?
What you can do as a workaround is:
Find using:
User u = em.find(User.class, userId)
and then,
em.delete(u);
Also,
http://groups.google.com/group/kundera-discuss/subscribe
can give you quick and better support to discuss issues around Kundera.
-Vivek
A possible approach to perform such a delete (in one command using Kundera, version 2.2 at the moment) is to use "native query", for example:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("cassandra_pu");
EntityManager em = emf.createEntityManager();
// "table" is the table name (case sensitive) you name your table in Cassandra
String query = "delete from table where key = 'keyValue'";
// "TablePersistencyEntity" is the Kundera Persistency Entity (Class) for the "table"
Query q = em.createNativeQuery(query, TablePersistencyEntity.class);
q.getResultList();
em.close();

JPQL where in array query

I'm trying to update every record for which I have the id in my arraylist but I'm getting this error:
IllegalStateException occured : org.hibernate.hql.QueryExecutionRequestException: Not supported for DML operations [update models.UserOnline uo SET currentRoom_id = :roomid where uo.id IN (:list)]
This is what I'm trying:
Query update_query = JPA.em().createQuery("update UserOnline uo SET currentRoom_id = :roomid where uo.id IN (:list)");
update_query.setParameter("roomid", null);
update_query.setParameter("list", idlist);
List<UserOnline> actual = update_query.getResultList();
Any ideas what's wrong?
I would try with update_query.executeUpdate();
From the docs.
Like Gonzalo already said, you'd have to use executeUpdate().
This is because you're actually MODIFYing data .
You only use getResultList() or getSingleResult() if you want to GET data out of the database.
a little helper:
use executeUpdate() if your query has the form
UPDATE ... SET .. WHERE ..
or
DELETE ... WHERE ...
use getResultList() or getSingleResult() if the query looks like
SELECT ... FROM xxx WHERE ...
or just
FROM xxx WHERE ...
Well, if we use Spring Repositories (CrudRepository or any of its type), and if we have a method declaration with an update Query
That is,
#Query("update employee e set e.name= :name where e.id = :id")
int updateEmployee(#Param("name") String name, #Param("id") Long id);
Then we will get the related Spring Exception org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations
Just add #Modifying annotation on the method and it will be fine.

Categories

Resources