Unknown Entity exception while running hibernate 5.0.1 program - java

I am getting the below error while running my Hibernate program on Hibernate 5.0.1:
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.abhinav.hibernate.UserDetails
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1542)
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:225)
at org.hibernate.event.internal.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:499)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:99)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:778)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:751)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:756)
at com.abhinav.hibernate.main.HibernateTest.main(HibernateTest.java:26)
Below is the configuration file:
<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">password</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</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 resource="com.abhinav.hibernate.UserDetails"/>
</session-factory>
The main class:
package com.abhinav.hibernate.main;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.abhinav.hibernate.UserDetails;
public class HibernateTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
UserDetails userDetails = new UserDetails();
userDetails.setUserId(1);
userDetails.setUserName("Abhinav");
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
Session session = sessionFactory.openSession();
session.getTransaction();
System.out.println("Session: "+session);
// session.save(userDetails);
session.persist(userDetails);
System.out.println("Session after save: "+session+" User details: "+userDetails.getUserId()+" "+userDetails.getUserName());
session.getTransaction().commit();
}
Entity Class: UserDetails with fields userId and userName.

There are two problems there
You need to use
<mapping class="com.abhinav.hibernate.UserDetails"/>
if you use annotations for mapping (resource is used for xml mappings).
You can't use Hibernate 4 way for building a session factory for Hibernate 5. The correct way:
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Refer for details
Hibernate 5 :- org.hibernate.MappingException: Unknown entity

Related

Anybody can check for me what wrong when I try to connect PostgreSQL by using Hibernate

First, let me list the things I have used:
Eclipse JEE version 2021-03
Apache Tomcat Server 9
Hibernate ORM version 5.2.18.Final
PostgreSQL 14
Java 8
Some driver I have used: the required in lib of Hibernate ORM, postgresql-42.2.22.jar, jaxb-api-1.0.jar
Second is my code:
In the main class, I use it to run the application I let the name of class is CreateStudentDemo in the phucldh.Demo package in the src folder
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// create a student object
Student tempStudent = new Student("Le", "Phuc", "phucldh.work#gmail.com");
// start a transaction
session.beginTransaction();
// save the student object
session.save(tempStudent);
// commit transaction
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("Create student demo error: " + e.getMessage());
} finally {
factory.close();
}
}
And to connect to PostgreSQL I have a configuration file hibernate.cfg.xml in the src folder and the content of this file:
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/HibernateLearn</property>
<property name="connection.username">postgres</property>
<property name="connection.password">********</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Set the current session context -->
<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 the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
</session-factory>
That all I have done but when I running I have a problem:
INFO: HHH000206: hibernate.properties not found
Exception in thread "main" java.lang.NoSuchMethodError: 'javax.xml.bind.JAXBContext javax.xml.bind.JAXBContext.newInstance(java.lang.Class[])'
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:122)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
at org.hibernate.cfg.Configuration.configure(Configuration.java:258)
at phucldh.Demo.CreateStudentDemo.main(CreateStudentDemo.java:15)
And I see that line 15 of CreateStudentDemo.java is the line about
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
So I hope that anybody can help me find what I have wrong. Thank everybody very much. Hope all have a nice day.

Retrieve data from database after OneToMany Unidirectional Realtion

So i got this project where i m storing a "Categorie" class in data base with onetomany relationship with "SousCategorie" class which works fine and it creates a table named "categorie_sous_categories"
when i tired to retrieve the data from categorie_sous_categories table an error occured that this class is mapped which hibernate had created the table bu i didin't declare the class in my program
my program structure:
the exception log:
Exception in thread "main" java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Categorie_sous_categories is not mapped [select categorie_matricule from categorie_sous_categories]
the code i try to run:
SessionFactory sessionFactory = new Configuration().
configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
List<String> categorieList = session.createQuery("select categorie_matricule from categorie_sous_categories").list();
for (String produit:categorieList){
System.out.println(produit);
}
session.getTransaction().commit();
session.close();
the table i try to retrive data from:
my hibernate.cfg.xml file:
<!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:postgresql://localhost:5432/DevIT</property> <!-- BD Mane -->
<property name="connection.driver_class">org.postgresql.Driver</property> <!-- DB Driver -->
<property name="connection.username">postgres</property> <!-- DB User -->
<property name="connection.password">test123</property> <!-- DB Password -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property> <!-- DB Dialect -->
<property name="hbm2ddl.auto">update</property> <!-- create / create-drop / update -->
<property name="show_sql">true</property> <!-- Show SQL in console -->
<property name="format_sql">true</property> <!-- Show SQL formatted -->
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="CoreApp.Categorie"/>
<mapping class="CoreApp.SousCategorie"/>
<mapping class="CoreApp.Produit"/>
</session-factory>
</hibernate-configuration>
try select categorie_matricule from Categorie, it will return the expected result.
Also, exception is self explanatory, table categorie_sous_categories is not mapped with any Entity/Class , it's a mapping table. And it shouldn't be fetched directly, any query you want to run on this table, can be changed - where original classes Categorie and SousCategorie are being used.

