java.lang.module.FindException: Module java.xml.bind not found - java

I am using jdk 13 but I want to create entity and write to database its.
and I added project->run configurations->arguments->VM Arguments
--add-modules java.xml.bind
then I ran the project but , I am getting this error :
Error occurred during initialization of boot layer
java.lang.module.FindException: Module java.xml.bind not found
I dont know, I am getting error why.I suppose my jdk is problem.But I dont know exactly.what should I do?
Test.java
package com.kerem.blog;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Test {
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("MyPersistenceUnit");
EntityManager manager = factory.createEntityManager();
Data data = new Data();
data.setDataName("Kerem");
data.setDataValue(23.2);
manager.getTransaction().begin();
manager.persist(data);
manager.getTransaction().commit();
manager.close();
}
}
Data.java
package com.kerem.blog;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Data {
#Id #GeneratedValue(strategy = GenerationType.IDENTITY)
private long dataId;
private String dataName;
private double dataValue;
public long getDataId() {
return dataId;
}
public void setDataId(long dataId) {
this.dataId = dataId;
}
public String getDataName() {
return dataName;
}
public void setDataName(String dataName) {
this.dataName = dataName;
}
public double getDataValue() {
return dataValue;
}
public void setDataValue(double dataValue) {
this.dataValue = dataValue;
}
}
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="MyPersistenceUnit">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.cj.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/testdb?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=Turkey" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password"
value="kerem2112" />
<property
name="javax.persistence.schema-generation.database.action"
value="create" />
</properties>
</persistence-unit>
</persistence>
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.keremsarmis</groupId>
<artifactId>blogbasic</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.6.Final</version>
</dependency>
</dependencies>
</project>

Related

Hibernate SQLite: Cannot get a connection as the driver manager is not properly initialized

