且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用JPA更新数据库中的记录的问题

更新时间:2023-02-08 16:25:49

我遇到了同样的问题,因为我创建了一个新的object:

I had the same problem, because I created a new object:

DatabaseObject obj = new DatabaseObject();
obj.setSomeValue(null);
obj.setRowId(1);
entityManager.merge(obj);

我想如果我明确设置了id号,那么如果JPA对象是新的则无关紧要,或具有所需id的现有。也许你做了同样的事情?

I thought if I explicitly set the id number that it wouldn't matter if the JPA object is new, or the existing one with the desired id. Perhaps you did the same?

正确的代码是:

DatabaseObject obj = entityManager.find(DatabaseObject.class, (long) 1);
obj.setSomeValue(null);
obj.setRowId(1);
entityManager.merge(obj);

我希望这有帮助。