Hibernate - Could not load requested class : org.mariadb.jdbc.Driver

So my issues is pretty basic. I'm just running a simple hibernate web application that sends a new entry to my SQL MariaDB. When I run the application I get an error message saying the requested class could not be loaded. What doesn't make sense is I have the .jar files in my library and my other test file runs fine. For this project I'm using Intellij IDEA.
hibernate.cfg.xml
<!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>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mariadb.jdbc.Driver</property>
<property name="connection.url">jdbc:mariadb://localhost:3306/hb_student_tracker</property>
<property name="connection.username">hbstudent</property>
<property name="connection.password"></property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MariaDB53Dialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
CreateStudentDemo
import com.luv2code.hibernate.demo.entity.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class CreateStudentDemo {
public static void main(String[] args) {
//create session factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// create a student object
System.out.println("Creating new student object...");
Student tempStudent = new Student(
"Paul", "Wall", "paul#luv2code.com");
// start a transaction
session.beginTransaction();
// save the student object
System.out.println("Saving the student...");
session.save(tempStudent);
// commit transaction
session.getTransaction().commit();
System.out.println("Done!");
}
finally {
factory.close();
}
}
I'm thinking the issue lies with the hibernate.xml file. Any help would be appreciated!
com.mariadb.jdbc.Driver
Could not load requested class : org.mariadb.jdbc.Driver

Running H2 embedded database in spring / hibernate

I am trying to create an spring boot application utilizing hibernate and h2. From what I have found online this can be done but I am having a problem starting the application. Hibernate is complaining that it cannot make a connection to the h2 database I have created.
Caused by: org.hibernate.HibernateException: Unable to make JDBC Connection [jdbc:h2:~/todo]
My theory is that the application needs to start for the database be available but hibernate is not letting the application start without the connection.
Am I on the right track with this theory, has there been similar issues that someone knows how to get around this?
Hibernate config
**<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<!--Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:h2:~/todo</property>
<property name="connection.username">username</property>
<property name="connection.password" />
<!--Set the database dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</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>
<!--Name the annotated Entity classes -->
<mapping class="com.todo.beans.User" />
</session-factory>
</hibernate-configuration>**
h2 config
import org.h2.server.web.WebServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class WebConfiguration {
#Bean
ServletRegistrationBean h2servletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
registrationBean.addUrlMappings("/console/*");
return registrationBean;
}
}
change following properties in hibernate config
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:mem:todo;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
</property>
Problem is with driver class; you may keep url as it is.
This sample project can help you.
https://github.com/dornala/HotelStackoverflow

Hibernate returns wrong results after updating rows

I am still a newbie with Hibernate but I am getting crazy. The thing is that after updating some Entities in the database Hibernate is not able to return me those changes. Also making SQL Queries return old values (Compared with the results I get from MySQLWorkbench)
I thought that it was a Cache problem, however in my hibernate.cnf,xml I have the following lines disabling 2nd line cache. Has anybody a solution for that problem?. I am using Hibernate v.4.3.1.
The conf file looks like:
<property name="connection.pool_size">3</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</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>
<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="hibernate.cache.use_query_cache">false</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">false</property>
<property name="show_comments">false</property>
I have a class to open the session factory:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
sessionFactory.getCache().evictAllRegions();
sessionFactory.getCache().evictEntityRegions();
sessionFactory.getCache().evictCollectionRegions();
sessionFactory.getCache().evictQueryRegions();
return sessionFactory;
}
}
UPDATE
I am using GWT+RequestFactory+Hibernate the thing is that changing the RequestProxy EntityProxy to ValueProxy (as I dont need an EntityProxy) is working fine. Could it be a problem of RequestFactory?

Categories

Resources