使用EntityManagerFactory导致重复的主键异常

时间:2010-03-09 00:48:47

标签: jpa java-ee eclipselink persistence-unit

嘿伙计们,我的目标是使用依赖于正在使用的数据库的属性创建一个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语句时遇到了问题。每当INSERT完成时,我每次都会遇到重复的主键异常。谁能解释为什么会发生这种情况?谢谢 -Brad

2 个答案:

答案 0 :(得分:1)

使用@PersistenceContext(unitName="app-x")

EntityManager添加注释

因此,您不需要创建新的实体管理器和工厂 - 所有内容都由容器自动处理。

答案 1 :(得分:1)

container-managed环境中,您可以直接注入EntityManager

  

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

@PersistenceContext
EntityManager em;

如果您需要处理不同的persistence units(以及几个EntityManager个实例),请在persistence.xml中声明它们,并通过其名称注入正确的EntityManager

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

更新:根据Specifying the Database(并且还提到了此blog post),EclipseLink可能能够自动检测数据库平台,eclipselink.target-database是可选的:

  

如果您使用的是默认持久性提供程序,则提供程序会尝试根据连接元数据自动检测数据库类型。

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

相关问题