Test JPA with Arquillian: Derby driver is running instead of PostgreSQL - java

What I have:
Entity:
#Entity
public class TestEntity {
#Id #GeneratedValue
private Integer id;
private String value;
// Constructors, getters/setters
}
Test itself:
#RunWith(Arquillian.class)
public class TestEntityTest {
#Deployment
public static JavaArchive deploy() {
return ShrinkWrap
.create(JavaArchive.class)
.addClass(TestEntity.class)
.addAsManifestResource("META-INF/persistence.xml", "persistence.xml")
.addAsResource(EmptyAsset.INSTANCE, "WEB-INF/beans.xml");
}
#PersistenceContext(name = "jpa_unit")
private EntityManager entityManager;
#Inject
private UserTransaction userTransaction;
#Test
public void test() throws Exception {
System.out.println(deploy().toString(true));
assertNotNull("Entity manager must be injected", entityManager);
assertNotNull("Transaction service must be injected", userTransaction);
userTransaction.begin();
TestEntity entity = new TestEntity("test value");
entityManager.persist(entity);
System.out.println("ID: [" + entity.getId() + "]");
assertNotNull(entity.getId());
userTransaction.commit();
}
}
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test-jpa</groupId>
<artifactId>test-jpa</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>1.1.10.Final</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1204-jdbc42</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-glassfish-embedded-3.1</artifactId>
<version>1.0.0.CR4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>3.1.2.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
META-INF/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="jpa_unit" transaction-type="JTA">
<properties>
<property name="javax.persistence.schema-generation-action"
value="drop-and-create"/>
<property name="javax.persistence.schema-generation-target"
value="database"/>
<property name="javax.persistence.jdbc.driver"
value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:postgresql://localhost:5432/test"/>
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="javax.persistence.jdbc.password" value="postgres"/>
</properties>
</persistence-unit>
</persistence>
When I launch test, container starts successfully and tries to run all this... But fails because of Derby error:
WARNING:
Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Schema 'POSTGRES' does not exist
Error Code: 20000
Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
bind => [2 parameters bound]
Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?")
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:333)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:644)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:535)
...
So, when I have specified PostgreSQL driver in persistence.xml, why Derby is picked up?

Related

No Persistence provider for EntityManager Error

I am getting this error "No Persistence provider for EntityManager named" and not able to proceed.
I am learning hibernate and trying so hands on stuff.
I tried all the methods mentions in this search forum, but still i get the same error. I tried the following
SAVED THE persistent.xml file in src/main/resources/META-INF/persistent.xml.
Updated the provider to "org.hibernate.jpa.HibernatePersistenceProvider".
Still no luck, can any one kindly help in how to resolve this. Below is screen shot and code.
POM:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.0-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.0.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
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">
<persistence-unit name="concretepage">
<description>JPA Demo</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/testDB1"/>
<property name="javax.persistence.jdbc.user" value="xxxxx"/>
<property name="javax.persistence.jdbc.password" value="yyyyy"/>
</properties>
</persistence-unit>
</persistence>
Java:
package database.hibernate;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class JPAUtility {
private static final EntityManagerFactory emFactory;
static {
emFactory = Persistence.createEntityManagerFactory("concretepage");
}
public static EntityManager getEntityManager(){
return emFactory.createEntityManager();
}
public static void close(){
emFactory.close();
}
}
Java Program calling JPAUtility:
public class App2 {
public static void main(String[] args) {
EntityManager entityManager = JPAUtility.getEntityManager();
entityManager.getTransaction().begin();
....
entityManager.getTransaction().commit();
}
}
Error Message:
Exception in thread "main" java.lang.ExceptionInInitializerError
at database.hibernate.App2.main(App2.java:9)
Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named concretepage
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at database.hibernate.JPAUtility.<clinit>(JPAUtility.java:9)
... 1 more
Project Structure:
You need to change the maven dependency version from <version>6.1.0.Final</version> to <version>5.2.11.Final</version> for <artifactId>hibernate-core</artifactId> as there has been significant changes from Hibernate 5 to 6 and need to consider upgrading corresponding dependencies and schema names etc in persistance.xml file
You can read another thread here - why is dependency to javax.persistence-api removed in hibernate-core 6.0.2
When I tried with 6.1.0.Final - I also get the same error as mentioned below.
But when I changed version back to 5.2.11 then it connected to database.
PS : I've used the maria db instead of mysql but that should not matter.

