创建新实体同时启用注入 [英] Creating new entities while enabling injection

查看:179
本文介绍了创建新实体同时启用注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于无状态会话bean的方法,它创建一个实体的新实例并持续存在。您通常可以使用新的MyEntity()来创建对象,但是我希望注入来填充实体的某些属性。

I have a method on a stateless session bean which creates a new instance of an entity and persists it. You might normally use new MyEntity() to create the object but I would like injection to populate some of the properties of the entity for me.

我使用

@Inject 
@New 
private MyEntity myNewEntity; 

在会话bean中,然后在我的方法中使用该实例。

in the session bean and then using that instance in my method.

我现在的问题是第二次调用该方法时,myNewEntity不是一个新对象,它与第一次创建的对象相同。因此我得到

The problem I have now is that the second time the method is called, myNewEntity isn't a new object, its the same object as the one created the first time. As a result I'm getting

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:键PRIMARY的重复条目'9'

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '9' for key 'PRIMARY'

或至少这就是为什么我认为我得到这个例外。当然,如果我使用新的MyEntity()我没有得到异常,但我的注射不会发生。

Or at least that's why I think I'm getting this exception. Certainly if I use new MyEntity() I don't get the exception but my injection doesn't happen.

我错误的轨道?如何在启用注入时创建新的本地实体对象?

Am I on the wrong track? How can I create a new local entity object while enabling injection?

任何帮助都会很棒!

推荐答案

首先,我非常怀疑使用CDI来控制实体的生命周期是个好主意。请参阅文档中的引用(这里):

First of all - I have serious doubts that it's a good idea to use CDI to control the lifecycle of a Entity. See this quote from the documentation (here):


根据这个定义,JPA
实体在技术上被管理
bean。然而,实体拥有
自己的特殊生命周期,状态和
身份模型,通常由JPA实例化或使用新的

因此,我们不建议直接
注入一个实体类。我们
特别建议不要将
a范围分配给@Dependent到
实体类,因为JPA不能
持续注入CDI代理。

According to this definition, JPA entities are technically managed beans. However, entities have their own special lifecycle, state and identity model and are usually instantiated by JPA or using new. Therefore we don't recommend directly injecting an entity class. We especially recommend against assigning a scope other than @Dependent to an entity class, since JPA is not able to persist injected CDI proxies.

创建新的实体实例时应该做的是添加一个间接层,或者使用 @Produces @Unwraps (Seam Solder,如果你需要它是真正的无状态的),从而确保代码显式调用新的

What you should do to create new instances of entities is adding a layer of indirection, either with @Produces or @Unwraps (Seam Solder, if you need it to be truly stateless), and thereby making sure that you code explicitly calls new.

这篇关于创建新实体同时启用注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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