I try to make use a Database system without have to run a separate database program.
I decided to use Hibernate SQLite. And I'm getting desperate here.
can someone pls tell me what i am doing whrong, or where i can find more help? I Faild with google, and ChatGPT was as always not helpfull to.
And for every one how try to convince me to use for example MariaDB, no. I need it to be one java application. Not more, not less...
src\main\resources\hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- <property name="hibernate.connection.url">jdbc:sqlite:path/to/your/database.db</property> -->
<property name="hibernate.connection.driver_class">org.sqlite.JDBC</property>
<property name="hibernate.connection.url">jdbc:sqlite:database.db</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLiteDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping class="de.minetrain.kekbot.database.test.Person"/>
</session-factory>
</hibernate-configuration>
src\main\resources\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_2.xsd" version="2.2">
<persistence-unit name="my-persistence-unit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>de.minetrain.kekbot.database.test.Person</class>
<!-- <class>com.example.MyOtherEntity</class> -->
<properties>
<property name="hibernate.connection.driver_class" value="org.sqlite.JDBC" />
<!-- <property name="hibernate.connection.url" value="jdbc:sqlite:path/to/your/database.db" /> -->
<property name="hibernate.connection.url" value="jdbc:sqlite:database.db" />
<property name="hibernate.connection.username" value="" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLiteDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<!-- <property name="hibernate.show_sql" value="true" /> -->
</properties>
</persistence-unit>
</persistence>
pom.xml
</ependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.1.Final</version>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.34.0</version>
</dependency>
</dependencies>
HibernateUtil class:
package de.minetrain.kekbot.database.test;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HibernateUtil {
private static final Logger logger = LoggerFactory.getLogger(HibernateUtil.class);
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
logger.error("Dant find class: ",e);
}
try {
Configuration configuration = new Configuration().configure("hibernate.cfg.xml"); // may wrong?
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
return configuration.buildSessionFactory(builder.build());
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Entity class:
package de.minetrain.kekbot.database.test;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Person {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
private int age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
And the class i try to whrite into the database:
package de.minetrain.kekbot.database.test;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class Database {
public static void test(){
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
// Verwenden Sie die Session, um Datenbankoperationen auszuführen
// session.close();
Transaction tx = null;
try {
tx = session.beginTransaction();
Person person = new Person();
person.setName("Max Mustermann");
person.setAge(30);
session.save(person);
tx.commit();
} catch (HibernateException ex) {
if (tx != null) {
tx.rollback();
}
ex.printStackTrace();
} finally {
session.close();
}
}
}
I just wanna lern to use SQLite, and try to Whrite a new person object into a database file.
Errors:
[20:00:15] >> WARN << [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator] - HHH000342: Could not obtain connection to query metadata java.lang.IllegalStateException: Cannot get a connection as the driver manager is not properly initialized
Initial SessionFactory creation failed.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.dialect.SQLiteDialect] as strategy [org.hibernate.dialect.Dialect]
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.hibernate.dialect.SQLiteDialect]
Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.hibernate.dialect.SQLiteDialect
I've managed to change the Exeptions. With the help from #andrewJames I found out, that I have to use a dialect, which I didn't know. I also noticed that I am using old versions of Hibernate and co.
And sorry in advance, for every experienced coder how gets headaches from my stupidity. I am not new to coding, but I am very new to databases and dealing with dependency's outside from just API package things. I tried to google as much as I could find, and testing every thing I could. But I ended up having to ask again. I am very sorry.
Iive changed stuff around and now have this pom.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.6.Final</version>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.40.0.0</version>
</dependency>
<dependency>
<groupId>com.github.gwenn</groupId>
<artifactId>sqlite-dialect</artifactId>
<version>0.1.2</version>
</dependency>
I've changed the dialect in the hibernate.cfg.xml:
<property name="hibernate.dialect">org.sqlite.hibernate.dialect.SQLiteDialect</property>
persistence.xml:
<property name="hibernate.dialect" value="org.sqlite.hibernate.dialect.SQLiteDialect" />
However, now I get the benefit of dealing with this exception:
[00:07:48] >> INFO << [org.hibernate.Version] - HHH000412: Hibernate ORM core version 6.1.6.Final
Initial SessionFactory creation failed.java.util.ServiceConfigurationError: org.hibernate.boot.spi.MetadataBuilderInitializer: Provider org.sqlite.hibernate.dialect.SQLiteMetadataBuilderInitializer could not be instantiated
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.util.ServiceConfigurationError: org.hibernate.boot.spi.MetadataBuilderInitializer: Provider org.sqlite.hibernate.dialect.SQLiteMetadataBuilderInitializer could not be instantiated
Caused by: java.lang.NoClassDefFoundError: org/hibernate/dialect/function/SQLFunction
Caused by: java.lang.ClassNotFoundException: org.hibernate.dialect.function.SQLFunction

Is it possible to deploy multiple bundles to ServiceMix that use Hibernate Envers?

