简体   繁体   中英

Problem with uploading database in hibernate

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();    

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 (ie EntityManager ) rather than then native Hibernate API (ie 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM