No Persistence provider for EntityManager named DataSourcePostgres - java

I receive the following error in my standalone java application:
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named DataSourcePostgres
Here's my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" 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://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="DataSourcePostgres">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>Denarnica</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.ProgressDialect"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<!--<property name="hibernate.show_sql" value="true"/>-->
<property name="hibernate.connection.username" value="*****"/>
<property name="hibernate.connection.password" value="*******"/>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/postgres"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
and here's my Server.java:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;
public class Server {
private static final String PERSISTENCE_UNIT_NAME = "DataSourcePostgres";
private static EntityManagerFactory factory;
public static void main(String[] args) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
// Read the existing entries and write to console
Query q = em.createQuery("select d from Data d");
List<Denarnica> dataList= q.getResultList();
System.out.println("Size: " + dataList.size());
}
}
I've been looking at some similar problems, but the solutions people suggested to them don't seem to help me. Any advice?

My problem was I didn't put the persistence.xml into a META-INF folder. After I fixed that everything worked.

Related

How to correctly inject EntityManager into JAX-WS web service?

I'm trying to implement a JAX-WS web service which has an endpoint that returns data from the configured data source. I managed to create the service and the client, but I can't access the database because I get Null Pointer Exceptions when I try to use the injected EntityManager.
Here is my service:
#WebService(serviceName="ViewDocuments")
public class ViewDocumentService {
#PersistenceContext(unitName = "HibernateJPA")
private EntityManager em;
#WebMethod
public String sayHello() {
return "Hello world!";
}
#Produces("application/json")
#WebMethod(operationName="getDocuments")
public List<File> getDocuments(#WebParam(name = "name") String filename) {
if(filename == null)
return em.createQuery("FROM File").getResultList();
else return null;
}
}
And here is my WebServiceClient:
#WebServiceClient(name="ViewDocuments", wsdlLocation = "http://localhost:8080/lab8/ViewDocuments?wsdl")
public class ViewDocumentClient extends Service {
protected ViewDocumentClient(URL wsdlDocumentLocation, QName serviceName) {
super(wsdlDocumentLocation, serviceName);
}
#WebEndpoint(name = "DocumentPort")
public ViewDocumentService getDocumentPort() {
return new ViewDocumentService();
}
}
I am trying to call the function here:
public class MainDocumentClient {
public static void main(String[] args) throws Exception {
URL wsdlUrl = new URL("http://localhost:8080/lab8/ViewDocuments?wsdl");
QName serviceName = new QName("http://webservices/", "ViewDocuments");
ViewDocumentClient service = new ViewDocumentClient(wsdlUrl, serviceName);
ViewDocumentService viewDocumentService = service.getDocumentPort();
System.out.println(viewDocumentService.sayHello());
System.out.println(viewDocumentService.getDocuments(null));
}
}
This is my persistence.xml file content:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
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_2.xsd">
<persistence-unit name="HibernateJPA" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>java:/Postgres-Source8</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL95Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.archive.autodetection" value="class, hbm" />
</properties>
</persistence-unit>
<persistence-unit name="HibernateJPAForTests" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/lab8" />
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.user" value="postgres" />
<property name="javax.persistence.jdbc.password" value="<password>" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL95Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.archive.autodetection" value="class, hbm" />
</properties>
</persistence-unit>
</persistence>
The sayHello() method works fine. I also tried to use an EntityManagerFactory, to instantiate my Repository by hand, to add the #Stateless annotation, but nothing seems to work. I just can't query my database.
After lots of research, I still can't seem to understand how to properly inject the EntityManager. Can someone explain this to me, please?
I am using Wildfly21.0.0.

Java EntityManager throwing NullPointerException

