0

I have a project in JavaEE, my task is to affect a professor to a form( a student placement form), I have an attribute called 'nb_sup' which is the number of student supervised by a selected professor, this number is incremented by one each time a professor is affected to a student. The problem is that my function sets the 'nub_sup' to one no matter how many times I affect the same professor.

Here is my code

public  void SetNbSupPrfessor(Professor prof) 
    {
        Query query = em.createQuery("update Professor u set nb_sup=:nb_sup WHERE u.id =:id");
        query.setParameter("nb_sup", (1+ prof.getNb_sup()));
        query.setParameter("id",prof.getId() );
        query.executeUpdate(); 
    }

It's safe to say that the professor inherits from the entity 'User' ,the 'nb_sup' is of type int and the 'id' is auto-increment.

I edited my code so this one worked

        Professor prof = em.createQuery("select p from Professor p where p.id = :id",Professor.class)
                .setParameter("id",id)
                .getSingleResult();
        prof.setNb_sup(prof.getNb_sup()+1);
        em.merge(prof);
  • 1
    Apart from `set nb_sup=nb_sup+1` - doing it all in SQL, I think the Professor is not loaded with nb_sup. – Joop Eggen Apr 05 '19 at 14:17
  • You should just debug and check which value is returned by `getNb_sup`. – LppEdd Apr 05 '19 at 14:19
  • Yes, the problem was that all the other attributes where set to null so that's what made th problem. I also edited my function to [ Professor prof = em.createQuery("select p from Professor p where p.id = :id",Professor.class) .setParameter("id",id) .getSingleResult(); prof.setNb_sup(prof.getNb_sup()+1); em.merge(prof); }] – BRIGUI Malek Apr 05 '19 at 15:07

0 Answers0