上下文:
在数据库中持久化某些数据的必要性
- ORM : hibernate's JPA (JPA 2.1, Hibernate 5.2.1 used throught an org.hibernate.core plugin as constructed [here (page 8)][1]
- database : in mysql
- constraint : Java SE environment, so the only way to obtain an EntityManager (for the persistence operations) is to create it through an EntityManagerFactory 第一步(工作!) :
管理数据库操作的插件,其结构:
com.plugin.name
JRE System Library
Plug-in Dependencies
Referenced Libraries (contains the mysql connector jar)
src/
com.plugin.name (package containing the plugin activator)
com.plugin.name.entities (package containing all my entities)
com.plugin.name.utils (package containing my access functions and a main)
META-INF/
persistence.xml
META-INF/
MANIFEST.MF在com.plugin.name.utils中,我的类执行所有持久性函数。
在这些类中,我以这种方式创建一个EntityManagerFactory:
private static final EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence.createEntityManagerFactory("com.plugin.name");其中"com.plugin.name“是在我的persistence.xml中定义的持久性单元名。
在其中一个类中,我有一个主要运行一些与数据库相关的函数。
当我以java应用程序的形式运行这个main时,一切都很好.
(为了防止将来出现问题:我的persistence.xml文件最初是在MANIFEST.MF META文件夹中生成的,但在运行这个主目录时却找不到它,所以我移动了它。当从另一个插件调用持久性函数时,我检查了这两种配置)
问题:
我需要从另一个插件访问我的持久性函数,我们叫他com.plugin.other
因此,我添加了com.plugin.name作为这个插件的依赖项。但是,当我试图运行应用程序时,我会得到以下错误:
javax.persistence.PersistenceException:没有名为com.plugin.name的EntityManager的持久性提供程序 在javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61) 在javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
当我作为独立应用程序运行主程序时,如果persistence.xml文件有任何问题(未找到、不完整等),则至少会提到.在这里,我实在不知道这个问题是从哪里来的。
发布于 2016-08-09 15:06:15
最后,我使用了createContainerEntityManagerFactory(PersistenceUnitInfo info,map)方法在PersistenceProvider中实现了它,而没有使用persistence.xml。
代码:
Activator a = Activator.getDefault();
Bundle b = a.getBundle();
URL url = b.getResource("META-INF/persistence.xml");
List<PersistenceProvider> providers = PersistenceProviderResolverHolder.getPersistenceProviderResolver().getPersistenceProviders();
for (PersistenceProvider pp : providers) {
PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl();
pui.setPersistenceUnitName("persistenceUnitName");
pui.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);
pui.setPersistenceUnitRootUrl(url);
Properties prop = pui.getProperties();
if (prop == null) {
prop = new Properties();
}
prop.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://ip:port/dbName");
prop.setProperty("javax.persistence.jdbc.user", "dbUser");
prop.setProperty("javax.persistence.jdbc.password", "dbPass");
prop.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
pui.setProperties(prop);
pui.setClassLoader(com.mysql.jdbc.Driver.class.getClassLoader());
emFactory = pp.createContainerEntityManagerFactory(pui, null);
}
}https://stackoverflow.com/questions/38663471
复制相似问题