-4

how can i update a single record in jpa using jpql // Person p = em.find(Person.class, 1); // p.setState_Of_Origin("Plateau"); // em.merge(p); for the above you have to know the user id, which doesn't help much. I used the following methods below

Person update(EntityManager em,String setPerson,String getPerson)
{ 
  TypedQuery<Person> m = em.createQuery("update Person b set b.State_Of_Origin =setPerson  
  where b.Firstname = ?1 ", Person.class);
  m.setParameter(1, getPerson);
}  

void Update(EntityManager em, String name)
{
     TypedQuery<Person> m = em.createQuery("update Person p set p.State_Of_Origin = 'Plateau' where p.Firstname = ?1 ", Person.class);
    int executeUpdate = m.setParameter(1,name).executeUpdate();
     System.out.println(executeUpdate); 
 }
Nasiru Aboki
  • 67
  • 2
  • 6

1 Answers1

2

I checked topics that had to do with updating a single record using jpa and none satisfied me on this website, but I'm grateful for the ideas though. Here is some piece of code to help another java enthusiast. It works!!!!!

//I'm using objectdb, so it allows u to use ur explicit object path instead of persistent unit name

EntityManagerFactory emf = Persistence.createEntityManagerFactory("$objectdb/db/directory.odb");
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
     String queryupdate = "UPDATE Person SET State_Of_Origin=?1 WHERE Firstname=?2"; 
    int executeUpdate= em.createQuery(queryupdate).setParameter(1, "Nasarawa").setParameter(2, "fajemi").executeUpdate();
    System.out.println("executed "+executeUpdate+" item"); 
    em.getTransaction().commit();
    em.close();
    emf.close();
Nasiru Aboki
  • 67
  • 2
  • 6