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
Related
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.
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.
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
I'm trying to learn how to use Java hibernate with mysql, and I'm having troubles running the example I've downloaded.
I'm getting the following error:
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.hibernate.exception.ErrorCodeConverter.handledNonSpecificException(ErrorCodeConverter.java:92)
at org.hibernate.exception.ErrorCodeConverter.convert(ErrorCodeConverter.java:80)
....
at org.hibernate.persister.entity.BasicEntityPersister.insert...
**Caused by: java.sql.SQLException: Syntax error or access violation message from server: "Access denied for user 'web'#'localhost' to database 'hibernatetutorial'"**
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:1997)
...
at org.hibernate.connection.DriverManagerConnectionProvider.getConnectio...
My configuration file includes the following code:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernatetutorial</property>
<property name="hibernate.connection.username">web</property>
<property name="hibernate.connection.password">web</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>
and the main function (which was downloaded from: http://www.roseindia.net/hibernate/runninge-xample.shtml) includes the following code:
public static void main(String[] args) {
Session session = null;
try{
// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
//Create new instance of Contact and set values in it by reading them from form object
System.out.println("Inserting Record");
Contact contact = new Contact();
contact.setId(6);
contact.setFirstName("Deepak");
contact.setLastName("Kumar");
contact.setEmail("deepak_38#yahoo.com");
session.save(contact);
System.out.println("Done");
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
session.flush();
session.close();
}
I've created the new "web" user with all the required permissions using:
CREATE USER 'web'#'localhost' IDENTIFIED BY 'web';
GRANT ALL PRIVILEGES ON hibernatetutorial.* TO web#localhost IDENTIFIED BY 'web';
And I've created the "hibernatetutorial" database.
Any idea what I'm doing wrong? I don't even know how to debug this.
Thanks,
Li
ON mydb.* TO web#localhost
shouldnt it be
ON hibernatetutorial.* TO web#localhost
I am using hibernate in spring app. but due to some problem i can't use spring injection so i manually have to declare the session factory like below
SessionFactory sessionFactory = new AnnotationConfiguration()
.configure("com/vaannila/service/hibernate.cfg.xml")
.buildSessionFactory();
Session session = sessionFactory.openSession();
Registration person = (Registration) session.get(Registration.class, 1);
As i am using annotation in entity class i get the following error
org.hibernate.MappingException: Unknown entity: com.vaannila.domain.Registration
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- We're using MySQL database so the dialect needs to MySQL as well-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- Enable this to see the SQL statements in the logs-->
<property name="show_sql">true</property>
<!-- This will drop our existing database and re-create a new one.
Existing data will be deleted! -->
<property name="hbm2ddl.auto">update</property>
<mapping class="com.vaannila.domain.Country" />
</session-factory>
</hibernate-configuration>
This could be because of the wrong FQCN entry for the class Registration or, you might be having
import javax.persistence.Entity;
instead of,
import org.hibernate.annotations.Entity;
Make sure your Registration class is annotated correctly with "javax.persistence.Entity".
I am just making sure, I have had same trouble when I missed that.
import javax.persistence.Entity;
#Entity
public class Registration{
}
Another reason could be that you class is not listed in hibernate.cfg.xml:
<mapping class="your.package.Registration"/>
Personally I haven't found the way to force standalone Hibernate scanning entity annotations, so I have pretty big list of mappings inside.