update row in DB

非 Y 不嫁゛ 提交于 2019-12-07 21:10:56

问题


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.


回答1:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!