We are attempting to deploy multiple bundles in ServiceMix 6.1.4 that each make updates to a database and we want those updates to be audited with Hibernate Envers 4.3.6.FINAL. We are in the proof-of-concept stage, so we are only building the jar files and putting them into the deploy directory of the apache-servicemix-6.1.4 directory, with a separate datasource blueprint file for each.
Individually, the bundles work and audit just fine. But if you have both bundles deployed, one will fail with the error:
2018-04-20 14:00:10,635 | WARN | mix-6.1.4/deploy | container | 260 - org.apache.aries.jpa.container - 1.0.2 | Error creating EntityManagerFactory
org.hibernate.event.service.spi.EventListenerRegistrationException: Duplicate event listener found
at org.hibernate.event.service.internal.EventListenerGroupImpl.listenerShouldGetAdded(EventListenerGroupImpl.java:143)[252:org.hibernate.core:4.3.6.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.appendListener(EventListenerGroupImpl.java:108)[252:org.hibernate.core:4.3.6.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.appendListeners(EventListenerGroupImpl.java:102)[252:org.hibernate.core:4.3.6.Final]
at org.hibernate.event.service.internal.EventListenerRegistryImpl.appendListeners(EventListenerRegistryImpl.java:172)[252:org.hibernate.core:4.3.6.Final]
at org.hibernate.envers.event.spi.EnversIntegrator.integrate(EnversIntegrator.java:84)[254:org.hibernate.envers:4.3.6.Final]
at Proxy7c321f84_ab1f_4b15_a78a_66080ada210e.integrate(Unknown Source)[:]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:312)[252:org.hibernate.core:4.3.6.Final]
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1857)[252:org.hibernate.core:4.3.6.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)[251:org.hibernate.entitymanager:4.3.6.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)[251:org.hibernate.entitymanager:4.3.6.Final]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)[252:org.hibernate.core:4.3.6.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)[251:org.hibernate.entitymanager:4.3.6.Final]
at org.hibernate.osgi.OsgiPersistenceProvider.createContainerEntityManagerFactory(OsgiPersistenceProvider.java:112)[253:org.hibernate.osgi:4.3.6.Final]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.createEntityManagerFactories(EntityManagerFactoryManager.java:336)[260:org.apache.aries.jpa.container:1.0.2]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.registerEntityManagerFactories(EntityManagerFactoryManager.java:239)[260:org.apache.aries.jpa.container:1.0.2]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.bundleStateChange(EntityManagerFactoryManager.java:182)[260:org.apache.aries.jpa.container:1.0.2]
at org.apache.aries.jpa.container.impl.PersistenceBundleManager.modifiedBundle(PersistenceBundleManager.java:301)[260:org.apache.aries.jpa.container:1.0.2]
at org.apache.aries.util.tracker.hook.BundleHookBundleTracker$Tracked.customizerModified(BundleHookBundleTracker.java:500)[9:org.apache.aries.util:1.1.1]
at org.apache.aries.util.tracker.hook.BundleHookBundleTracker$Tracked.customizerModified(BundleHookBundleTracker.java:433)[9:org.apache.aries.util:1.1.1]
at org.apache.aries.util.tracker.hook.BundleHookBundleTracker$AbstractTracked.track(BundleHookBundleTracker.java:725)[9:org.apache.aries.util:1.1.1]
at org.apache.aries.util.tracker.hook.BundleHookBundleTracker$Tracked.bundleChanged(BundleHookBundleTracker.java:463)[9:org.apache.aries.util:1.1.1]
at org.apache.aries.util.tracker.hook.BundleHookBundleTracker$BundleEventHook.event(BundleHookBundleTracker.java:422)[9:org.apache.aries.util:1.1.1]
at org.apache.felix.framework.util.SecureAction.invokeBundleEventHook(SecureAction.java:1103)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.util.EventDispatcher.createWhitelistFromHooks(EventDispatcher.java:695)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.util.EventDispatcher.fireBundleEvent(EventDispatcher.java:483)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.Felix.fireBundleEvent(Felix.java:4403)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.Felix.startBundle(Felix.java:2092)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:955)[org.apache.felix.framework-4.2.1.jar:]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.startBundle(DirectoryWatcher.java:1243)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.startBundles(DirectoryWatcher.java:1215)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.doProcess(DirectoryWatcher.java:506)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.process(DirectoryWatcher.java:355)[7:org.apache.felix.fileinstall:3.5.2]
at org.apache.felix.fileinstall.internal.DirectoryWatcher.run(DirectoryWatcher.java:307)[7:org.apache.felix.fileinstall:3.5.2]
I created two simple bundles that can reproduce the issue based on the standard managed-jpa example code.
First 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.hibernate.osgi</groupId>
<artifactId>managed-jpa-test1</artifactId>
<version>1.0.0</version>
<packaging>bundle</packaging>
<dependencies>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.enterprise</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.karaf.shell</groupId>
<artifactId>org.apache.karaf.shell.console</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>4.3.6.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>3.0.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>org.hibernate.osgi.managed-jpa-test1</Bundle-SymbolicName>
<Bundle-Name>managed-jpa-test1</Bundle-Name>
<Bundle-Version>1.0.0</Bundle-Version>
<Private-Package>
org.hibernate.osgitest,
org.hibernate.osgitest.entity
</Private-Package>
<Import-Package>
org.hibernate.jpa,
org.apache.felix.service.command,
org.apache.felix.gogo.commands,
org.apache.karaf.shell.console;resolution:=optional;version="[3.0,4)",
org.apache.karaf.shell.commands;resolution:=optional;version="[3.0,4)",
javax.persistence;version="[1.0.0,2.1.0]",
<!-- Needed for proxying's Javassist enhancement during runtime -->
org.hibernate.proxy,
javassist.util.proxy,
*
</Import-Package>
<Meta-Persistence>META-INF/persistence.xml</Meta-Persistence>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>
Second 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.hibernate.osgi</groupId>
<artifactId>managed-jpa-test2</artifactId>
<version>1.0.0</version>
<packaging>bundle</packaging>
<dependencies>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.enterprise</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.karaf.shell</groupId>
<artifactId>org.apache.karaf.shell.console</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>4.3.6.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>3.0.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>org.hibernate.osgi.managed-jpa-test2</Bundle-SymbolicName>
<Bundle-Name>managed-jpa-test2</Bundle-Name>
<Bundle-Version>1.0.0</Bundle-Version>
<Private-Package>
org.hibernate.osgitest2,
org.hibernate.osgitest2.entity
</Private-Package>
<Import-Package>
org.hibernate.jpa,
org.apache.felix.service.command,
org.apache.felix.gogo.commands,
org.apache.karaf.shell.console;resolution:=optional;version="[3.0,4)",
org.apache.karaf.shell.commands;resolution:=optional;version="[3.0,4)",
javax.persistence;version="[1.0.0,2.1.0]",
<!-- Needed for proxying's Javassist enhancement during runtime -->
org.hibernate.proxy,
javassist.util.proxy,
*
</Import-Package>
<Meta-Persistence>META-INF/persistence.xml</Meta-Persistence>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>
First blueprint.xml:
<blueprint default-activation="eager"
xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://aries.apache.org/xmlns/jpa/v1.0.0"
xmlns:tx="http://aries.apache.org/xmlns/transactions/v1.0.0">
<bean id="dpService" class="org.hibernate.osgitest.DataPointServiceImpl">
<jpa:context unitname="managed-jpa-test1" property="entityManager"/>
<tx:transaction method="*" value="Required"/>
</bean>
<service ref="dpService" interface="org.hibernate.osgitest.DataPointService"/>
<bean id="integrator" class="org.hibernate.envers.event.spi.EnversIntegrator" />
<service ref="integrator" interface="org.hibernate.integrator.spi.Integrator" />
<command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">
<command>
<action class="org.hibernate.osgitest.command.AddCommand">
<property name="dpService" ref="dpService"/>
</action>
</command>
</command-bundle>
</blueprint>
Second blueprint.xml:
<blueprint default-activation="eager"
xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://aries.apache.org/xmlns/jpa/v1.0.0"
xmlns:tx="http://aries.apache.org/xmlns/transactions/v1.0.0">
<bean id="dpService2" class="org.hibernate.osgitest2.DataPointService2Impl">
<jpa:context unitname="managed-jpa-test2" property="entityManager2"/>
<tx:transaction method="*" value="Required"/>
</bean>
<service ref="dpService2" interface="org.hibernate.osgitest2.DataPointService2"/>
<bean id="integrator" class="org.hibernate.envers.event.spi.EnversIntegrator" />
<service ref="integrator" interface="org.hibernate.integrator.spi.Integrator" />
<command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">
<command>
<action class="org.hibernate.osgitest2.command.AddCommand2">
<property name="dpService2" ref="dpService2"/>
</action>
</command>
</command-bundle>
</blueprint>
DataPoint.java:
#Entity
#Audited
public class DataPoint {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
DataPoint2.java:
#Entity
#Audited
public class DataPoint2 {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
First 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"
version="1.0">
<persistence-unit name="managed-jpa-test1" transaction-type="JTA">
<jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=test1/mssql)</jta-data-source>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
<property name="hibernate.archive.autodetection" value="class"/>
</properties>
</persistence-unit>
</persistence>
Second 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"
version="1.0">
<persistence-unit name="managed-jpa-test2" transaction-type="JTA">
<jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=test2/mssql)</jta-data-source>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
<property name="hibernate.archive.autodetection" value="class"/>
</properties>
</persistence-unit>
</persistence>
DataPointService.java:
public interface DataPointService {
public void add(DataPoint dp);
}
DataPointServiceImpl.java:
public class DataPointServiceImpl implements DataPointService {
private EntityManager entityManager;
public void add(DataPoint dp) {
entityManager.persist( dp );
entityManager.flush();
}
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
}
AddCommand.java:
#Command(scope = "dp1", name = "add")
public class AddCommand implements Action {
#Argument(index=0, name="Name", required=true, description="Name", multiValued=false)
String name;
private DataPointService dpService;
public void setDpService(DataPointService dpService) {
this.dpService = dpService;
}
public Object execute(CommandSession session) throws Exception {
DataPoint dp = new DataPoint();
dp.setName( name );
dpService.add( dp );
return null;
}
}
DataPointService2.java:
public interface DataPointService2 {
public void add(DataPoint2 dp);
}
DataPointService2Impl.java:
public class DataPointService2Impl implements DataPointService2 {
private EntityManager entityManager2;
public void add(DataPoint2 dp) {
entityManager2.persist( dp );
entityManager2.flush();
}
public EntityManager getEntityManager2() {
return entityManager2;
}
public void setEntityManager2(EntityManager entityManager2) {
this.entityManager2 = entityManager2;
}
}
AddCommand2.java:
#Command(scope = "dp2", name = "add")
public class AddCommand2 implements Action {
#Argument(index=0, name="Name", required=true, description="Name", multiValued=false)
String name;
private DataPointService2 dpService2;
public void setDpService2(DataPointService2 dpService2) {
this.dpService2 = dpService2;
}
public Object execute(CommandSession session) throws Exception {
DataPoint2 dp = new DataPoint2();
dp.setName( name );
dpService2.add( dp );
return null;
}
}
datasource-test1.xml:
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
<bean id="test1DataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver"/>
<property name="url" value="jdbc:jtds:sqlserver://localhost:1433;databaseName=XXXX;tds=8.0;lastupdatecount=true;uselobs=false"/>
<property name="username" value="sa"/>
<property name="password" value="XXXXX"/>
</bean>
<service interface="javax.sql.DataSource" ref="test1DataSource">
<service-properties>
<entry key="osgi.jndi.service.name" value="test1/mssql"/>
</service-properties>
</service>
</blueprint>
datasource-test2.xml
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
<bean id="test2DataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver"/>
<property name="url" value="jdbc:jtds:sqlserver://localhost:1433;databaseName=XXXX;tds=8.0;lastupdatecount=true;uselobs=false"/>
<property name="username" value="sa"/>
<property name="password" value="XXXXX"/>
</bean>
<service interface="javax.sql.DataSource" ref="test2DataSource">
<service-properties>
<entry key="osgi.jndi.service.name" value="test2/mssql"/>
</service-properties>
</service>
</blueprint>
I think that is all the relevant files. Probably more than I need, but better safe than sorry.
We want to be able to offer the bundles as separate solutions that a customer can use depending on their needs. Like one HL7 bundle and a WebService bundle and so forth.
If it is only possible to have one bundle using Envers, then we will have to develop an additional bundle that does the database updates, but it would be better if the bundles could be self-contained.
You are offering the envers extension using
<bean id="integrator" class="org.hibernate.envers.event.spi.EnversIntegrator" />
<service ref="integrator" interface="org.hibernate.integrator.spi.Integrator" />
As this is an OSGi service it will be picked up by all bundles. So the bundle that starts last will see both and complain. Try to put this in its own bundle to make sure it is only registered once.

