I am getting this error:
Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: org.hibernate.Session.close()Ljava/sql/Connection;
When calling this function:
private static SessionFactory factory;
public static void insert(Object model) {
factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
try {
session.save(model);
tx.commit();
} catch (HibernateException exc) {
if (tx != null)
tx.rollback();
exc.printStackTrace();
} finally {
session.close(); // here is when the error occurs
}
}
I believe I have imported all the necessary jars from /lib/required/ directory in the latest Hibernate 5.0.1.
The hibernate.cfx.xml file is also correctly configured:
<?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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3307/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property >
<mapping resource="customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
And customer.hbm.xml mapping file:
<class name="com.test.app.model.Customer" table="customer">
<meta attribute="class-description">
Test.
</meta>
<id column="id" name="id" type="int">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"/>
<property name="phoneNumbers" column="phone_numbers" type="string"/>
<property name="emailAddresses" column="email_addresses" type="string"/>
<property name="address" column="address" type="string"/>
<property name="note" column="note" type="string"/>
</class>
What could be the issue?
Looks like you have two hibernate-core-5.0.1.Final.jar in your classpath. For example, if you run a project in the IDE and add other project with hibernate-core-5.0.1.Final.jar to your classpath.
P.S. Please don't configure the session factory in every insert, and rollback on any exception, not only on HibernateException. You can see how properly working with transactions here, and you can find a simply example console project using Hibernate 5 and MySQL here.
Related
SOLVED
What did i do to solve it?
I added the Persistence JPA2.1 to the library
Initial error
I'm having this error:
Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: javax/persistence/NamedStoredProcedureQuery
Exception in thread "main" java.lang.ExceptionInInitializerError
at modelo.util.HibernateUtil.<clinit>(HibernateUtil.java:29)
at modelo.dao.GenericDAO.getAll(GenericDAO.java:89)
at principal.Main.main(Main.java:34)
Caused by: java.lang.NoClassDefFoundError: javax/persistence/NamedStoredProcedureQuery
at org.hibernate.cfg.AnnotationBinder.bindDefaults(AnnotationBinder.java:276)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1402)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at modelo.util.HibernateUtil.<clinit>(HibernateUtil.java:25)
... 2 more
Caused by: java.lang.ClassNotFoundException: javax.persistence.NamedStoredProcedureQuery
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
Have no idea why I'm getting that exception
Main class:
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
GenericDAO clienteDAO = new GenericDAO();
List<Cliente> list = clienteDAO.getAll(Cliente.class);
System.out.println(list.size());
for(Cliente c : list)
{System.out.println("-> " + c.getNombre());
}
}
}
HibernateUtil class:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Mapping Class.hbm.xml file:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 21/05/2017 17:46:05 by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="modelo.pojo.Cliente" table="cliente" catalog="basededatosprueba" optimistic-lock="version">
<id name="codigo" type="java.lang.Integer">
<column name="codigo" />
<generator class="identity" />
</id>
<property name="nombre" type="string">
<column name="nombre" />
</property>
<property name="direccion" type="string">
<column name="direccion" />
</property>
<property name="telefono" type="string">
<column name="telefono" />
</property>
<property name="cuit" type="string">
<column name="cuit" />
</property>
<property name="cp" type="java.lang.Integer">
<column name="cp" />
</property>
<property name="saldo" type="java.lang.Double">
<column name="saldo" precision="22" scale="0" />
</property>
<property name="deuda" type="java.lang.Double">
<column name="deuda" precision="22" scale="0" />
</property>
</class>
</hibernate-mapping>
my hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/basededatosprueba?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
<mapping resource="modelo/pojo/Cliente.hbm.xml"/>
</session-factory>
</hibernate-configuration>
libraries
I don't know why I'm getting that error.
Hope someone can help me. Thanks
SOLVED
What did I do to solve it?
I added the Persistence JPA2.1 to the library
Any questions? I'll be glad to help
As an output I m receiving error:
org.hibernate.InvalidMappingException: Could not parse mapping document from resource User.hbm.xml.
I have tried solving it using links:
Could not parse mapping document from resource Books.hbm.xml
Hibernate and maven: Could not parse mapping document from resource
I'm trying to enter values in database using pojo class
User.hbm.xml
<hibernate-mapping>
<class name="com.program.User" table="user">
<id name="ID" type="int" column="id">
<generator class="increment" />
</id>
<property name="NAME" type="java.lang.String" column="name">
<column name="name" />
</property>
<property name="AGE" type="int" column="age">
<column name="age" />
</property>
</class>
</hibernate-mapping>
Program.java
package com.program;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Program {
public static void main(String[] args) {
try{
System.out.println("hello world");
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();;
Session session = factory.openSession();
session.beginTransaction();
User user = new User();
user.setID(1);
user.setNAME("Toral");
user.setAGE(21);
session.save(user);
session.getTransaction().commit();
session.close();
}catch(Exception e){
System.out.println(e);
}
}
}
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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/student</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update </property>
<mapping resource="User.hbm.xml" />
</session-factory>
</hibernate-configuration>
I think you misplaced actual value for "name" attribute ane "column" attribute.
"name" attribute represents property of your POJO class.
"column" attribute represents column name of your table.
Try this:
<hibernate-mapping>
<class name="com.program.User" table="user">
<id name="id" type="int" column="ID">
<generator class="increment" />
</id>
<property name="name" type="java.lang.String" column="NAME"></property>
<property name="age" type="int" column="AGE"></property>
</class>
I'm using hibernate framework for a desktop application (Swing) and I called the needed librairies for hibernte to work but I still get this exception when I create a SessionFactory:
private static SessionFactory factory = new Configuration(). configure(). buildSessionFactory();
And this is the list of used librairies:
My config file:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.PostgreSQLDialect
</property>
<property name="hibernate.connection.driver_class">
org.postgresql.Driver
</property>
<property name="hibernate.connection.url">
jdbc:postgresql://localhost:5432/test_hibernate
</property>
<property name="hibernate.connection.username">
postgres
</property>
<property name="hibernate.connection.password">
root
</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
My mapping file:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="employee">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"/>
<property name="salary" column="salary" type="double"/>
</class>
</hibernate-mapping>
Try removing encoding part from top level tag in both config and hbm file.
I am not sure if this will work for you, it worked for us.
I'm trying to store an object Ficheiro inside my in-memory database. This object contains:
private int version;
private Workbook content;
This is my code I'm using to store in the database:
HSQLServerUtil.getInstance().start("DBMemoria");
Ficheiro fich = new Ficheiro();
fich.setVersion(1);
fich.setContent(workbook);
byte[] by = serialize(fich);
try {
Blob blob = new SerialBlob(by);
Session ss = HibernateUtils.newSessionFactory("csheets\\ext\\Hibernate\\hibernate.cfg.xml").openSession();
ss.beginTransaction();
ss.getTransaction();
ss.save(workbook);
ss.getTransaction().commit();
ss.close();
} catch (SQLException ex) {
System.out.println("ERROR");
}
This is my hibernate.cfg.xml file:
<?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.connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.connection.url">jdbc:hsqldb:file:C:\Users\Adam\Documents\NetBeansProjects\lapr4_2dd_g1_s2\lib\Version</property>
<property name="hibernate.connection.username"/>
<property name="hibernate.connection.password"/>
<mapping resource="csheets/ext/Hibernate/File.hbm.xml"/>
</session-factory>
</hibernate-configuration>
And finally this is my File.hbm.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class dynamic-insert="false" dynamic-update="false" mutable="true" name="csheets.ext.Hibernate.Ficheiro" optimistic-lock="version" polymorphism="implicit" select-before-update="false" table="File">
<id column="version" name="version" type="int" unsaved-value="0">
<generator class="identity">
</generator>
</id>
<property column="content" name="content" type="blob"/>
<!--<property column="name" name="name" type="string"/>-->
</class>
</hibernate-mapping>
I'm getting the following error:
Exception in thread "AWT-EventQueue-0" org.hibernate.MappingException: Unknown entity: csheets.core.Workbook
I've already put an #Entity in the Workbook class. Anybody know whats wrong?
And if possible, can you tell me if i'm doing this right?
Thanks
Update your hibernate config to the following to make it work (for development machine):
<property name="hibernate.hbm2ddl.auto">update</property>
I am learning hibernate and I can't figure out why is this error popping up. I tried searching but I couldn't find a solution that helped me. I'd like to learn why am I getting this error.
Exception in thread "main" org.hibernate.MappingException: Unknown entity: from Destination
Here are some details:
main():
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
// Destination destination = new Destination();
// destination.setName("IDelhi");
// destination.setLatitude(1.0f);
// destination.setLongitude(123.0f);
// session.save(destination);
List result = session.createCriteria("from Destination").list();
session.getTransaction().commit();
session.close();
// for (Object dest : result) {
// Destination d = (Destination)dest;
// System.out.println(d.getId() + ": "+ d.getName());
// }
}
}
When I try to insert the destination (commented code), values are being inserted into db.
Configurations:
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 name="">
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.password">*****</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/</property>
<property name="hibernate.connection.username">*****</property>
<property name="hibernate.default_schema">wah_schema</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<mapping class="org.wah.dao.Destination" resource="org/wah/dao/Destination.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Destination.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Jan 25, 2012 3:31:00 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="org.wah.dao.Destination" table="DESTINATION">
<id name="id" type="int">
<column name="ID"/>
<generator class="identity"/>
</id>
<property generated="never" lazy="false" name="name" type="java.lang.String">
<column name="NAME"/>
</property>
<property generated="never" lazy="false" name="latitude" type="float">
<column name="LATITUDE"/>
</property>
<property generated="never" lazy="false" name="longitude" type="float">
<column name="LONGITUDE"/>
</property>
</class>
</hibernate-mapping>
Can someone please help me figure this out ?
use session.createCriteria(Destination.class); You are trying to use HQL - Hibernate Query Language for which you need to use other api like
Query query = session.createQuery("from Destination");
List list = query.list();
<mapping class="org.wah.dao.Destination"
resource="org/wah/dao/Destination.hbm.xml"/>
instead of this, please change it to
<mapping resource="org/wah/dao/Destination.hbm.xml">
Hibernate throws this error because when it expect some Annotation based class, you are referring the XML based Hibernate mapping. Stick to two different rule Annotations or XML based.
You are mixing HQL and Criteria query. You should either do
session.createCriteria(Destination.class).list();
or
session.createQuery("from Destination").list();
According to here, something like this should work:
List result = session.createCriteria(Destination.class).list();
I had similar problem for a simple Console application trying to use Hibernate. The solution I arrived to make the add the "packagesToScan" property explicitly for LocalSessionFactoryBean.
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.mg.learning.spring.orm"/> <--- this SOLVED!
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>