2

I'm trying to learn how to do CRUD operations, but I can't seem to figure out how to update an existing row in my DB. I've gotten the create and delete part working, but I don't really know how to solve the update part. I've googled a lot about it, but I can't find a explanation that I fully understand.

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class Modell {

    @PersistenceContext(unitName = "mess")
    private EntityManager em;
    private EntityTransaction tx;

    public void addMessage(String message) {
        EntityDB me = new EntityDB();
        me.setMessage(message);
        em.persist(me);
    }


    public void delete(EntityDB entityDB) {
        em.remove(em.merge(entityDB));

    }

    public void edited(EntityDB entityDB) {
        EntityDB me = new EntityDB();
        //tx.begin();
        em.persist(me);
      // EntityDB me = new EntityDB();
        me.setMessage("edited");
        em.merge(entityDB);
        //tx.commit();

    }

    public List<EntityDB> findAll() {
        Query namedQuery = em.createNamedQuery("findAllMessageEntities");
        return namedQuery.getResultList();
    }
}

Can someone point me in the right direction on this one. As of now the the edit method only adds another row.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user2261654
  • 23
  • 1
  • 4

1 Answers1

4

If you have to update entity, then you have to apply changes on the existing one in the database, rather than creating a new instance.

public void edited(EntityDB entityDB) {       

  EntityDB me = em.find(EntityDB.class, pk); //-- Else create query
  me.setMessage("edited");
  em.merge(me);
}
Nayan Wadekar
  • 11,444
  • 4
  • 50
  • 73
  • Incidentally, no need for the `merge()` call; the `find()` call places the found entity in the persistence context already. – Laird Nelson Jun 17 '14 at 17:34