doubt with Querys - BDOO

1

I have the following code:

In the entity Article I have the following @NamedQuery

@NamedQuery(name="Article.aumentapreu",

            query="UPDATE Article a SET a.preu=a.preu*:quantitat")

And in manager class article:

/**
 * Incrementa el preu de tots els articles de la base de dades en un percentatge determinat    
 * @param percentantge tant per cent (%) d'increment 
 */
public void incrementarPreu(float percentantge){
    //TODO completar el metode
    Query ap = em.createNamedQuery("Article.aumentapreu");
    ap.setParameter("quantitat", percentantge);
    em.getTransaction().begin();
    ap.executeUpdate();
    em.getTransaction().commit();
}

The problem I have is that it gives me an error because it tells me that the query only supports input parameters between the WHERE or HAVING clauses.

Any idea how to solve it?

    
asked by Montse Mkd 20.03.2018 в 17:54
source

1 answer

1

Assuming you use a version greater than or equal to JPA 2.1, according to documentation your @NamedQuery should be valid.

  

Input parameters can only be used in the WHERE clause or HAVING clause   of a query or as the new value for an update item in the SET clause of   an update statement.

or in Spanish:

  

The input parameters can only be used in a WHERE clause   or HAVING of a query or as the new value of an item of   update in the SET clause of a update

statement

However, you might use an implementation that does not follow the specification correctly.

For example, eclipseLink has the following bug reported.

If you use JPA 2.0 instead, you can not use these parameters in the SET clause:

  

Input parameters can only be used in the WHERE clause or HAVING clause of a query.

What to do if you can not use a newer version?

Some options:

1.- You can obtain all the entities that you need to update, establish their new values and persist them by hand:

List<Article> articles = em.createQuery('SELECT a FROM Article a')
    .getResultList(); 
for (Article a : articles) {
    a.setPreu(a.getPreu() * percentantge);
    em.merge(a);
}

2.- You can build the sentence by concatenating the parameter by hand:

String query = new StringBuilder("UPDATE Article a SET a.preu = a.preu * ")
    .append(percentantge)
    .build();
em.createQuery(query).executeUpdate();
    
answered by 20.03.2018 / 19:51
source