JPA EntityManager:merge()试图在db中创建一个新行 - 为什么? [英] JPA EntityManager: merge() is trying to create a new row in the db - why?

查看:101
本文介绍了JPA EntityManager:merge()试图在db中创建一个新行 - 为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过Play Framework使用JPA。

I'm using JPA through the Play Framework.

我正在检查是否缓存了User对象,如果是,我将检索它并合并( )这样我可以更新字段并稍后保存更改:

I'm checking to see if a User object is cached, and if so I retrieve it and merge() it such that I can update fields and save the changes later:

user = (User) Cache.get("user-auth-" + sessionAuthToken);
if (user != null) {
    user = user.merge();  // I believe this is the same as EntityManager.merge()
}

但是当我这样做我得到以下错误:

However when I do this I get the following error:

PersistenceException occured : 
  org.hibernate.exception.ConstraintViolationException: 
    could not insert: [models.User]
...
Caused by: com.mysql.jdbc.exceptions.jdbc4.
   MySQLIntegrityConstraintViolationException: 
     Duplicate entry '1235411688335416533' for key 'authToken'

它看起来它试图插入一个新用户,即使这个用户应该是,并且已经在数据库中。为什么merge()会这样做?

It seems like its trying to insert a new user, even though this user should be, and is already in the database. Why would merge() do that?

或者我可能完全以错误的方式解决这个问题 - 建议会受到赞赏。

Or perhaps I'm going about this entirely the wrong way - advice would be appreciated.

推荐答案

我相信你的问题是Play管理JPA环境(和事务)的方式。

I believe your problem is the way Play manages the JPA environment (and transactions).

收到请求后,框架会立即创建JPA管理器和事务。从那一刻开始,所有模型实体都会自动链接到经理。

Once you receive a request the framework immediately creates the JPA manager and a transaction. From that moment onwards all your Model entities are automatically linked to the manager.

Play有助于以两种方式使用此模型:

Play facilitates working with this model in 2 ways:


  • 您必须明确指出要保存对象的更改(通过save())

  • 除非有,否则将自动提交事务一个例外,或者你将其标记为回滚(JPA.setRollbackOnly())

通过运行merge,你试图添加到管理已经存在的实体,它会导致唯一的密钥异常。如果你只是从缓存中加载实体,你就可以修改并在完成后调用save(),它会起作用。

By running "merge" you are trying to add to the Manager an entity which is already there, which causes the unique key exception. If you just load the entity from the cache, you will be able to modify and call save() once done, and it will work.

这篇关于JPA EntityManager:merge()试图在db中创建一个新行 - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