Hibernate Basic Example not working - java

I'm trying to implement a basic Hibernate example but I can't get it to work.
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class SimpleTest {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().
configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
Lecturer lecturer1 = new Lecturer();
lecturer1.setFirstName("Fatma");
lecturer1.setLastName("Meawad");
session.save(lecturer1);
tx.commit();
System.out.println
("The lecturer " + lecturer1.getFirstName()+ " "
+ lecturer1.getLastName()+" is successfully added to your database");
}
}
Everytime I try to run it I get:
Exception in thread "main" org.hibernate.HibernateException: Unable to
make JDBC Connection [jdbc:mysql//127.0.0.1:3306/sampledb] at
org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:77)
at
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
at
org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
at
org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
at
org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
at
org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
at
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
at
org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at SimpleTest.main(SimpleTest.java:11) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483) at
com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
I just started with Hibernate today but after a whole day trying I can't get an basic example (I tried other examples) to work. What did I forget?
EDIT: My hibernate.cfg.xml
<?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>
<!-- ________________ To be Edited _________________ -->
<property name="connection.url">jdbc:mysql//127.0.0.1:3306/sampledb</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<!-- _____________ End of To be Edited ______________ -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<!-- _________ Defining the Mapping Files ___________ -->
<mapping resource="Lecturer.hbm.xml" />
</session-factory>
</hibernate-configuration>

<property name="hibernate.hbm2ddl.auto">update</property>
add this in you hibernate.cfg.xml,and try it again

Related

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

Error message: Exception in thread "main" org.hibernate.HibernateException: Error accessing stax stream

I´m trying to create a MySQL database table by using hibernate but I get this error message:
Exception in thread "main" org.hibernate.HibernateException: Error accessing stax stream
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:107)
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:259)
at com.anika.hibernate.Main.main(Main.java:18)
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[2,34]
This answers do not solve my problem: Error connecting with database using hibernate
Exception in thread "main" org.hibernate.HibernateException: Error accessing stax stream
This is my Main.java file:
package com.anika.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args){
Student_Info student = new Student_Info();
student.setName("Anika");
student.setRollNo(1);
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(student);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
}
My 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, 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>.
-->
<hibernate-configuration
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernatetutorials</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.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 class="com.anika.hibernate.Stundent_Info"/>
</session-factory>
</hibernate-configuration>
Thank you for your help
I faced the same issue. It turns out that system is not able to access the hibernate-configuration-3.0.dtd from the url provided.
<DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
So, I referenced it from the local system.
<!DOCTYPE hibernate-configuration SYSTEM
"classpath://org/hibernate/hibernate-configuration-3.0.dtd">
Worked well for me. Hope it helps!
cleared the space at the begining of hibernate.cfg.xml file. lt worked
<?xml version="1.0" encoding="UTF-8"?>
You need to close the tag <hibernate-configuration.
<hibernate-configuration>
There is not the ! character in the DOCTYPE:
<DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
Should be
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
The issue for me was the lack of HTTPS.
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-config">
I changed to:
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "https://www.hibernate.org/dtd/hibernate-config">
That fixed the issue.

abstractMethod error in hibernate 4.1

I am trying with hibernate 4.1 . I configure settings by seeing this but still, I am getting session factory impl Abstract method error.
Here is my code and I am using maven for downloading jars
hibernate.cfg.xml
<?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>
<property name="hibernate.archive.autodetection">class,hbm</property>
<property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="hibernate.connection.username">SA</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping class="main.java.entity.Advocate"></mapping>
<mapping class="main.java.entity.Case"></mapping>
</session-factory>
</hibernate-configuration>
This my config class:
package main.java.service;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import main.java.businessTier.CaseTO;
import main.java.entity.Advocate;
import main.java.entity.Case;
public class LegalService {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()). buildServiceRegistry();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session;
public int registerCase(CaseTO caseTO) {
session=sessionFactory.openSession();
session.beginTransaction();
Case c = new Case();
Advocate a = new Advocate();
a.setAdvocateId(caseTO.getAdvocateId());
c.setAdvocate(a);
c.setClientAge(caseTO.getClientAge());
c.setClientName(caseTO.getClientName());
c.setDate(caseTO.getDate());
c.setDescription(caseTO.getDescription());
session.persist(c);
session.getTransaction().commit();
return c.getCaseNo();
}
}
Error:
Exception in thread "main" java.lang.AbstractMethodError
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:306)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1744)
at main.java.service.LegalService.<init>(LegalService.java:23)
hibernate-envers dependency in your pom.xml is creating issue. Please remove hibernate-envers dependency from you pom.xml
Use only hibernate-core and hsql dependency.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.4.Final</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.3.3</version>
</dependency>
It will work then. Let me know, if it worked or not. At my end it worked.