error header: 41007000 JPA and Servlet when call StoredProcedure

I'm student and try to do project at school, which allows the user choose year for report video by year, but when i tried chooes the year had data and I am getting the following error:
java.io.StreamCorruptedException: invalid stream header: 41007000
java.base/java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:966)
java.base/java.io.ObjectInputStream.<init>(ObjectInputStream.java:405)
org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:309)
org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:299)
org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:218)
org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:287)
org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:139)
org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:114)
org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:28)
org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:60)
org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:260)
org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:256)
org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:246)
org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:332)
org.hibernate.loader.Loader.extractKeysFromResultSet(Loader.java:794)
org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:719)
org.hibernate.loader.Loader.processResultSet(Loader.java:991)
org.hibernate.result.internal.OutputsImpl$CustomLoaderExtension.processResultSet(OutputsImpl.java:289)
org.hibernate.result.internal.OutputsImpl.extractResults(OutputsImpl.java:136)
org.hibernate.result.internal.OutputsImpl.extractCurrentResults(OutputsImpl.java:127)
org.hibernate.result.internal.OutputsImpl.access$100(OutputsImpl.java:35)
org.hibernate.result.internal.OutputsImpl$CurrentReturnState.buildOutput(OutputsImpl.java:187)
org.hibernate.result.internal.OutputsImpl$CurrentReturnState.getOutput(OutputsImpl.java:171)
org.hibernate.result.internal.OutputsImpl.getCurrent(OutputsImpl.java:91)
org.hibernate.procedure.internal.ProcedureCallImpl.getResultList(ProcedureCallImpl.java:751)
com.lab6.servlet.NamedQuery.doNamedQueryReportByYear(NamedQuery.java:70)
com.lab6.servlet.NamedQuery.service(NamedQuery.java:56)
javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
org.hibernate.type.SerializationException: could not deserialize
org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:243)
org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:287)
org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:139)
org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:114)
org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:28)
org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:60)
org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:260)
org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:256)
org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:246)
org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:332)
org.hibernate.loader.Loader.extractKeysFromResultSet(Loader.java:794)
org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:719)
org.hibernate.loader.Loader.processResultSet(Loader.java:991)
org.hibernate.result.internal.OutputsImpl$CustomLoaderExtension.processResultSet(OutputsImpl.java:289)
org.hibernate.result.internal.OutputsImpl.extractResults(OutputsImpl.java:136)
org.hibernate.result.internal.OutputsImpl.extractCurrentResults(OutputsImpl.java:127)
org.hibernate.result.internal.OutputsImpl.access$100(OutputsImpl.java:35)
org.hibernate.result.internal.OutputsImpl$CurrentReturnState.buildOutput(OutputsImpl.java:187)
org.hibernate.result.internal.OutputsImpl$CurrentReturnState.getOutput(OutputsImpl.java:171)
org.hibernate.result.internal.OutputsImpl.getCurrent(OutputsImpl.java:91)
org.hibernate.procedure.internal.ProcedureCallImpl.getResultList(ProcedureCallImpl.java:751)
com.lab6.servlet.NamedQuery.doNamedQueryReportByYear(NamedQuery.java:70)
com.lab6.servlet.NamedQuery.service(NamedQuery.java:56)
javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Report class
I call #NamedStoredProcedureQuery for setup StoredProcedure with annonation
#NamedStoredProcedureQueries({
#NamedStoredProcedureQuery(
name = "Report.spFavoriteByYear",
procedureName = "spFavoriteByYear",
resultClasses = {Report.class},
parameters = {
#StoredProcedureParameter(name = "Year",
type = Integer.class)
}
)
})
public class Report implements Serializable{...}
NamedQuery.java
In method doNamedQueryReportByYear, im using createNamedStoredProcedureQuery to call name name query in Report class entity and set list Report with method getResultlist()
private void doNamedQueryReportByYear(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PolyOEUnit");
EntityManager em = emf.createEntityManager();
String method = req.getMethod();
if(method.contentEquals("POST")) {
Integer years = Integer.valueOf(req.getParameter("year"));
StoredProcedureQuery query =
em.createNamedStoredProcedureQuery("Report.spFavoriteByYear");
query.setParameter("Year", years);
List<Report> listReport = query.getResultList();
req.setAttribute("videos", listReport);
}
pom.xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.12.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>8.2.2.jre8</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.eclipse.persistence/eclipselink -->
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>3.0.2</version>
</dependency>
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="PolyOEUnit" transaction-type="RESOURCE_LOCAL">
<class>com.lab6.servlet.Favorite</class>
<class>com.lab6.servlet.User</class>
<class>com.lab6.servlet.Video</class>
<class>com.lab6.servlet.Report</class>
<!-- <class>com.lab5.servlet.User</class> --> <!-- của lab 5 -->
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://localhost:1433;databaseName=PolyOE"/>
<property name="javax.persistence.jdbc.password" value="0907852396"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" />
<property name="hibernate.format_sql" value="true"/>
<property name ="hibernate.show_sql" value = "true" />
</properties>
</persistence-unit>
</persistence>
spFavoriteByYear
CREATE PROC spFavoriteByYear(#Year INT)
AS
BEGIN
SELECT
v.Title AS 'Group',
count(f.Id) AS 'Likes',
max(f.LikeDate) AS 'Newest',
min(f.LikeDate) AS 'Oldest'
FROM Favorites f JOIN Videos v ON v.Id = f.VideoId
WHERE year(f.LikeDate) = #Year
GROUP BY v.Title
END

Entity Manager is null when trying to connect to Dockerised DB2 in Java using JPA, also using maven & Open Liberty

So I'm developing an API and I'm trying to connect to a local docker instance of DB2 from java using JPA entity manager. After running Apache Maven and getting build success, I try a GET request from Postman to test an endpoint and get a list of all users from DB2. I'm receiving the below error saying that entity manager is null. I've tried researching online and can't seem to find the solution.
The Dao class is virtually unchanged from a previous iteration that used Derby instead of DB2 and it worked fine.
I was wanting to know where I've gone wrong, what needs changing, and if anything is not needed. Provided below is the xml files and the DAO java class containing the entity manager. All properties for DB2 is correct as they're unchanged from a successful connection I was able to do from Eclipse's Database Development. The driver used then was db2jcc4 which I think is different to the driver said to use for the maven dependency so not sure if that's an issue.
Postman:
Error 500: java.lang.NullPointerException: Cannot invoke
"javax.persistence.EntityManager.createNamedQuery(String, java.lang.Class)" because
"this.em" is null
Maven:
[INFO] [ERROR ] CWWJP0015E: An error occurred in the org.eclipse.persistence.jpa.PersistenceProvider persistence provider when it attempted to create the container entity manager factory for the jpa-unit persistence unit. The following error occurred: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.7.9.v20210604-2c549e2208): org.eclipse.persistence.exceptions.EntityManagerSetupException
[INFO] Exception Description: Predeployment of PersistenceUnit [jpa-unit] failed.
[INFO] Internal Exception: javax.persistence.PersistenceException: CWWJP0013E: The server cannot locate the java:comp/DefaultDataSource data source for the jpa-unit persistence unit because it has encountered the following exception: javax.naming.NameNotFoundException: javax.naming.NameNotFoundException: java:comp/DefaultDataSource.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.obdoblock</groupId>
<artifactId>hyperledger-api</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!-- Liberty configuration -->
<liberty.var.default.http.port>3500</liberty.var.default.http.port>
<liberty.var.default.https.port>9443</liberty.var.default.https.port>
<liberty.var.app.context.root>api</liberty.var.app.context.root>
<!-- TestDB Configuration -->
<version.ibm.db2>11.5.6.0</version.ibm.db2>
</properties>
<dependencies>
<!-- Provided dependencies -->
<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-api</artifactId>
<version>8.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.microprofile</groupId>
<artifactId>microprofile</artifactId>
<version>3.3</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
<!-- For tests -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-client</artifactId>
<version>3.3.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.3.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>yasson</artifactId>
<version>1.0.7</version>
<scope>test</scope>
</dependency>
<!-- DB2 connector -->
<dependency>
<groupId>com.ibm.db2</groupId>
<artifactId>jcc</artifactId>
<version>11.5.6.0</version>
</dependency>
<!-- Hyperledger Fabric Gateway for Blockchain -->
<dependency>
<groupId>org.hyperledger.fabric</groupId>
<artifactId>fabric-gateway-java</artifactId>
<version>2.2.0</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- Enable liberty-maven plugin -->
<plugin>
<groupId>io.openliberty.tools</groupId>
<artifactId>liberty-maven-plugin</artifactId>
<version>3.3.4</version>
<configuration>
<copyDependencies>
<location>${project.build.directory}/liberty/wlp/usr/shared/resources</location>
<dependency>
<groupId>com.ibm.db2</groupId>
<artifactId>jcc</artifactId>
<version>11.5.6.0</version>
</dependency>
</copyDependencies>
</configuration>
</plugin>
<!-- Plugin to run functional tests -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<systemPropertyVariables>
<http.port>${liberty.var.default.http.port}</http.port>
<context.root>${liberty.var.app.context.root}</context.root>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
</plugin>
<!-- Plugin to run unit tests -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
</project>
server.xml
<server description="Obdoblock REST Server">
<featureManager>
<feature>jaxrs-2.1</feature>
<feature>openapi-3.1</feature>
<feature>jpa-2.2</feature>
<feature>cdi-2.0</feature>
</featureManager>
<httpEndpoint
httpPort="${default.http.port}"
httpsPort="${default.https.port}"
id="defaultHttpEndpoint"
host="*"
/>
<webApplication
location="hyperledger-api.war"
contextRoot="${app.context.root}"
/>
<!-- DB2 Library Configuration -->
<library id="DB2JCCLib">
<fileset dir="${shared.resource.dir}" includes="*.jar" />
</library>
<dataSource jndiName="jdbc/db2">
<jdbcDriver libraryRef="jdbcLib"/>
<properties
databaseName="testdb"
serverName="localhost"
portNumber="50000"
user="****" password="****"
/>
</dataSource>
</server>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- TODO: This will have to be configured by ENV as well -->
<!-- https://www.eclipse.org/eclipselink/documentation/2.5/jpa/extensions/p_ddl_generation.htm -->
<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="jpa-unit" transaction-type="JTA">
<properties>
<!-- Connection Specific -->
<property name="hibernate.dialect" value="org.hibernate.dialect.DB2Dialect"/>
<property name="javax.persistence.jdbc.driver" value="com.ibm.db2.jcc.DB2Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:db2://localhost:50000/testdb" />
<property name="javax.persistence.jdbc.user" value="****" />
<property name="javax.persistence.jdbc.password" value="****" />
<property name="show_sql" value="true"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties>
</persistence-unit>
</persistence>
UserDao.java
package dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.enterprise.context.RequestScoped;
import models.*;
#RequestScoped
public class UserDao {
#PersistenceContext(name = "jpa-unit")
private EntityManager em;
public void createUser(Users user){
em.persist(user);
}
public Users readUser(int userId){
return em.find(Users.class, userId);
}
public List<Users> readAllUsers(){
return em.createNamedQuery("Users.findAll", Users.class).getResultList();
}
public void updateUser(Users user){
em.merge(user);
}
public void deleteUser(Users userId){
em.remove(userId);
}
public List<Users> findUser(String email){
return em.createNamedQuery("Users.findUser", Users.class)
.setParameter("email", email)
.getResultList();
}
public void createHistory(History hist){
em.persist(hist);
}
//wait this doesnt do anything?
public Users readHistory(int id){
return em.find(Users.class, id);
}
public List<History> readAllHistory(){
return em.createNamedQuery("History.findAll", History.class).getResultList();
}
}
Versions:
Docker: 20.10.8, build 3967b7d
DB2: ibm/db2 docker image version 11.5.6
Maven: 3.8.3
Java: JDK 14.0.2
If needing any more details, I'm happy to provide them.
Thanks, Dylan
Your persistence.xml is incorrect. It should point to datasource configured in the server.xml, not specify driver properties.
Like this:
<?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="jpa-unit" transaction-type="JTA">
<jta-data-source>jdbc/guestbookDS</jta-data-source>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create" />
<property name="javax.persistence.schema-generation.create-database-schemas" value="true" />
<property name="javax.persistence.schema-generation.scripts.action" value="create" />
<property name="javax.persistence.schema-generation.scripts.create-target" value="create.ddl"/>
<!--
<property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="both" />
-->
</properties>
</persistence-unit>
</persistence>
You can check this very simple Liberty project which uses JPA and database here https://github.com/stocktrader-ops/db-sat-demo (it is using PostgreSQL instead of DB2, but you should just use your datasource setup)

No Persistence provider for EntityManager named xxxx

enter image description herecurrently Hibernate. I create simply project. I did everything as is in course but i get "No Persistence provider for EntityManager named xxxx". I dont know what is wrong. I find many solutions but none work with me.
package pl.javastart.dao;
import pl.javastart.model.Book;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class BookDaoImpl implements BookDao {
private EntityManagerFactory emFactory;
private EntityManager entityManager;
public BookDaoImpl() {
emFactory = Persistence.createEntityManagerFactory("myPersistenceUnit");
entityManager = emFactory.createEntityManager();
}
public void save(Book book) {
EntityTransaction tx = entityManager.getTransaction();
tx.begin();
entityManager.persist(book);
tx.commit();
}
public Book get(Long id) {
Book book = entityManager.find(Book.class, id);
return book;
}
public void cleanUp() {
entityManager.close();
emFactory.close();
}
}
<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="myPersistenceUnit"
transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/library" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="admin" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.schema-generation.database.action"
value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>JPAbezSpringa</groupId>
<artifactId>jpabezbezsprinsaa</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<release>10</release>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.3.1.Final</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
</project>
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named myPersistenceUnit
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:85)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at pl.javastart.dao.BookDaoImpl.(BookDaoImpl.java:16)
at pl.javastart.main.Main.main(Main.java:10)
Maybe it will help you : https://stackoverflow.com/a/1285436/9593249
define the persistence provider name:
<provider>org.hibernate.ejb.HibernatePersistence</provider>
if you are using Hibernate 4 or for Hibernate 5
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
after
<persistence-unit name="myPersistenceUnit">

