大家好,我的目标是使用依赖于正在使用的数据库的属性创建一个 EntityManager。我在所有 Google 搜索中都看到过类似的操作(为了解决这个问题,我使代码变得更加基本):
@PersistenceUnit
private EntityManagerFactory emf;
private EntityManager em;
private Properties props;
@PostConstruct
public void createEntityManager(){
//if oracle set oracle properties else set postgres properties
emf = Persistence.createEntityManagerFactory("app-x");
em = emf.createEntityManager(props);
}
这有效,我可以成功加载 Oracle 或 Postgres 属性,并且可以从任一数据库中进行选择。然而,我在执行 INSERT 语句时遇到了问题。每当插入完成时,我都会收到重复的主键异常..每次!谁能解释一下为什么会发生这种情况?谢谢
-布拉德
Hey guys, my goal is create an EntityManager using properties dependent on which database is in use. I've seen something like this done in all my Google searches(I made the code more basic for the purpose of this question):
@PersistenceUnit
private EntityManagerFactory emf;
private EntityManager em;
private Properties props;
@PostConstruct
public void createEntityManager(){
//if oracle set oracle properties else set postgres properties
emf = Persistence.createEntityManagerFactory("app-x");
em = emf.createEntityManager(props);
}
This works and I can load Oracle or Postgres properties successfully and I can Select from either database. HOWEVER, I am running into issues when doing INSERT statements. Whenever an INSERT is done I get a duplicate primary key exception.. every time! Can anyone shed some light on why this may be happening? Thanks
-Brad
发布评论
评论(2)
在容器管理环境中,您可以直接注入
EntityManager
:如果需要处理不同的 持久性单元(以及几个
EntityManager
实例),在persistence.xml
并注入正确的EntityManager
按其名称:更新:根据指定数据库(还提到了博客文章),EclipseLink 可能能够自动检测数据库平台,并且
eclipselink.target-database
是可选的:如果这适用于 Oracle 和 PostgreSQL(我的理解是它应该),客户只需设置一个数据源,这在我看来是理想的场景。
In a container-managed environment, you can directly inject an
EntityManager
:If you need to deal with different persistence units (and thus several
EntityManager
instances), declare them in thepersistence.xml
and get the rightEntityManager
injected by its name:Update: According to Specifying the Database (and also mentioned this blog post), EclipseLink may be able to auto-detect the database platform and the
eclipselink.target-database
is optional:If this works with Oracle and PostgreSQL (and my understanding is that it should), the customer would only have to setup a datasource which is IMO the ideal scenario.
使用 < 注释您的
EntityManager
code>@PersistenceContext(unitName="app-x")因此,您不需要创建新的实体管理器和工厂 - 一切都由容器自动处理。
Annotate your
EntityManager
with@PersistenceContext(unitName="app-x")
Thus you will not need to create new entity managers and factories - everything is automatically handled by your container.