Connection refused when trying to connect to mysql using hibernate

I am trying to connect to mysql database using hibernate from the cfg file as
<?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:3306/test</property>
<property name="hibernate.connection.username">
root</property>
<property name="hibernate.connection.password">
root</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="Employee.hbm.xml" />
</session-factory>
</hibernate-configuration>
private static SessionFactory factory;
public static void main(String[] args) {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
ex.fillInStackTrace();
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
Though my connection-string,username,password are correct and the same are working fine in other project with basic jdbc connection, But when I try it using hibernate I am getting this error on console
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.hibernate.ManageEmployee.main(ManageEmployee.java:21)
Caused by: org.hibernate.HibernateException: Could not parse configuration: /hibernate.cfg.xml
at com.hibernate.ManageEmployee.main(ManageEmployee.java:19)
Caused by: org.dom4j.DocumentException: Connection refused: connect Nested exception: Connection refused: connect
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1481)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1411)
at com.hibernate.ManageEmployee.main(ManageEmployee.java:16)
And yes the database server is up and running but the connections from this hibernate application are refused
The problem is that the xml parser is trying to access the schema file which is specified in the configuration file. Can the box, where you are running your program, access the internet?
Here is some additional information:
https://forum.hibernate.org/viewtopic.php?f=1&t=949031

hibernate invalid configuration exception

I am new to Hibernate. My Hibernate configuration file is as follows:
<?xml version='1.0' encoding='utf-8'?>
<hibernate-configuration
xmlns="http://www.hibernate.org/xsd/hibernate-configuration"
xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-configuration hibernate-configuration-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">QADEER</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</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>
<!-- 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 class="org.test.Person"/>
</session-factory>
</hibernate-configuration>
I have the following Person.java class:
package org.test;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Person
{
#Id
private int id;
private String name;
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
Main class:
package org.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Main
{
public static void main(String args[])
{
Person obj=new Person();
obj.setId(1);
obj.setName("qadeer");
#SuppressWarnings("deprecation")
SessionFactory buildSessionFactory = new Configuration().configure().buildSessionFactory();
Session session = buildSessionFactory.openSession();
session.beginTransaction();
session.save(obj);
session.getTransaction().commit();
}
}
when i run the code it give me following excwption.....
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml Sep 13, 2013 10:34:32 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Exception in thread "main" org.hibernate.MappingException: invalid configuration
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2070)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1987)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1966)
at org.test.Main.main(Main.java:15)
Caused by: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 25; Document is invalid: no grammar found.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapp er.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:226)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:602)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3065)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:881)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:489)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at org.dom4j.io.SAXReader.read(SAXReader.java:465)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2067)
... 3 more
With Hibernate 4.x you should use the same DTD as 3.x:
<?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>
as you can see by this bug report, where the deprecation warning was removed.
Also the tutorials for 4.2 version use this, as you can see here.
The exception clearly says Caused by: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 25; Document is invalid: no grammar found. at
which means that there is no baseline (define structure of the xml) to check your xml tags against.
You need to add the hibernate DOCTYPE, which is
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" >
Also check is your xml well formed, look for any unclosed tags, etc...
This is related to hibernate.cfg.xml. For hibernate 4.3.0 Final also should use dtd as shown below to resolve this error.
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" >
It is working after adding below
<?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">

Categories

Resources