更新数据库中的行 [英] update row in DB
问题描述
我正在尝试学习如何进行CRUD操作,但似乎无法弄清楚如何更新数据库中的现有行.我已经使创建和删除部分工作了,但是我真的不知道如何解决更新部分.我已经在Google上搜索了很多,但是找不到我完全理解的解释.
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();
}
}
有人可以在这个问题上指出我正确的方向吗?到目前为止,edit方法仅添加另一行.
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);
}
这篇关于更新数据库中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!