Code Bug Fix: How to update in hibernate?

Original Source Link

When I entered a new data for a registration id CL123 where the registration id is a priamary key and I called the following method it would entered successfully into the database with a Status as ‘FRESH’. If I want to update this particular registration id by calling the same method also it would work fine but now I want to update it with a Status as “DUPLICATE”. How to do? Please help me..

public Integer savecertificate(Certification certification) {
     Session session = sessionFactory.openSession();
     session.beginTransaction();
     certification.setRegID("CL123");
     certification.setClass("M.Sc");
     certification.setStatus("FRESH");

     //certification.setStatus("DUPLICATE");

     session.saveOrUpdate(certification);
     session.getTransaction().commit();
    }

You need to create another method for update like below.

public Integer updateCertificate(Certification certification) {
     Session session = sessionFactory.openSession();
     session.beginTransaction();
     certification.setRegID("CL123");
     //certification.setStatus("FRESH");

     certification.setStatus("DUPLICATE");

     session.saveOrUpdate(certification);
     session.getTransaction().commit();
    }

FYI… Hibernate will check the Database with the same id(primary key) if that exist then it will update or it create a new record in the database.

Visit this StackOverFlow Link

I have found a solution to my problem. Here it is

    public Integer savecertificate(Student info) {
         Session session = sessionFactory.openSession();
         session.beginTransaction();

         String hql = "Select status from Student where regid='CL123'";
         SQLQuery query = session.createSQLQuery(hql);
         query.setParameter("info", info);
         List<String> status=query.list();

         certification.setRegID("CL123");
         certification.setClass("M.Sc");
         if(status.isEmpty){
            certification.setStatus("FRESH");
         }
         else{
            certification.setStatus("DUPLICATE");
         }

         session.saveOrUpdate(certification);
         session.getTransaction().commit();
    }

It works perfectly

Tagged : / / /

Leave a Reply

Your email address will not be published. Required fields are marked *