-1

My web application used hibernate mysql. I can add records to database without having any issue. But if i going to update latest adding record It will not updating. But if I re-start the server(tomcat) and then try to update It's working.

To update the record following condition should be satisfied.

//Check record aready exist
public boolean idExists(String id) {
Session session = (Session) HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();        
List<Officer>  list = (List<Officer>) session.createQuery("from Officer as p where p.idno =" + "\'" + id.trim() + "\'").list();

return (list.size() > 0) ;
}

Immediate(return 1) adding records It will returns 0. But one restart the server and update the record It will work. I also verify after adding record it's successfully commit to DB.

public class HibernateUtil {
private static final SessionFactory sessionFactory;

static{
try{
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}catch(Throwable ex){
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

Let me know if something wrong in my code?

4

3 回答 3

1

Hibernate does not interact with database immediately after transaction or it does at the time of flushing session, it manages and updates its record to increase system performance in its own way, If you want immediate reflection use :

session.flush();

After updating records.

于 2013-08-25T07:43:21.967 回答
0

You could try to flush the session. Entities are not immediately persisted into the database.

session.flush();
于 2013-08-25T07:46:47.477 回答
0

I think better you use Transactions here.

You put session.biginTranasaction();

Instead do something like,

public boolean idExists(String id) {
Session session = (Session) HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();        
List<Officer>  list = (List<Officer>) session.createQuery("from Officer as p where p.idno =" + "\'" + id.trim() + "\'").list();

tx.commit();
if(session != null){
session.close();
}
    return (list.size() > 0) ;
    }

On other end you should generate new session and do other stuffs.

于 2013-08-25T08:15:38.733 回答