When I try to run the Unit test for this DAO class, I am getting NullPointerException at getById return statement. I know that the class does not initialize the EntityManager, but I don’t understand why? - I can’t tell whether my persistence.xml configuration is wrong or the DB credentials are incorrect.
I saw two or more StackOverflow threads but had had little luck. I am using Intellij IDE.
package com.beetlehand.model.dao;
import com.beetlehand.model.AttributeEntity;
import org.apache.commons.lang.StringUtils;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
#Stateless
public class AttributeDao extends AbstractDao<AttributeEntity> {
#PersistenceContext(unitName = "NewPersistenceUnit")
protected EntityManager entityManager;
public AttributeEntity getById(Long id) {
if(id == null) return null;
return entityManager.find(AttributeEntity.class, id);
}
/*** more code ***/
}
Persistence configuration file
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="NewPersistenceUnit">
<class>com.beetlehand.model.AttributeEntity</class>
<class>com.beetlehand.model.AttributeValueEntity</class>
<class>com.beetlehand.model.AuditEntity</class>
<class>com.beetlehand.model.CategoryEntity</class>
<class>com.beetlehand.model.CustomerEntity</class>
<class>com.beetlehand.model.DepartmentEntity</class>
<class>com.beetlehand.model.OrderDetailEntity</class>
<class>com.beetlehand.model.OrdersEntity</class>
<class>com.beetlehand.model.ProductEntity</class>
<class>com.beetlehand.model.ProductAttributeEntity</class>
<class>com.beetlehand.model.ProductCategoryEntity</class>
<class>com.beetlehand.model.ReviewEntity</class>
<class>com.beetlehand.model.ShippingEntity</class>
<class>com.beetlehand.model.ShippingRegionEntity</class>
<class>com.beetlehand.model.ShoppingCartEntity</class>
<class>com.beetlehand.model.TaxEntity</class>
<properties>
<property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/beetlehand"/>
<property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/beetlehand"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="openjpa.ConnectionURL" value="jdbc:mysql://localhost:3306/beetlehand"/>
<property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver"/>
<property name="eclipselink.jdbc.url" value="jdbc:mysql://localhost:3306/beetlehand"/>
<property name="eclipselink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="username"/>
<property name="hibernate.connection.password" value="password"/>
</properties>
</persistence-unit>
</persistence>
You need to mock the entityManager then you need to do stub for entityManager.find() as shown below.
#Mock // Mocking enitt
private EntityManager entityManager;
public AttributeEntity entity = new AttributeEntity();
// Stubbing for entityManager.find()
Mockito.when(entityManager.find(Mockito.any(AttributeEntity.class), Mockito.any())).thenReturn(entity);

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] Hibernate Java

I can't compile my program, and get data from remote Database, below I added my persistance.xml, when I want to compile my program i get Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] error.
What I suppose to do?
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" 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">
<persistence-unit name="hibernate-dynamic" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider </provider>
<properties>
<!-- Configuring JDBC properties -->
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://mysql.wmi.amu.edu.pl:3306/s434739_pracownia?useSSL=false"/>
<property name="javax.persistence.jdbc.user" value="s434739"/>
<property name="javax.persistence.jdbc.password" value="pracownia0"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
<!-- Hibernate properties -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="validate"/>
<property name="hibernate.format_sql" value="false"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
App.class
public class App {
private static EntityManager entityManager = null;
private static EntityManagerFactory entityManagerFactory = null;
public static void main( String[] args ) {
try {
entityManagerFactory =
Persistence.createEntityManagerFactory("hibernate");
entityManager = entityManagerFactory.createEntityManager();
} catch (Exception ex) {
System.out.println("ERR: " + ex.getMessage());
}
MainLogic mainLogic = new MainLogic();
mainLogic.getThemAll(entityManager);
mainLogic.printThemAll();
}
}
MainLogic.class
void getThemAll(EntityManager entityManager) {
for(String tableName: tableNames) {
String str = "SELECT k FROM " + tableName + " k";
Query query = entityManager.createQuery("SELECT k FROM BrandAmbassador k");
if(tableName.equals("Ambasadorzy_marki"))
brandAmbassadorList = query.getResultList();
if(tableName.equals("Kategorie"))
categoryList = query.getResultList();
if(tableName.equals("Producenci"))
brandList = query.getResultList();
if(tableName.equals("Produkty"))
productList = query.getResultList();
if(tableName.equals("Samochody_sluzbowe"))
companyCarList = query.getResultList();
}
// this.entityManager.close();
}

Provider org.hibernate.envers.event.EnversIntegrator not a subtype error in CDI+JPA2.1+Restful