Java hibernate JPA error with JUnit Testing

I am using hibernate in my Java EE application in combination with my Wildfly server to persist my Classes in a mysql Database.
So far this works fine but now I am writing unit tests and I am getting crazy about some error which I get.
I would like to test my DAO-Layer in my Unit-Tests but I get these errors:
Caused by: org.hibernate.engine.jndi.JndiException: Error parsing JNDI name [java:/MySqlDS]
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
my persistence.xml ist this:
<?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="primary">
<jta-data-source>java:/MySqlDS</jta-data-source>
<class>org.se.bac.data.Employee</class>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/empdb?useSSL=false"/>
<property name="hibernate.connection.username" value="student"/>
<property name="hibernate.connection.password" value="student"/>
<!--
SQL stdout logging
-->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="use_sql_comments" value="true"/>
</properties>
</persistence-unit>
</persistence>
So, Here I am using a jta-data-source> as you can see.
If I remove this line my tests are going fine! But I can not build my project with maven anymore.
Error:
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [com.mysql.jdbc.Driver]
Caused by: java.lang.ClassNotFoundException: Could not load requested class : com.mysql.jdbc.Driver"}}
He can not find the datasource because I removed the line in my persistence.xml
How can I manage to get both run in my application. The tests and of course the maven build?
Here is my test: (Setup is already causing the error):
package org.se.bac.data.dao;
import java.util.List;
import javax.persistence.EntityManager;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.se.bac.data.model.Employee;
public class EmployeeDAOTest
{
private static final JdbcTestHelper JDBC_HELPER = new JdbcTestHelper();
private final static JpaTestHelper JPA_HELPER = new JpaTestHelper();
private EntityManager em = JPA_HELPER.getEntityManager("primary");
private EmpDAO dao;
#BeforeClass
public static void init()
{
JDBC_HELPER.executeSqlScript("sql/test/dropEmployeeTable.sql");
JDBC_HELPER.executeSqlScript("sql/test/createEmployeeTable.sql");
}
#AfterClass
public static void destroy()
{
//JDBC_HELPER.executeSqlScript("sql/test/dropEmployeeTable.sql");
}
#Before
public void setUp()
{
JDBC_HELPER.executeSqlScript("sql/test/dropEmployeeTable.sql");
JDBC_HELPER.executeSqlScript("sql/test/createEmployeeTable.sql");
dao = new EmpDAOImpl();
dao.setEm(em);
JPA_HELPER.txBegin();
Employee emp2 = new Employee();
emp2.setFirstname("Max");
emp2.setLastname("Muster");
emp2.setHiredate("23-12-1991");
dao.insert(emp2);
}
And JPAHELPER Class:
package org.se.bac.data.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class JpaTestHelper
{
/*
* Property: persistenceUnitName
*/
private String persistenceUnitName;
public String getPersistenceUnitName()
{
return persistenceUnitName;
}
public void setPersistenceUnitName(String persistenceUnitName)
{
if(persistenceUnitName == null || persistenceUnitName.length() == 0)
throw new IllegalArgumentException("Illegal parameter persistenceUnitName = " + persistenceUnitName);
this.persistenceUnitName = persistenceUnitName;
}
/*
* Get an instance of the EntityManagerFactory.
*/
protected EntityManagerFactory getEnityManagerFactory()
{
if(persistenceUnitName == null)
throw new IllegalStateException("PersistenceUnitName must be set!");
return Persistence.createEntityManagerFactory(persistenceUnitName);
}
/*
* Manage an EntityManager.
*/
private EntityManager em;
public EntityManager getEntityManager()
{
if(em == null)
{
em = getEnityManagerFactory().createEntityManager();
}
return em;
}
public EntityManager getEntityManager(String persistenceUnitName)
{
setPersistenceUnitName(persistenceUnitName);
return getEntityManager();
}
public void closeEntityManager()
{
if(em != null)
em.close();
}
/*
* Handle Transactions
*/
protected void txBegin()
{
EntityTransaction tx = em.getTransaction();
tx.begin();
}
protected void txCommit()
{
EntityTransaction tx = em.getTransaction();
if(tx.getRollbackOnly())
{
tx.rollback();
}
else
{
tx.commit();
}
}
protected void txRollback()
{
EntityTransaction tx = em.getTransaction();
tx.rollback();
}
}
and my DAO:
package org.se.bac.data.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.se.bac.data.model.Employee;
class EmpDAOImpl // package private
implements EmpDAO
{
#PersistenceContext
private EntityManager em;
/*
* CRUD methods
*/
public Employee findById(int id)
{
System.out.println("empdaoimpl ID " + id);
return em.find(Employee.class, id);
}
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
}
Wildfly Datasource:
<datasources>
<datasource jta="true" jndi-name="java:/MySqlDS" pool-name="MySqlDS" enabled="true" use-ccm="false">
<connection-url>jdbc:mysql://localhost:3306/empdb?useSSL=false</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<driver>mysql-connector-java-5.1.44-bin.jar_com.mysql.jdbc.Driver_5_1</driver>
<security>
<user-name>student</user-name>
<password>student</password>
</security>
<validation>
<valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker"/>
<background-validation>true</background-validation>
<exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter"/>
</validation>
</datasource>
</datasources>
He can not find the datasource because I removed the line in my persistence.xml
How can I manage to get both run in my application.
The problem is that the data source is managed by Wildfly which is not available on your test environment. So what you could do is define two separate persistence units (one for your production code and the other for the test) as follows:
<?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="primary">
<jta-data-source>java:/MySqlDS</jta-data-source>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<!-- SQL stdout logging -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="use_sql_comments" value="true"/>
</properties>
</persistence-unit>
<persistence-unit name="testPU" transaction-type="RESOURCE_LOCAL">
<class>org.se.bac.data.Employee</class>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/empdb?useSSL=false"/>
<property name="hibernate.connection.username" value="student"/>
<property name="hibernate.connection.password" value="student"/>
<!-- SQL stdout logging -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="use_sql_comments" value="true"/>
</properties>
</persistence-unit>
</persistence>
and then in your EmployeeDAOTest class modify the following line as:
private EntityManager em = JPA_HELPER.getEntityManager("testPU");
Note:
I removed the JDBC connection properties from the primary persistence unit because you don't need them as you already have the data source there on Wildfly.

How to configure Hibernate+JPA with Configuration?

I am new to JPA . Earlier I know Hibernate. But as per the requirement, I need to enhance to Hibernate+JPA Configuration.
Please Look my configuration.
POJO:
package com.skc.order;
import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="blc_order")
public class Orders {
#Id
#Column(name="order_id")
Long orderId;
#Column(name="ORDER_NUMBER")
String orderNumber;
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public String getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}
}
Persistance.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="ExpensePersistentUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>tamSql</non-jta-data-source>
<class>com.skc.order.Orders</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/broadleaf" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"></property>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.password" value="root" />
<property name="hibernate.connection.username" value="mysql" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
EntityManagerTest Class :
package com.skc.order;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
public class EntityManagerTest {
/*#PersistenceContext(unitName = "ExpensePersistentUnit")
protected EntityManager em;*/
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ExpensePersistentUnit");
EntityManager em = emf.createEntityManager();
Query qry = em.createNativeQuery("select * from blc_order", Orders.class);
Orders order = em.find(Orders.class, 1512);
System.out.println(order.getOrderNumber());
}
}
Jar Added In the ClassPath :
antlr-2.7.7
dom4j-1.6.1
hibernate-commons-annotations-4.0.1.Final
hibernate-core-4.2.0.Final
hibernate-jpa-2.0-api-1.0.1.Final
hibernate-validator-4.3.1.Final
javassist-3.15.0-GA
jboss-logging-3.1.2.GA
jboss-logmanager-1.4.0.Final
jboss-transaction-api_1.1_spec-1.0.1.Final
log4j-jboss-logmanager-1.0.1.Final
slf4j-api-1.6.1
slf4j-log4j12-1.6.1
commons-logging-1.1.1
hibernate-3.2.3.ga
hibernate-entitymanager-3.3.2.GA
And I am getting exception like :
Exception in thread "main" java.lang.IllegalAccessError: tried to access method org.hibernate.cfg.Configuration.<init>(Lorg/hibernate/cfg/SettingsFactory;)V from class org.hibernate.ejb.Ejb3Configuration
at org.hibernate.ejb.Ejb3Configuration.<init>(Ejb3Configuration.java:134)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:124)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at com.skc.order.EntityManagerTest.main(EntityManagerTest.java:13)
Please Help me out to solve this Problem.
Thanks ...
For Hibernate-core use 3.6.3 version..
This error used to come due to the class version mismatch. So I also got the same error just few minutes back. I just changed the version and that error is gone now. I am using hibernate core 3.6.3.FINAL with spring version 4.1.7.RELEASE. Hope this will work for you too. If you have doubt please comment.

