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.
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);
}
来源:https://stackoverflow.com/questions/15905524/update-row-in-db