0

This code for database update works fine when it is running in JDBC but when I try to run in hibernate I get this error: Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Positional parameter does not exist: 5 in query: UPDATE uposlenik SET ime=?,prezime=?,adresa=?,plata=? WHERE id= ?

I tried to change queries in many ways, but every time I get some error, and if I don't get error it won't update

session = Sesija.kreirajSesiju();
    Transaction tr = session.beginTransaction();
    SQLQuery query=session.createSQLQuery ("UPDATE uposlenik SET ime=?,prezime=?,adresa=?,plata=? WHERE id= ?");
        query.setString(1, jText_Ime.getText());
        query.setString(2, jText_Prezime.getText());
        query.setString(3, jText_Adresa.getText()); 
        query.setString(4, jText_Plata.getText()); 
        query.setString(5, jText_id.getText());


     query.executeUpdate();
     tr.commit();
  // 
     session.close();    
1
  • Looks like positional parameter indexes for hibernate native queries are 0 based, not 1 based. Commented Oct 27, 2019 at 18:32

1 Answer 1

1

The parameter position is the zero-based which mean you have to start the parameter position from zero :

SQLQuery query=session.createSQLQuery ("UPDATE uposlenik SET ime=?,prezime=?,adresa=?,plata=? WHERE id= ?");
        query.setString(0, jText_Ime.getText());
        query.setString(1, jText_Prezime.getText());
        query.setString(2, jText_Adresa.getText()); 
        query.setString(3, jText_Plata.getText()); 
        query.setString(4, jText_id.getText());

BTW , the best practise for updating record in Hibernate is to get the object instance that you want to update and then update the object state by callings its method rather than written UPDATE SQL manually. Also consider to use the JPA API (i.e. EntityManager) rather than then native Hibernate API (i.e. Session) .Only unwrap the EntityManager to Session to use Hibernate specific feature if something cannot be done with JPA. In short, the best practise codes should look like:

 EntityTransaction tr = entityManager.getTransaction();
 tr.begin();

 Uposlenik uposlenik = entityManager.find(Uposlenik.class, 1);
 if(uposlenik == null){
    throw new RuntimeException("The record does not exist");
    tr.rollback();
 }
 uposlenik.updatePrice(123);
 ......

 tr.commit();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.