I am trying to call JPA from a rest web service. but it throws me
org.hibernate.integrator.spi.Integrator: Provider org.hibernate.envers.event.EnversIntegrator not a subtype at org.apache.cxf.service.invoker.AbstractInvoker.createFault(AbstractInvoker.java:170) at
org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:136) at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:204) at
org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:101) at
org.apache.openejb.server.cxf.rs.AutoJAXRSInvoker.invoke(AutoJAXRSInvoker.java:68) at org.apache.cxf.interceptor.ServiceInvokerInterceptor
I have used maven 4, JPA 2.1, CDI.
My code:
JPA part:
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("defaultMainUnit", null);
EntityManager entityManager = entityManagerFactory.createEntityManager();
Persistence.generateSchema("defaultMainUnit", null);
Query master Query = entityManager
.createNamedQuery("master.findAll");
List<Master > masterList = masterQuery.getResultList();
for(Master master : masterList){
System.out.println("Master id: "+master .getMaster TrackingId());
}
entityManager.clear();
entityManager.close();
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="defaultMainUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>core.Master</class>
<class>core.Child</class>
<properties>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" />
<property name="hibernate.connection.url" value="jdbc:hsqldb:mem:defaultDB" />
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.connection.release_mode" value="after_statement"/>
<!-- insert data using sql file -->
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.schema-generation.create-source" value="metadata"/>
<property name="javax.persistence.schema-generation.drop-source" value="metadata"/>
<property name="javax.persistence.sql-load-script-source" value="mcb-test-import.sql"/>
</properties>
</persistence-unit>
Restservice:
package restcdi.rest;
#Path("/")
public class GreetREST {
#Inject
private EnglishGreet greet;
#GET
#Path("/greet")
#Produces(MediaType.TEXT_PLAIN)
public String greet() {
return greet.greet();
}
#GET
#Path("/master")
#Produces(MediaType.APPLICATION_JSON)
public List master() throws FileNotFoundException, IOException{
CheckJPAProperties check = new CheckJPAProperties();
List masterList = check.runMe();
return masterList;
}
}
in the above code, runMe() returns all the masters in database using JPA code above. when i run the JPA code without a rest service in main it runs fine and returns everything. I am not sure what I am missing. I tried including the hibernate-envers dependency in pom.xml but it still throws the same error.
please help.
ps: just in case this is needed i am including my applicationConfig
package restcdi.rest;
import java.util.Set;
import javax.ws.rs.core.Application;
#javax.ws.rs.ApplicationPath("rest")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
resources.add(GreetREST.class);
return resources;
}
}

JPA entries are not created or retrieved

I'm having program that creates JPA entries with the entity manager.
during the process I don't get any errors.
...
factory = Persistence.createEntityManagerFactory("perst");
EntityManager entityManager = factory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(object);
entityManager.getTransaction().commit();
...
entityManager.close();
I have created a program like follows to read the data but it doesn't return any data,
the query returns empty. What could be the reason ?
This is the program to read the data:
static List<String> classList = new ArrayList<String>();
private static EntityManagerFactory factory;
public static void main(String[] args) {
// TODO Auto-generated method stub
factory = Persistence.createEntityManagerFactory("perst");
EntityManager entityManager = factory.createEntityManager();
classList.add("LeaveRequest");
classList.add("person");
for (Object classOjc : classList) {
String className = classOjc.toString();
Query query = entityManager.createQuery("SELECT p FROM " + className + " p");
#SuppressWarnings("rawtypes")
List resultList = query.getResultList();
System.out.println(resultList.size());
for (Object result : resultList) {
System.out.println(result.toString());
}
}
}
the xml persist is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="perst" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>LeaveRequest</class>
<class>person</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:derby:/home/vogella/databases/simpleDb;create=true" />
<property name="javax.persistence.jdbc.user" value="Sales" />
<property name="javax.persistence.jdbc.password" value="" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
<property name="eclipselink.logging.level" value="SEVERE" />
<property name="eclipselink.logging.exceptions" value="true" />
</properties>
</persistence-unit>
</persistence>
You configured eclipselink to drop and recreate the schema each time the app is started:
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
So obviously, if you run a first application that persists some entries, and then a second application which tries to read what the first one has written, you won't find anything anymore, since eclipselink drops everything and recreates the schema every time.

Categories