Running Hibernate in an Eclipse plugin-based environment - eclipse

Lately, I have been trying to use Hibernate as O-R-Mapper for a project based on Eclipse bundles.
Because of the unique class-loading of Eclipse-bundles, many people advise using Eclipselink instead of Hibernate.
Having tried Eclipselink and being not quite satisfied with it, I do want to know:
Isn't there a way to get Hibernate up and running in my Eclipse Plug-In Project?

Here is a small walk-through of how I got it to work. Please feel free to ask questions and post suggestions on how to improve this:
Download Hibernate 4.2.5 or newer, which comes with OSGi-Support (see Hibernate OSGi Documentation). However, the examples there use Apache Felix as OSGi-implementation and not equinox.
Create a new Plug-In Project from existing jar-archives.
In my case, I added the following jars:
hibernate-core-4.2.5
hibernate-osgi-4.2.5
hibernate-commons-annotations-4.0.2 (i am using annotations)
hibernate-jpa-2.0 (i am using the java persistence api for more flexibility)
hibernate-entitymanager-4.2.5 (also the more generic jpa entitymanager instead of hibernates session)
org.osgi.core-4.3.1 (for the osgi classes)
jboss-logging
jboss-transaction-api
dom4j-1.6.1
antlr-2.7.7
Open the MANIFEST.MF of the project and add the following:
Bundle-Activator: org.hibernate.osgi.HibernateBundleActivator (this is hibernate's bundle activator from the hibernate-osgi bundle)
Bundle-ActivationPolicy: lazy (so that osgi passes the context to the bundle once it is activated)
Eclipse-BuddyPolicy: registered (we need this later to make our entity classes known to hibernate and vice versa)
Also make sure all your jars are on the Bundle-Classpath and all packages of the plug-in are exported.
Now, create a new plug-in project for your hibernate configuration and DAO.
Put your persistence configuration file (persistence.xml or hibernate.cfg.xml) in the META-INF folder at the root of your plugin. Here is an example for the persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_2_1.xsd"
version="1.0">
<persistence-unit name="TheNameOfMyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<description>My Persistence Unit</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>de.eicher.jonas.SomeClass</class>
<class>de.eicher.jonas.AnotherClass</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/>
<property name="hibernate.connection.url" value="jdbc:derby:C:/Temp/data;create=true"/>
<property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.EmbeddedDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="org.hibernate.FlushMode" value="commit" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.current_session_context_class" value="thread"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
Add org.eclipse.core.runtime to your dependencies and create an Activator to get static access to the BundleContext:
import org.eclipse.core.runtime.Plugin;
import org.osgi.framework.BundleContext;
public class HibernateJpaActivator extends Plugin {
private static BundleContext context;
#Override
public void start(BundleContext context)
throws Exception {
HibernateJpaActivator.context = context;
}
public static BundleContext getContext() {
return context;
}
}
In your DAO or Util class, use the following code to get the EntityManagerFactory or EntityManager:
BundleContext context = HibernateJpaActivator.getContext();
ServiceReference serviceReference = context.getServiceReference( PersistenceProvider.class.getName() );
PersistenceProvider persistenceProvider = (PersistenceProvider) context.getService( serviceReference );
emf = persistenceProvider.createEntityManagerFactory( "TheNameOfMyPersistenceUnit", null );
EntityManager em = emf.createEntityManager();
Only a few more things to do, before it works:
Open the MANIFEST.MF and make sure that your bundle receives the BundleContext on activation.
Bundle-ActivationPolicy: lazy
Bundle-Activator: my.package.name.HibernateJpaActivator
Open the plug-in containing your entities and add a dependecy to the plugin with your hibernate jars (the first one we created).
Now we also need the entities to be known in the plugin with the hibernate jars. We can't add a dependency there, because this would produce a cyclic dependency. Fortunately, Eclipse provides us with a workaround:
Open the MANIFEST.MF of your entity-bundle and register your hibernate-jar plugin as a buddy:
Eclipse-RegisterBuddy: org.hibernate4.osgi (the name of your hibernate plugin, the one where you set Eclipse-Buddy-Policy: registered)
Now Hibernate knows our classes and our classes know Hibernate. We also made sure, that Hibernate finds our persistence.xml (or hibernate.cfg.xml) and creates our readily configured EntityMangerFactory (or Session).

Related

JSF2 + Spring 4 + CDI + Spring Data, good match?

Let me tell you my story, and in between I will ask questions
I am working in a project I have to use JSF, there is not really other choice.
Coming from the wonderful Spring world in the last years, I really wanted to use some features like Spring Data, Spring singleton beans, Autowire beans into other beans, etc.
So I thought initially everything would be smooth, JSF (backing beans) will be managed by CDI container and #Service, #Respostory and database connection Entity manager by spring container. I want to make my application independent from a Java EE container, but just for information I am using Wildfly 9. In Wildfly, I create a datasource (connection to an oracle database) to bind later to my application.
So my first difficulty was, Some years ago, I code some JSF and I knew about #ManagedBean anotations and JSF scopes, all even though has not changed, there seems to be another aproach, and acording to what I read it is recommendable to use #Named and so on (CDI annotations) instead of the JSF annotations. So I wanted to follow those advices and somehow forces me to introduce CDI container into my application.
1st Question: Is that true ? Isn´t it recommendable to use old JSF annotations ?
My JSF beans look like this:
import java.io.Serializable;
import java.util.Locale;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.validation.constraints.NotNull;
import co.com.psl.connectnetwork.service.AuthenticationService;
import lombok.Data;
#Named
#SessionScoped
#Data
public class LoginBean implements Serializable {
}
My first issue, is that as I mentioned before, I wanted to introduce Spring, so I had in my application context xml file
<context:annotation-config />
<context:component-scan base-package="co.com.package" />
That was causing me problems because it seemed that Spring scanned my JSF managed beans , and treated them as Spring beans, which I don´t have any issue with that, but in practice those beans were singleton !!! , so terrible for an application which manages some state among logged users.
So I solved it by excluding JSF beans from spring container, I did it by introducing this:
<context:component-scan base-package="co.com.scannedpackage" >
<context:exclude-filter type="regex" expression="co.excludedpackage.*Bean" />
</context:component-scan>
So It did not seem to me so terrible , and as it seems to be some imcompatibility I though It was better that JSF beans will not be managed by Spring.
2nd Question: Do you agree?
As I said, I will have some #Service (Spring annotations) beans which I will eventually have to inject into the JSF managed beans . Initially I used #Inject to inject the service bean into the JSF bean , and it worked perfectly , the only issue is that when the JSF bean was using javax.enterprise.context.SessionScoped , it forced that all attributes are Serializable, so I made the #Service Spring bean implement the Serializable interface, which I dont think it is nice , even if it works, it seems to me a contradiction and a spring singleton bean (stateless) is forced to be serialized. So I tried to use the #Autowired anotation in the JSF managed bean , but the bean was not been injected and I got a null reference. Basically I guess the error I think it was, to use #Autowired in a bean which is not managed by spring.
3rd Question: How can I make it work ? I really think it is better to use #Autowired than to have spring beans serializable .If the ApplicationScope/viewScope/SessionScope JSF bean is passivated, will the Spring bean be injected again?, I don´t think so. If #ManagedBean is used, will it work ?
Another issue I am having, is that if my JSF beans are managed by CDI, It seems that javax.faces.bean.ViewScoped does not work well with CDI
4th Question: Is that so? Do you recommend me to use #ManagedBean instead of #Named? If I use #ManagedBean, how do I inject Spring dependencies? Is there any other CDI scope I could use instead of ViewScoped?
Now moving from JSF to Spring, I really want to use Spring in my applications, Features like Spring-Data, Spring-Security and others, the advantages of Spring singleton beans over EJB Stateless beans, are things I don´t want to miss. In my application, I will have a datasource created in the Java EE server or Java EE container. Then, I will bind that datasource internally in my application. So in my applicationContext.xml, I have:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<bean id="datasource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:/jndi-spring"/>
<property name="lookupOnStartup" value="true"/>
<property name="proxyInterface" value="javax.sql.DataSource"/>
</bean>
<!-- <jee:jndi-lookup id="datasource" jndi-name="java:/ConnectNetworkDS"/> -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasource" />
<property name="persistenceUnitName" value="persistenceUnit2" />
<property name="packagesToScan" value="co.com.packagestoscan" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
</props>
</property>
</bean>
<jpa:repositories base-package="co.com.packagewhererepositoriearelocated" />
</beans>
Please note that I am using Spring data and this line
<jpa:repositories base-package="co.com.packagewhererepositoriearelocated" />
is to indicate the interfaces annotated with #org.springframework.stereotype.Repository.Resository
Unfortunately, when I deploy my application, I get:
ERROR [org.jboss.msc.service.fail] (MSC service thread 1-1) MSC000001: Failed to start service jboss.deployment.unit."deployedwar.war".WeldStartService: org.jboss.msc.service.StartException in service jboss.deployment.unit."deployedwar.war".WeldStartService: Failed to start service
So I was doing so internet research, and I included :
persistence.xml
CdiConfig class
The content of persistence.xml is:
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="persistenceUnit">
<class>co.com.entityClass1</class>
<class>co.com.entityClass2</class>
<jta-data-source>java:/jndi-string</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider" />
</properties>
</persistence-unit>
</persistence>
And CdiConfig class:
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class CdiConfig {
#Produces
#Dependent
#PersistenceContext
private EntityManager entityManager;
}
5th Question: Can somebody please tell me why this is required ? Shouldn´t spring be able to inject the enntityManager into the #Repository Spring beans ? Why a persistence.xml is necessary ? Why does it seems that injection into #Repository Spring beans have to be done by Spring ? I think this somehow is redundant
Isn´t it recommendable to use old JSF annotations?
That's true. In JSF we're moving away from the JSF native beans and injection in favor of CDI. Although still not officially so, #ManagedBean and friends should be considered effectively deprecated.
#ViewScoped should work fine with CDI, but make sure you're importing the right one. The old one does not work, the newer one does. The one you need is:
javax.faces.view.ViewScoped
See CDI compatible #ViewScoped

javax.persistence.PersistenceException: No Persistence provider for EntityManager named DogovoraPool [duplicate]

I have my persistence.xml with the same name using TopLink under the META-INF directory.
Then, I have my code calling it with:
EntityManagerFactory emfdb = Persistence.createEntityManagerFactory("agisdb");
Yet, I got the following error message:
2009-07-21 09:22:41,018 [main] ERROR - No Persistence provider for EntityManager named agisdb
javax.persistence.PersistenceException: No Persistence provider for EntityManager named agisdb
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:89)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:60)
Here is the persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="agisdb">
<class>com.agis.livedb.domain.AddressEntity</class>
<class>com.agis.livedb.domain.TrafficCameraEntity</class>
<class>com.agis.livedb.domain.TrafficPhotoEntity</class>
<class>com.agis.livedb.domain.TrafficReportEntity</class>
<properties>
<property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/agisdb"/>
<property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="toplink.jdbc.user" value="root"/>
<property name="toplink.jdbc.password" value="password"/>
</properties>
</persistence-unit>
</persistence>
It should have been in the classpath. Yet, I got the above error.
Put the "hibernate-entitymanager.jar" in the classpath of application.
For newer versions, you should use "hibernate-core.jar" instead of the deprecated hibernate-entitymanager
If you are running through some IDE, like Eclipse: Project Properties -> Java Build Path -> Libraries.
Otherwise put it in the /lib of your application.
After <persistence-unit name="agisdb">, define the persistence provider name:
<provider>org.hibernate.ejb.HibernatePersistence</provider>
Make sure that the persistence.xml file is in the directory: <webroot>/WEB-INF/classes/META-INF
Faced the same issue and couldn't find solution for quite a long time. In my case it helped to replace
<provider>org.hibernate.ejb.HibernatePersistence</provider>
with
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
Took solution from here
I needed this in my pom.xml file:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.6.Final</version>
</dependency>
There is another point: If you face this problem within an Eclipse RCP environment, you might have to change the Factory generation from Persistence.createEntityManagerFactory to new PersistenceProvider().createEntityManagerFactory
see ECF for a detailed discussion on this.
Maybe you defined one provider like <provider>org.hibernate.ejb.HibernatePersistence</provider> but referencing another one in jar. That happened with me: my persistence.xml provider was openjpa but I was using eclipselink in my classpath.
Hope this help!
Quick advice:
check if persistence.xml is in your classpath
check if hibernate provider is in your classpath
With using JPA in standalone application (outside of JavaEE), a persistence provider needs to be specified somewhere. This can be done in two ways that I know of:
either add provider element into the persistence unit: <provider>org.hibernate.ejb.HibernatePersistence</provider> (as described in correct answere by Chris: https://stackoverflow.com/a/1285436/784594)
or provider for interface javax.persistence.spi.PersistenceProvider must be specified as a service, see here: http://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html (this is usually included when you include hibernate,or another JPA implementation, into your classpath
In my case, I found out that due to maven misconfiguration, hibernate-entitymanager jar was not included as a dependency, even if it was a transient dependency of other module.
If you are using Eclipse make sure that exclusion pattern does not remove your persistence.xml from source folders on build path.
Go to Properties -> Java Build Path -> Source tab
Check your exclusion pattern which is located atMyProject/src/main/java -> Excluded: <your_pattern>tree node
Optionally, set it to Excluded: (None) by selecting the node and clicking Edit... button on the left.
I'm some years late to the party here but I hit the same exception while trying to get Hibernate 3.5.1 working with HSQLDB and a desktop JavaFX program. I got it to work with the help of this thread and a lot of trial and error. It seems you get this error for a whole variety of problems:
No Persistence provider for EntityManager named mick
I tried building the hibernate tutorial examples but because I was using Java 10 I wasn't able to get them to build and run easily. I gave up on that, not really wanting to waste time fixing its problems. Setting up a module-info.java file (Jigsaw) is another hairball many people haven't discovered yet.
Somewhat confusing is that these (below) were the only two files I needed in my build.gradle file. The Hibernate documentation isn't clear about exactly which Jars you need to include. Entity-manager was causing confusion and is no longer required in the latest Hibernate version, and neither is javax.persistence-api. Note, I'm using Java 10 here so I had to include the jaxb-api, to get around some xml-bind errors, as well as add an entry for the java persistence module in my module-info.java file.
Build.gradle
// https://mvnrepository.com/artifact/org.hibernate/hibernate-core
compile('org.hibernate:hibernate-core:5.3.1.Final')
// https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api
compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.0'
Module-info.java
// Used for HsqlDB - add the hibernate-core jar to build.gradle too
requires java.persistence;
With hibernate 5.3.1 you don't need to specify the provider, below, in your persistence.xml file. If one is not provided the Hibernate provider is chosen by default.
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
The persistence.xml file should be located in the correct directory so:
src/main/resources/META-INF/persistence.xml
Stepping through the hibernate source code in the Intellij debugger, where it checks for a dialect, also threw the exact same exception, because of a missing dialect property in the persistence.xml file. I added this (add the correct one for your DB type):
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
I still got the same exception after this, so stepping through the debugger again in Intellij revealed the test entity I was trying to persist (simple parent-child example) had missing annotations for the OneToMany, ManyToOne relationships. I fixed this and the exception went away and my entities were persisted ok.
Here's my full final persistence.xml:
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="mick" transaction-type="RESOURCE_LOCAL">
<description>
Persistence unit for the JPA tutorial of the Hibernate Getting Started Guide
</description>
<!-- Provided in latest release of hibernate
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
-->
<class>com.micks.scenebuilderdemo.database.Parent</class>
<class>com.micks.scenebuilderdemo.database.Child</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbc.JDBCDriver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:hsqldb:file:./database/database;DB_CLOSE_DELAY=-1;MVCC=TRUE"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
</properties>
</persistence-unit>
</persistence>
I probably wasted about half a day on this gem. My advice would be to start very simple - a single test entity with one or two fields, as it seems like this exception can have many causes.
Corner case: if you are using m2Eclipse, it automatically puts in excludes on your resources folders. Then when you try to run tests inside eclipse, the subsequent absence of persistence.xml will produce this error.
Make sure you have created persistence.xml file under the 'src' folder. I created under the project folder and that was my problem.
If you're using Maven, it could be that it is not looking at the right place for the META-INF folder. Others have mentioned copying the folder, but another way that worked for me was to tell Maven where to look for it, using the <resources> tag. See: http://maven.apache.org/plugins/maven-resources-plugin/examples/resource-directory.html
It happenes when the entity manager is trying to point to many persistence units. Do the following steps:
open the related file in your editor (provided your project has been closed in your IDE)
delete all the persistence and entity manager related code
save the file
open the project in your IDE
now bind the db or table of your choice
I faced the same problem, but on EclipseLink version 2.5.0.
I solved my problem by adding yet another jar file which was necessarily (javax.persistence_2.1.0.v201304241213.jar.jar);
Jars needed:
- javax.persistence_2.1.0.v201304241213.jar
- eclipselink.jar
- jdbc.jar (depending on the database used).
I hope this helps.
I also had this error but the issue was the namespace uri in the persistence.xml.
I replaced http://xmlns.jcp.org/xml/ns/persistence to http://java.sun.com/xml/ns/persistence and the version 2.1 to 2.0.
It's now working.
You need to add the hibernate-entitymanager-x.jar in the classpath.
In Hibernate 4.x, if the jar is present, then no need to add the org.hibernate.ejb.HibernatePersistence in persistence.xml file.
In my case, previously I use idea to generate entity by database schema, and the persistence.xml is automatically generated in src/main/java/META-INF,and according to https://stackoverflow.com/a/23890419/10701129, I move it to src/main/resources/META-INF, also marked META-INF as source root. It works for me.
But just simply marking original META-INF(that is, src/main/java/META-INF) as source root, doesn't work, which confuses me.
and this is the structre:
The question has been answered already, but just wanted to post a tip that was holding me up. This exception was being thrown after previous errors. I was getting this:
property toplink.platform.class.name is deprecated, property toplink.target-database should be used instead.
Even though I had changed the persistence.xml to include the new property name:
<property name="toplink.target-database" value="oracle.toplink.platform.database.oracle.Oracle10Platform"/>
Following the message about the deprecated property name I was getting the same PersistenceException like above and a whole other string of exceptions. My tip: make sure to check the beginning of the exception sausage.
There seems to be a bug in Glassfish v2.1.1 where redeploys or undeploys and deploys are not updating the persistence.xml, which is being cached somewhere. I had to restart the server and then it worked.
In an OSGi-context, it's necessary to list your persistence units in the bundle's MANIFEST.MF, e.g.
JPA-PersistenceUnits: my-persistence-unit
Otherwise, the JPA-bundle won't know your bundle contains persistence units.
See http://wiki.eclipse.org/EclipseLink/Examples/OSGi/Developing_with_EclipseLink_OSGi_in_PDE .
You need the following jar files in the classpath:
antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.1.Final.jar
hibernate-core-4.0.1.Final.jar
hibernate-entitymanager.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
javassist-3.9.0.jar
jboss-logging-3.1.1.GA.jar
jta-1.1.jar
slf4j-api-1.5.8.jar
xxx-jdbc-driver.jar
I just copied the META-INF into src and worked!
Hibernate 5.2.5
Jar Files Required in the class path. This is within a required folder of Hibernate 5.2.5 Final release. It can be downloaded from http://hibernate.org/orm/downloads/
antlr-2.7.7
cdi-api-1.1
classmate-1.3.0
dom4j-1.6.1
el-api-2.2
geronimo-jta_1.1_spec-1.1.1
hibernate-commons-annotation-5.0.1.Final
hibernate-core-5.2.5.Final
hibernate-jpa-2.1-api-1.0.0.Final
jandex-2.0.3.Final
javassist-3.20.0-GA
javax.inject-1
jboss-interceptor-api_1.1_spec-1.0.0.Beta1
jboss-logging-3.3.0.Final
jsr250-api-1.0
Create an xml file "persistence.xml" in
YourProject/src/META-INF/persistence.xml
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="sample">
<class>org.pramod.data.object.UserDetail</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/hibernate_project"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="root"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="false"/>
<property name="hibernate.cache.use_second_level_cache" value="false"/>
<property name="hibernate.archive.autodetection" value="true"/>
</properties>
</persistence-unit>
please note down the information mentioned in the < persistance > tag and version should be 2.1.
please note the name < persistance-unit > tag, name is mentioned as "sample". This name needs to be used exactly same while loading your
EntityManagerFactor = Persistance.createEntityManagerFactory("sample");. "sample" can be changed as per your naming convention.
Now create a Entity class. with name as per my example UserDetail, in the package org.pramod.data.object
UserDetail.java
package org.pramod.data.object;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "user_detail")
public class UserDetail {
#Id
#Column(name="user_id")
private int id;
#Column(name="user_name")
private String userName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Override
public String toString() {
return "UserDetail [id=" + id + ", userName=" + userName + "]";
}
}
Now create a class with main method.
HibernateTest.java
package org.pramod.hibernate;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.pramod.data.object.UserDetail;
public class HibernateTest {
private static EntityManagerFactory entityManagerFactory;
public static void main(String[] args) {
UserDetail user = new UserDetail();
user.setId(1);
user.setUserName("Pramod Sharma");
try {
entityManagerFactory = Persistence.createEntityManagerFactory("sample");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist( user );
entityManager.getTransaction().commit();
System.out.println("successfull");
entityManager.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output will be
UserDetail [id=1, userName=Pramod Sharma]
Hibernate: drop table if exists user_details
Hibernate: create table user_details (user_id integer not null, user_name varchar(255), primary key (user_id))
Hibernate: insert into user_details (user_name, user_id) values (?, ?)
successfull
If there are different names in Persistence.createEntityManagerFactory("JPAService") in different classes than you get the error. By refactoring it is possible to get different names which was in my case. In one class the auto-generated Persistence.createEntityManagerFactory("JPAService")in private void initComponents(), ContactsTable class differed from Persistence.createEntityManagerFactory("JPAServiceExtended") in DBManager class.
Mine got resolved by adding info in persistence.xml e.g. <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> and then making sure you have the library on classpath e.g. in Maven add dependency like
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0</version>
</dependency>
Verify the peristent unit name
<persistence-unit name="com.myapp.model.jpa"
transaction-type="RESOURCE_LOCAL">
public static final String PERSISTENCE_UNIT_NAME = "com.myapp.model.jpa";
Persistence.createEntityManagerFactory(**PERSISTENCE_UNIT_NAME**);
In my case it was about mistake in two properties as below. When I changed them ‘No Persistence provider for EntityManager named’ disappered.
So you could try test connection with your properties to check if everything is correct.
<property name="javax.persistence.jdbc.url" value="...”/>
<property name="javax.persistence.jdbc.password" value="...”/>
Strange error, I was totally confused because of it.
Try also copying the persistence.xml manually to the folder <project root>\bin\META-INF. This fixed the problem in Eclipse Neon with EclipseLink 2.5.2 using a simple plug-in project.
Had the same issue, but this actually worked for me :
mvn install -e -Dmaven.repo.local=$WORKSPACE/.repository.
NB : The maven command above will reinstall all your project dependencies from scratch. Your console will be loaded with verbose logs due to the network request maven is making.
You have to use the absolute path of the file otherwise this will not work. Then with that path we build the file and pass it to the configuration.
#Throws(HibernateException::class)
fun getSessionFactory() : SessionFactory {
return Configuration()
.configure(getFile())
.buildSessionFactory()
}
private fun getFile(canonicalName: String): File {
val absolutePathCurrentModule = System.getProperty("user.dir")
val pathFromProjectRoot = absolutePathCurrentModule.dropLastWhile { it != '/' }
val absolutePathFromProjectRoot = "${pathFromProjectRoot}module-name/src/main/resources/$canonicalName"
println("Absolute Path of secret-hibernate.cfg.xml: $absolutePathFromProjectRoot")
return File(absolutePathFromProjectRoot)
}
GL
Source

EclipseLink : No Persistence provider for EntityManager

I am trying to develop a web application. I started creating a Play! Framework project in Eclipse.
For the model part I chose to use JPA and since I had already created the database I was searching a way auto-generate the model classes.
I converted it to faceted form and used Dali to create the mapping with the database. During the configuration I was promted to chose a JPA implementation so I chose EclipseLink 2.1.3 Helios as a user library.
All the jars where added in my project.
After searching for similar errors, I modified the persistence.xml to:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="StudentApplication">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>models.Grade</class>
<class>models.GradePK</class>
<class>models.Student</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/studentapplication"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
</properties>
</persistence-unit>
</persistence>
The exact error I am getting now is:
Execution exception (In /app/controllers/class.java around line 98)
PersistenceException occured : No Persistence provider for EntityManager named jpa
I have to note that in application.conf I have declared the db connection and when I run the application I get
22:03:53,084 INFO ~ Connected to jdbc:mysql://localhost/studentapplication?useUnicode=yes&characterEncoding=UTF-8&connectionCollation=utf8_general_ci
Finally the file structure is:
-controllers
-models
-views
-META-INF
|_persistense.xml
As you may have understood (besides my rep) I am a newbie in web application development and specifically in JPA. I would be more than grateful to any kind of help. I apologize in advance if I posted not-needed information or if I missed mandatory information. Thank you for your time.
Thomas
It seems that you are referencing the persistence unit in your application by a different name than in your persistence.xml. Your persistence unit is named "StudentApplication" in persistence.xml. However, the error states that it is named "jpa" in your application.
Assuming that you are using application managed entity manager, there must be a line like this in your app:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa");
Change it to
EntityManagerFactory emf = Persistence.createEntityManagerFactory("StudentApplication");

JPA createEntityManagerFactory "Unknown Source" error (non-J2EE)

I can't find what's wrong: many people seem to have issues with creating a EntityManagerFactory using the PU name. But I've checked all the suggestions, and none helped so far.
I'm trying to build my first JavaFX2 app. It is a small dictionary application, originally built on the Netbeans Application framework (by extending the default "Master-Detail" generated classes). It uses a SQLite db.
I'm now porting it over from there to another (JavaFX2-enabled) project. I first set out to rebuild the JPA persistence stuff in the new app. As far as I can see, I have everything in place: META-INF/persistence.xml with all the necessary entity classes declarated, using the same DB connection as the original application.
I added eclipselink-2.3.0.jar; eclipselink-javax.persistence-2.0.jar and eclipselink-jpa-modelgen-2.3.0.jar to the project.
Instead of the Application Context I use a simple Properties class to hold the data (such as queries) that previously went in the .properties files.
This is the test class:
package ithildinfx;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.beans.property.StringProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class IthildinFX extends Application {
private void init(Stage primaryStage) {
entityManager = javax.persistence.Persistence.createEntityManagerFactory("IthildinFXPU").createEntityManager();
entryQuery = entityManager.createQuery(Properties.entryQuery).setParameter("gloss", "a%");
entryList = entryQuery.getResultList();
Group root = new Group();
primaryStage.setScene(new Scene(root));
(TableColumn definitions)
(TableView code)
root.getChildren().add(tableView);
}
#Override
public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
private javax.persistence.EntityManager entityManager;
private java.util.List<ithildinfx.Entry> entryList;
private javax.persistence.Query entryQuery;
}
And this is the contents of persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="IthildinFXPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>ithildinfx.Dataclass</class>
<class>ithildinfx.Metadata</class>
<class>ithildinfx.Translation</class>
<class>ithildinfx.Entry</class>
<class>ithildinfx.TrMd</class>
<class>ithildinfx.Language</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:sqlite:lib/db/ithildin-13-11-11.db"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="org.sqlite.JDBC"/>
<property name="javax.persistence.jdbc.user" value=""/>
</properties>
</persistence-unit>
</persistence>
One of the suggestions that I read here on StackOverflow was to add this line to manifest.mf:
Meta-Persistence: META-INF/persistence.xml
and, possibly:
JPA-PersistenceUnits: IthildinFXPU
But neither made any difference.
This is the output that I invariably get:
Building jar: /Users/luthien/NetBeansProjects/IthildinFX/dist/IthildinFX.jar
Copy libraries to /Users/luthien/NetBeansProjects/IthildinFX/dist/lib.
Building jar: /Users/luthien/NetBeansProjects/IthildinFX/dist/IthildinFX.jar
Detected JavaFX Ant API version 1.1
Deleting: /Users/luthien/NetBeansProjects/IthildinFX/dist/IthildinFX.jar
Deleting: /Users/luthien/NetBeansProjects/IthildinFX/dist/lib/IthildinFX.jar
Deleting: /Users/luthien/NetBeansProjects/IthildinFX/dist/README.TXT
Skip jar copy to itself: IthildinFX.jar
Skip jar copy to itself: lib/eclipselink-2.3.0.jar
Skip jar copy to itself: lib/eclipselink-javax.persistence-2.0.jar
Skip jar copy to itself: lib/eclipselink-jpa-modelgen-2.3.0.jar
Skip jar copy to itself: lib/sqlite-jdbc-3.7.2.jar
jfx-deployment:
jar:
run:
Exception in Application start method
java.lang.NullPointerException
at javax.persistence.spi.PersistenceProviderResolverHolder$DefaultPersistenceProviderResolver.getProviderNames(Unknown Source)
at javax.persistence.spi.PersistenceProviderResolverHolder$DefaultPersistenceProviderResolver.getPersistenceProviders(Unknown Source)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at ithildinfx.IthildinFX.init(IthildinFX.java:29)
at ithildinfx.IthildinFX.start(IthildinFX.java:109)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:298)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:136)
at com.sun.javafx.application.PlatformImpl$3.run(PlatformImpl.java:108)
JavaFX application launcher: calling System.exit
jfxsa-run:
BUILD SUCCESSFUL (total time: 5 seconds)
The libraries seem to all be in the right place - in any case, they are in the same place as they are in the first application. It might be that the Netbeans Application framework does some scary voodoo under the bonnet, but I really don't know how to figure that out.
Does anyone know of a reason why it can't seem to find the PU?
Thanks in advance!
Luthien
There error is coming from the JPA library itself, it seems that JPA is not configured correctly. The issue dos not seem to have anything to do with the persistence unit, the JPA library seems to have issues, looks like it can't find its services file resource.
Maybe remove eclipselink-javax.persistence-2.0.jar, if you server already has JPA on its classpath, there could be a conflict.

Class "model.Address" is listed in the persistence.xml file but not mapped

I have created a JPA project. In that Eclipse displays the following error on the entity class.
Class "model.Address" is listed in the persistence.xml file but not mapped
How am I supposed to map the entity class in persistance.xml?
Here is the model.Address entity:
package model;
import java.io.Serializable;
import javax.persistence.*;
#Entity
public class Address implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String city;
private String country;
private String province;
private String postalCode;
private String street;
// Getters/setters omitted for brevity.
}
Here is the persistence.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0"
>
<provider>org.eclipse.persistance.example.jpa.20.employee.annotations</provider>
<persistence-unit name="employee" transaction-type="RESOURCE_LOCAL">
<class>model.Employee</class>
<class>model.Address</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:#localhost:1521:orcl" />
<property name="javax.persistence.jdbc.user" value="scott" />
<property name="javax.persistence.jdbc.password" value="tiger" />
</properties>
</persistence-unit>
</persistence>
This is an Eclipse quirk. I recently had exactly this problem when I created a new JPA project with the JPA library configuration disabled, but didn't manually configure the JPA libraries before I created the entities by the Eclipse New JPA Entity wizard. After creating the entities I configured the JPA libraries in project's Build Path (just by adding target Java EE server runtime in Libraries), but the validation error still remains. I could solve it in at least one of following ways:
Rightclick persistence.xml file, JPA Tools -> Synchronize Class List.
Or, rightclick project, Validate.
Or, close/reopen project.
This is consistently reproducible. I was using Eclipse Indigo SR1. When I create the entities after configuring the JPA libraries, this validation error doesn't occur.
Right click on jpa project
then
I think you have the wrong JPA provider class. It has to be:
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
(the one you've set doesn't seem to be a class at all, let alone a provider class)
Make sure your class is annotated with #Entity
(from javax.persistence.Entity)
I realise that's not the OP's problem, but I got caught by that and Google sent me here.
You need to create a persistence file and a ORM mapping file for JPA, refer the mapping file from persistence file.
<persistence-unit name="persistenceUnit"
transaction-type="RESOURCE_LOCAL">
<provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
<mapping-file>META-INF/hbase-orm.xml</mapping-file>
<class>com.xxx.logcollector.entity.DefaultLogableEntity</class>
<properties>
<property name="datanucleus.jpa.addClassTransformer" value="false" />
<property name="datanucleus.managedRuntime" value="false" />
....
Create ORM mapping file
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"
version="1.0">
<entity class="com.xxx.cne.logcollector.entity.DefaultLogableEntity"
name="DefaultLogableEntity">
<table name="RAW_LOG_COLLECTION" />
<attributes>
<id name="clientHostIP">
<column name="ANALYTICS:CLIENT_IP" />
</id>
<basic name="requestDateTime">
<column name="ANALYTICS:REQUEST_DATETIME" />
</basic>
...
Create entity manager in spring
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="persistenceUnit"></property>
If eclipse is used , go to Window>Preference>Validation and uncheck Suspend all validators option .Clean the project and problem get solved.
Any of the above didnt work.
For anyone who is searching for the "Class xxxx is mapped, but is not included in any persistence unit" error in Eclipse or RAD:
Right-click on the project and choose properties.
Select JPA
Select the radio button "Discover annotated classes automatically"
OK and wait for the project to finish building.
These steps worked for me.
It should be written like:
#Entity
**#Table(name="Address",schema="ABCD")** `
...or it could be written like :
#Entity
public class Address {
}
i got similar error and when eclipse artifacts folder ".settings" is missed .
After i generate eclipse artifacts using "maven-eclipse-plugin" , the error is gone