No Persistence provider for EntityManager named cache

Message.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
#Entity
#Table(name="MESSAGES")
#Cache(region = "messages", usage = CacheConcurrencyStrategy.READ_WRITE)
public class Message {
Message(){
}
Message(String message){
message_text=message;
}
#Id #GeneratedValue
#Column(name="MESSAGE_ID")
public Long id;
#Column(name="MESSAGE_TEXT")
public String message_text;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMessage_text() {
return message_text;
}
public void setMessage_text(String message_text) {
this.message_text = message_text;
}
}
Ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" />
<cache name="messages" maxElementsInMemory="10" eternal="true" overflowToDisk="false" />
</ehcache>
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
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="annotation">
<properties>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:#ebiz-dev-db-esb:1521:esbd"/>
<property name="hibernate.connection.username" value="CUST_INFO"/>
<property name="hibernate.connection.password" value="POUND987"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle9Dialect"/>
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="3000"/>
<property name="show_sql" value="true"/>
<property name="format_sql" value="true"/>
<property name="hibernate.cache.region.factory_class" value="net.sf.ehcache.hibernate.EhCacheRegionFactory"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.EhCacheProvider" />
<property name="hibernate.cache.provider_configuration_file_resource_path" value="ehcache.xml" />
</properties>
</persistence-unit>
</persistence>
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>HibernateWithAnnotation</groupId>
<artifactId>HibernateWithAnnotation</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>HibernateWithAnnotation</name>
<repositories>
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.6.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.5</version>
</dependency>
</dependencies>
</project>
TestAnnotation class
package com.annotation;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
public class TestAnnotation {
public static void main(String args[]){
EntityManagerFactory factory=Persistence.createEntityManagerFactory("annotation");
EntityManager manager=factory.createEntityManager();
EntityTransaction transaction=manager.getTransaction();
transaction.begin();
manager.persist(new Message("My Entity Test One More Example New"));
transaction.commit();
System.out.println("First time calling Message Object");
getMessage(manager,23);
System.out.println("Second time calling Message Object");
getMessage(manager,23);
factory.close();
}
public static void getMessage(EntityManager manager,long id){
EntityTransaction transaction1=manager.getTransaction();
transaction1.begin();
Query q=manager.createQuery("from Message m where m.id="+id);
Message m=(Message)q.getSingleResult();
System.out.println(m.getMessage_text());
transaction1.commit();
}
}
My problem is: When I run this code from TestAnnotation class via main method I get the following error:
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named annotation
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:32)
at com.annotation.TestAnnotation.main(TestAnnotation.java:10)
Your persistence-unit is incomplete. See the documentation.
Add <class>com.annotation.TestAnnotation</class> to your persistence-unit node in your persistence.xml file before the properties node.
You likely also need transaction-type="RESOURCE_LOCAL" on you persistence-unit node.
For example, my working version uses:
pom.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.5.4-Final</version>
<scope>runtime</scope>
</dependency>
persistenct.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
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="MyPU" transaction-type="RESOURCE_LOCAL">
<class>com.myentities.MyEntity</class>
<properties>
<property name="hibernate.cache.use_query_cache" value="false"/>
<property name="hibernate.cache.use_second_level_cache" value="false"/>
<!-- These lines can be used for debugging -->
<!--<property name="show_sql" value="true"/>-->
<!--<property name="format_sql" value="true"/>-->
</properties>
</persistence-unit>
</persistence>
My DAO class:
private EntityManager m_entityManagerFactory;
// initializer (this is costly, do only 1x on post construct)
m_entityManager = createEntityManagerFactory( jdbcDriverName, jdbcURL, dbUserName, dbPassword );
// when needed (less costly, can do 1x or whenever you need the entity manager)
EntityManager entityManager = m_entityManagerFactory.createEntityManager();
private EntityManagerFactory createEntityManagerFactory (
#NotNull final String jdbcDriverName,
#NotNull final String jdbcURL,
#NotNull final String dbUserName,
#NotNull final String dbPassword )
{
final Properties properties = new Properties();
properties.put( "hibernate.connection.driver_class", jdbcDriverName );
properties.put( "hibernate.connection.url", jdbcURL );
properties.put( "hibernate.connection.username", dbUserName );
properties.put( "hibernate.connection.password", dbPassword );
return Persistence.createEntityManagerFactory( "AlertProcessorPU", properties );
}

Categories

Resources