I am using Hibernate with derby database, My configuration is:
<?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.apache.derby.jdbc.ClientDriver</property>
<property name="hibernate.connection.url">jdbc:derby://localhost:1527/test;create=true</property>
<property name="hibernate.connection.username">derby</property>
<property name="hibernate.connection.password">derby</property>
<property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update </property>
<mapping resource="admin.cfg.xml"/>
</session-factory>
</hibernate-configuration>
admin.cfg.xml
<hibernate-mapping>
<class name="com.bean.Lecturer" table="lecturer">
<id name="ID" type="int">
<generator class="increment"/>
</id>
<property name="firstName" column="FName" type="string"/>
<property name="lastName" column="LName" type="string"/>
</class>
</hibernate-mapping>
Main method
public static void main(String a[]) {
static Configuration cfg = null;
static SessionFactory factory = null;
static Session s = null;
try {
cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
factory = cfg.buildSessionFactory();
s = factory.openSession();
if (s != null) {
System.out.println("Ok");
Transaction t = s.beginTransaction();
Lecturer l = new Lecturer();
l.setFirstName("Suresh");
l.setLastName("R");
s.save(l);
t.commit();
} else {
System.out.println("NOt Ok");
}
} catch (Exception z) {
System.out.println("Hibernate Connection Exception" + z);
} finally {
try {
} catch (Exception z) {
System.out.println("Hibernate Connection closing Exception" + z);
}
}
}
My Error is
Hibernate Connection Exception org.hibernate.exception.JDBCConnectionException: Cannot open connection 8285
[main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 40000, SQLState: 08001 8285
[main] ERROR org.hibernate.util.JDBCExceptionReporter - java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
Related
I developed a java desktop application using hibernate to connect to my computer's mysql database.
When I run the application on the computer that is the mysql server, it works properly, but when I run it from another computer to connect, I get the error:
WARN: HHH000342: Could not obtain connection to query metadata : Communications link failure
This is 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-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.1.72:3306/factura_registro?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">false</property>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
</session-factory>
</hibernate-configuration>
This is my main class
public class App {
public static Configuration c;
public static ServiceRegistry reg;
public static void main(String[] args) {
try {
c= new Configuration().configure().addAnnotatedClass(Usuario.class).addAnnotatedClass(Unidad.class);
reg= new ServiceRegistryBuilder().applySettings(c.getProperties()).buildServiceRegistry();
SessionFactory sf= c.buildSessionFactory(reg);
Session s= sf.openSession();
//-------------Comenzar interface inicio sesion--------------//
final Dao dao = new Dao(s);
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
GUIInicioSesion sesion =new GUIInicioSesion(dao);
sesion.setLocationRelativeTo(null);
sesion.setVisible(true);
}
});
}catch(Exception e) {
JOptionPane.showMessageDialog(null,"Error", "Alerta", 2);
}
}
}
These are de messages
Starting configuration
Warning show
Exception message
I'm trying to test the hibernate configuration of a project, but when I try to run the test it throws a MappinException saying that it does not known my entity, I checked the database and it is not creating the tables either, so my guess is that it is not reading the mapping files, but I checked that and the path is correct. And the package and class properties inside the mapping files is also correct (supposely).
Most of the questions I read are Annotation Focused, does anyone has an idea what's happening under the hood?
Thanks in advance
I have the following directory structure:
The hibernate.cfg.xml file it's like follows:
<hibernate-configuration>
<session-factory>
<!-- Hibernate Configuration -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.hbm2ddl.auto">
update
</property>
<!-- Database Configuration -->
<property name="hibernate.connection.url">
jdbc:mysql://127.0.0.1:3306/library_management?createDatabaseIfNotExist=true
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
cetys
</property>
<!-- Class Mapping Files -->
<mapping resource="Hibernate.config/mapping/Book.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/Classification.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/Collection.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/Loan.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/NonExistentRegistry.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The Loan mapping file is:
<hibernate-mapping package="com.cetys.cetyslibraryinventory.Core.DomainModels">
<class name="Loan" table="loan">
<meta attribute="class-description">
This class contains the basic information for a Loan
</meta>
<id name="id" column="loan_id" type="int"></id>
<many-to-one name="bookId" class="Book" unique="true"
column="book_id" cascade="all"/>
</class>
</hibernate-mapping>
The model:
package com.cetys.cetyslibraryinventory.Core.DomainModels;
//imports ommited
public class Loan implements Catalogable {
private int id;
private int book_id;
protected Loan () {
}
public Loan ( int id, int book_id ) {
this.id = id;
this.book_id = book_id;
}
// Getters and Setters Ommited
}
And when I try to run the following:
public class Program {
public static void main ( String[] args ) {
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try {
Configuration configuration = new Configuration();
configuration.configure( "hibernate.cfg.xml" );
ServiceRegistry serviceRegistry
= new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties() ).build();
sessionFactory = configuration.
buildSessionFactory( serviceRegistry );
session = sessionFactory.openSession();
Loan ln = new Loan( 0, 0 );
tx = session.beginTransaction();
session.save( ln );
tx.commit();
} catch ( Exception e ) {
LOGGER.log( Level.SEVERE, e.getMessage(), e );
} finally {
if ( session != null ) {
session.close();
}
if ( sessionFactory != null ) {
sessionFactory.close();
}
}
}
}
Exception Error:
SEVERE: Unknown entity: com.cetys.cetyslibraryinventory.Core.DomainModels.Loan
org.hibernate.MappingException: Unknown entity: com.cetys.cetyslibraryinventory.Core.DomainModels.Loan
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1533)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
at com.cetys.cetyslibraryinventory.Program.main(Program.java:74)
Jun 08, 2016 10:04:41 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://127.0.0.1:3306/library_management?createDatabaseIfNotExist=true]
I have about 5000 rows to insert to my database using hibernate, but it lasts about 2 minutes, I have no idea why. Here is my code:
hibernate.cfg.xml:
<?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.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://sql.user.nazwa.pl:3307/user</property>
<property name="hibernate.jdbc.batch_size">20</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">pasword</property>
<property name="show_sql">false</property>
<mapping resource="model/models.hbm.xml"/>
</session-factory>
</hibernate-configuration>
models.hbm.xml:
<?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="model.User" table="User">
<id name="userId" type="int" column="userId">
<generator class="native"/>
</id>
<property name="userName" column="userName" type="string"/>
<property name="height" column="height" type="double"/>
<property name="weight" column="weight" type="double"/>
<property name="hrMax" column="hrMax" type="double"/>
<property name="hrMin" column="hrMin" type="double"/>
<set name="trainings" cascade="all-delete-orphan,save-update" lazy="false">
<key column="userId"/>
<one-to-many class="model.Training"/>
</set>
</class>
<class name="model.Training" table="Training">
<id name="trainingId" type="int" column="trainingId">
<generator class="native"/>
</id>
<property name="type" column="type" type="string"/>
<property name="date" column="date" type="string"/>
<property name="duration" column="duration" type="org.hibernate.type.LocalTimeType"/>
<property name="totalDistance" column="totalDistance" type="double"/>
<property name="averageHeartRate" column="averageHeartRate" type="int"/>
<property name="averageSpeed" column="averageSpeed" type="double"/>
<property name="maxSpeed" column="maxSpeed" type="double"/>
<property name="calories" column="calories" type="int"/>
<property name="fatPercentageOfCalories" column="fatPercentageOfCalories" type="int"/>
<set name="trainingDetails" cascade="all-delete-orphan,save-update" lazy="false">
<key column="trainingId"/>
<one-to-many class="model.TrainingDetails"/>
</set>
</class>
<class name="model.TrainingDetails" table="TrainingDetails">
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="time" column="time" type="org.hibernate.type.LocalTimeType"/>
<property name="heartRate" column="heartRate" type="int"/>
<property name="speed" column="speed" type="double"/>
<property name="altitude" column="altitude" type="int"/>
<property name="distance" column="distance" type="double"/>
</class>
</hibernate-mapping>
HibernateUtil.java:
package model;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* Created by Piotr on 2015-10-11.
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
Method that executes too long:
public void addTrainingsDetailsToTraining(Map<String, String> mapOne, Map<String, ArrayList<String>> mapTwo
, int trainingId, int rowCount) {
Session session = hibernateUtil.getSessionFactory().openSession();
session.setCacheMode(CacheMode.IGNORE);
Transaction tx = null;
try {
tx = session.beginTransaction();
Training training = (Training) session.get(Training.class, trainingId);
for (int i = 0; i < rowCount; i++) {
training.getTrainingDetails().add(new TrainingDetails(LocalTime.parse(mapTwo.get(time).get(i))
, Integer.parseInt(mapTwo.get(heartRate).get(i)), Double.parseDouble(mapTwo.get(speed).get(i))
, Integer.parseInt(mapTwo.get(altitude).get(i)), Double.parseDouble(mapTwo.get(distance).get(i))));
if (i % 20 == 0) {
session.flush();
session.clear();
}
}
session.update(training);
tx.commit();
} catch (Exception e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
If your design allows you could give plain SQL a change (or maybe there is also a HQL equivalent).
I guess the INSERT ... ON DUPLICATE KEY UPDATE Syntax should be way faster when upserting multiple data with VALUES:
http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html
I am trying to create a simple project using Hibernate
I have the following classes :
Model :
public class InputHStock implements Serializable {
private long hsID;
private String locationCode ;
private String itemCode;
private int stock;
DAO :
public class InputHStockDAO {
public List<InputHStock> getAllIHS() {
List<InputHStock> ihs = new ArrayList<InputHStock>();
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
ihs = session.createQuery("select locationCode ").list();
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
session.flush();
session.close();
}
return ihs;
}
}
hibernate.cfg.xml :
<?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 name="Myfactory">
<property name="hibernate.connection.driver_class"> oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="hibernate.connection.username">testSQL</property>
<property name="hibernate.connection.password">testpwd1</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="InputHStock.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Mapping :
<?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="InputHStock" table="POC_HEALTHYSTOCK">
<id name="hsID" column="ID" type="int">
<generator class="native"/>
</id>
<property name="locationCode" column="LOCATIONCODE" type="string"/>
<property name="itemCode" column="ITEMCODE" type="string"/>
<property name="stock" column="STOCK" type="int"/>
</class>
</hibernate-mapping>
However When I run the project I have the following error :
No data type for node: org.hibernate.hql.internal.ast.tree.IdentNode
-[IDENT] IdentNode: 'locationCode' {originalText=locationCode}
Any ideas ?
I am trying to learn hibernate framework with making a simple program that push a class Cliente into a table on postgres, The error that returns is as follow:
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Caused by: org.postgresql.util.PSQLException: ERROR: the relation "clienti_id_seq" does not exist
This is my database by PGAdmin (sorry for imgur i can't upload picture directly) http://i.imgur.com/Fz9o1fR.png?1
This is the class Cliente
public class Cliente {
private long clienteId;
private String clienteNome;
private String clienteCognome;
private String clienteTelefono;
private String clienteMail;
private String clientePermesso;
private long clienteCommessa;
public long getClienteId() {
return clienteId;
}
public void setClienteId(long clienteId) {
this.clienteId = clienteId;
}
public String getClienteNome() {
return clienteNome;
}
public void setClienteNome(String clienteNome) {
this.clienteNome = clienteNome;
}
public String getClienteCognome() {
return clienteCognome;
}
public void setClienteCognome(String clienteCognome) {
this.clienteCognome = clienteCognome;
}
public String getClienteTelefono() {
return clienteTelefono;
}
public void setClienteTelefono(String clienteTelefono) {
this.clienteTelefono = clienteTelefono;
}
public String getClienteMail() {
return clienteMail;
}
public void setClienteMail(String clienteMail) {
this.clienteMail = clienteMail;
}
public String getClientePermesso() {
return clientePermesso;
}
public void setClientePermesso(String clientePermesso) {
this.clientePermesso = clientePermesso;
}
public long getClienteCommessa() {
return clienteCommessa;
}
public void setClienteCommessa(long clienteNome) {
this.clienteCommessa = clienteCommessa;
}
}
This is my mapping file
<hibernate-mapping>
<class name="beans.Cliente" table="Clienti">
<id name="clienteId" type="integer" column="id" >
<generator class="sequence">
<param name="sequence">CLIENTI_ID_seq</param>
</generator>
</id>
<property name="clienteNome" column="nome" type="string">
</property>
<property name="clienteCognome" column="cognome" type="string">
</property>
<property name="clienteTelefono" column="telefono" type="string">
</property>
<property name="clienteMail" column="mail" type="string">
</property>
<property name="clientePermesso" column="permesso" type="string">
</property>
<property name="clienteCommessa" column="commessa" type="string">
</property>
</class>
</hibernate-mapping>
This is the hibernate cfg.xml file, the information about url pass and user are correct
<?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.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql:postgres</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/Georilievi</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">Fabio1990</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="Clienti.hbm.xml"/>
</session-factory>
</hibernate-configuration>
This is the main file, here i create an istance of Cliente, and try to push in the postgres database
package main;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import beans.Cliente;
public class Main {
public static void main(String [] args){
// Create a configuration instance
Configuration configuration = new Configuration();
// Provide configuration file
configuration.configure("hibernate.cfg.xml");
// Build a SessionFactory
SessionFactory factory = configuration.buildSessionFactory(new StandardServiceRegistryBuilder().configure().build());
// Get current session, current session is already associated with Thread
Session session = factory.getCurrentSession();
// Begin transaction
session.getTransaction().begin();
Cliente cliente = new Cliente();
cliente.setClienteNome("Fabio");
cliente.setClienteCognome("Tramontana");
cliente.setClienteTelefono("3343052346");
cliente.setClienteMail("info.tramontanafabio#gmail.com");
cliente.setClientePermesso("admin");
cliente.setClienteCommessa(0);
// Save*/
session.save(cliente);
// Commit, calling of commit will cause save an instance of employee
session.getTransaction().commit();
}
}
thanks all of you for helping me, i don't understand the error, i think it is in the declaration of the generator.
Please try changing the generator class from sequence to identity and see. I guess the issue is the auto generation of IDs.
See these links:
http://www.roseindia.net/hibernate/hibernateidgeneratorelement.shtml
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-property