AbstractMethodError thrown at runtime with Hibernate/JPA - java

I am absolutely new to Hibernate and JPA and I have the following problem trying to implement a tutorial that uses Hibernate following the JPA specification.
I have these classes:
1) A HelloWorldClient class, the entry point of my application, containing the main method:
package client;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import entity.Message;
public class HelloWorldClient {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("merging");
EntityManager em = emf.createEntityManager();
EntityTransaction txn = em.getTransaction();
txn.begin();
Message message = new Message("Hello"); //transient state
em.persist(message); //persistent state
txn.commit();
em.close();
message.setText("Hi"); //modifying the detached state of message
EntityManager em2 = emf.createEntityManager();
EntityTransaction txn2 = em2.getTransaction();
txn2.begin();
//the returned mergedMessage is a persistent object
//any changes to mergedMessage will be dirty checked when the txn2 will be committed and updated in the database
Message mergedMessage = em2.merge(message);
txn2.commit();
em2.close();
//Detaching objects explicitly
/*
EntityManager em3 = emf.createEntityManager();
EntityTransaction txn3 = em.getTransaction();
txn3.begin();
Message msg = new Message("Howdy"); //transient state
em.persist(msg); //persistent state
em.detach(msg); //detaching the message object explicitly
txn3.commit();
em3.close();
*/
}
}
2) A Message entity class that is mapped on a database table:
package entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="message")
public class Message {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="ID")
private Long id;
#Column(name="TEXT")
private String text;
public Message() {}
public Message(String text) {
this.text = text;
}
public void setText(String text) {
this.text = text;
}
}
3) And finally I have the persistence.xml configuration file in the META-INF folder of my application:
<?xml version="1.0" encoding="UTF-8"?>
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="merging" transaction-type="RESOURCE_LOCAL">
<properties>
<!-- Database connection settings -->
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/hello-world" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="myPassword" />
<!-- SQL dialect -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<!-- Create/update tables automatically using mapping metadata -->
<property name="hibernate.hbm2ddl.auto" value="update" />
<!-- Pretty print the SQL in the log file and console -->
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
When I try to run my application, I obtain this error message in the stacktrace:
Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar
Exception in thread "main" java.lang.AbstractMethodError: org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.getConfigurationValues()Ljava/util/Map;
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:404)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:75)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at client.HelloWorldClient.main(HelloWorldClient.java:14)

I've had the same issue when trying to do hibernate tutorials. It usually means that there are compatibility issues between the jar files you added to your build path.
in your case, it would seem that
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.getConfigurationValues()
appears in the latest version as an abstract method, hence the above error. Try changing the JPA jar to a previous version, that will probably solve the issue; that's what helped in my case.

I had the same problem and when I checked the Maven repository for hibernate-entity manager I found I wasn't specifying the latest version in my POM.xml. Once I updated to the latest version it fixed the problem.

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

How to Initialize persistance.xml variables on program start?

Basically I am doing a Insert inside a PostgreSQL database, but since I have multiple databases I have to change the configurations based on each environment.
The thing is that I used a not really good way to do so, since everytime I do a insert, I replace all variables, which is ultra slow and definetly not a good way to achiev that.
How would I be able to do the same inserts, but having it configured while my Api started?
Here's what i'm currently doing:
package br.jus.tjba.dje.local.service;
import br.jus.tjba.dje.local.entity.Conteudo;
import br.jus.tjba.dje.local.repository.ConteudoRepository;
import br.jus.tjba.tjfw4.core.service.AbstractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.persistence.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
#Service
public class ConteudoService extends AbstractService {
#Autowired
private ConteudoRepository conteudoRepository;
public EntityTransaction insertInDb(String something, String somethingElse) {
Map<String, String> env = System.getenv();
Map<String, Object> configOverrides = new HashMap<>();
// Here I change my persistance.xml configs
for(Map.Entry<String, String> entry: env.entrySet()) {
if (entry.getKey().contains("DATABASE_URL")) {
configOverrides.put("javax.persistence.jdbc.url", env.get(entry.getValue()));
} else if (entry.getKey().contains("DATABASE_USER")) {
configOverrides.put("javax.persistence.jdbc.user", env.get(entry.getValue()));
} else if (entry.getKey().contains("DATABASE_PASSWORD")) {
configOverrides.put("javax.persistence.jdbc.password", env.get(entry.getValue()));
}
}
// Cria um factory dando override nas variáveis.
EntityManagerFactory factory = Persistence.createEntityManagerFactory("default", configOverrides);
EntityManager conteudoManager = factory.createEntityManager();
Query query = conteudoManager.createNativeQuery("INSERT INTO something(" +
"SOMETHING," +
"SOMETHING_ELSE)" +
" VALUES (" +
":something," +
":somethingElse)");
conteudoManager.getTransaction().begin();
query.setParameter("something", something);
query.setParameter("somethingElse", somethingElse);
query.executeUpdate();
return conteudoManager.getTransaction();
}
public Conteudo getContent() {
return conteudoRepository.getContent();
}
}
Also my 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="default" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="javax.persistence.jdbc.url" value="url" />
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.password" value="password" />
<property name="javax.persistence.jdbc.user" value="login" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>

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.

Hibernate Mapping Exception : Unknown entity: org.hibernate.test.akashtest.UserDetails

Mapping classes <mapping class="org.hibernate.test.akashtest.UserDetails"/>.
The configuration file is not able to pick the UserDetails class.
Added Annotation Class in configuration, packages location as well.
How can I fix this?
Code:
package org.hibernate.test.akashtest;
import java.lang.annotation.Annotation;
import javax.persistence.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.fasterxml.classmate.AnnotationConfiguration;
import com.fasterxml.classmate.AnnotationInclusion;
public class hibernate_1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
UserDetails user=new UserDetails();
user.setuserId(1);
user.setuserName("First User");
SessionFactory sessionFactory= new Configuration().addAnnotatedClass(org.hibernate.test.akashtest.UserDetails.class).configure("/org/hibernate/test/akashtest/hibernate.cfg.xml").buildSessionFactory();
Session session=sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
/// My hibernate.cfg.xml
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration
>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>
<property name="connection.username">postgres</property>
<property name="connection.password">akash5758</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping package="org.hibernate.test.akashtest"/>
<mapping class="org.hibernate.test.akashtest.UserDetails"/> /*MAPPING CLASS*/
</session-factory>
</hibernate-configuration>
/// My UserDetails.java
package org.hibernate.test.akashtest;
public class UserDetails {
private int userId;
private String userName;
public int getUserId()
{
return userId;
}
public void setuserId(int userId)
{
this.userId=userId;
}
public String getuserName()
{
return userName;
}
public void setuserName(String userName)
{
this.userName=userName;
}
}
You have to add #Entity annotation in your UserDetails class.

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.

Categories

Resources