使用EntityManagerFactory导致重复的主键异常 [英] use of EntityManagerFactory causing duplicate primary key exceptions

查看:217
本文介绍了使用EntityManagerFactory导致重复的主键异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿伙计们,我的目标是使用依赖于正在使用的数据库的属性创建一个EntityManager。我在所有Google搜索中都看到过类似的内容(为了解决这个问题,我的代码更基本):

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);
}

这有效,我可以成功加载Oracle或Postgres属性,我可以从中选择无论是数据库但是,我在执行INSERT语句时遇到了问题。每当INSERT完成时,我每次都会遇到重复的主键异常。任何人都可以阐明为什么会发生这种情况?谢谢
-Brad

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

推荐答案

容器管理环境,你可以直接注入 EntityManager

In a container-managed environment, you can directly inject an EntityManager:


要获取EntityManager实例,请将实体管理器注入应用程序组件:

To obtain an EntityManager instance, inject the entity manager into the application component:

@PersistenceContext
EntityManager em;


如果你需要处理不同的持久性单元(以及几个 EntityManager instances),在 persistence.xml 并按名称注入正确的 EntityManager

If you need to deal with different persistence units (and thus several EntityManager instances), declare them in the persistence.xml and get the right EntityManager injected by its name:

@PersistenceContext(unitName = "MyFirstPU")
EntityManager em;

更新:根据指定数据库(并且还提到了这个博客文章),EclipseLink可能能够自动检测数据库平台和 eclipselink.target-database 是可选的:

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 you are using the default persistence provider, the provider attempts to automatically detect the database type based on the connection metadata.

如果这适用于Oracle和PostgreSQL(我的理解是它应该),客户只需要设置一个数据源IMO是理想情况。

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.

这篇关于使用EntityManagerFactory导致重复的主键异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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