JPA Hibernate: Invalid persistence.xml

I am having some trouble with Hibernate and JPA. I have used Hibernate before but not with JPA so writing my first persistence.xml currently. I get error message " Invalid persistence.xml." or that the entity manager could not be created, depending on how I write my persistence.xml. The code line that fails is
entityManagerFactory = Persistence.createEntityManagerFactory("name");
And the persisted class looks something like
#Entity
#Table( name = "test_tbl" )
public class Test {
private Long _id;
private String _type;
public Position() {
// this form used by Hibernate
}
#Id
#GeneratedValue(generator="increment")
#GenericGenerator(name="increment", strategy = "increment")
#Column(name = "n_id")
public Long getId() {
return _id;
}
public void setId(Long id) {
this._id = id;
}
#Column(name = "str_type")
public String getType() {
return _type;
}
public void setType(String type) {
this._type = type;
}
And my pom.xml looks like this
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycoolproject</groupId>
<artifactId>Proj</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<name>Proj</name>
<url>http://maven.apache.org</url>
<properties>
<!-- Skip artifact deployment -->
<maven.deploy.skip>true</maven.deploy.skip>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.13.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.13.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>4.2.13.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
And this i my Persistence.xml placed in "src/main/java/resources/META-INF/
<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">
<persistence-unit name="name">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.mycoolproject.Test</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5555/trial"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.user" value="lalala"/>
<property name="javax.persistence.jdbc.password" value="testing"/>
<property name="hibernate.max_fetch_depth" value="3"/>
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
It looks like this is Java SE application. You might need to change persistent-unit tag like this:
<persistence-unit name="name" transaction-type="RESOURCE_LOCAL">
in Java SE you don't have JTA transactions, which are default.

Categories