Inserting many rows with hibernate is very slow - java

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

Related

Delete a Simple row from database

I have 2 tables, testInput and testCases and in testInput i have a FK with the id of the other table.
So basically the rows I want to delete are id of the input, id of the testCase, name and a description.
'43', '21', 'USERNAME', 'USERNAME'
'44', '21', 'PASSWORD', 'PASSWORD'
I tried to delete that row and I get
java.sql.SQLIntegrityConstraintViolationException: Cannot delete or
update a parent row: a foreign key constraint fails
(mydb.testInput, CONSTRAINT fk02 FOREIGN KEY (testCase)
REFERENCES testCases (idtestCase) ON DELETE NO ACTION ON UPDATE NO
ACTION)
I don't want to delete the record of testCase. I just want to delete the inputs of that testCase. What do I do?
code if u want...
List<TestInput> previousInputs = TestInput.getInputs(testCaseName);
for(TestInput in : previousInputs) {
Database.deleteObject(in);
}
//delete the object to the database
public static void deleteObject(Object object) {
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
session.delete(object);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
xml TestCases
<hibernate-mapping>
<class name="TestCase" table="testCases">
<meta attribute="class-description">
This class contains the testCases details.
</meta>
<id name="id" type="int" column="idtestCase">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"/>
<many-to-one name="type" class="TestType" column="type" fetch="select" lazy="false"/>
<property name="data" column="data" type="binary"/>
<property name="amountOfInputs" column="amountOfInputs" type="int"/>
<property name="creationDate" column="creationDate" type="string"/>
<property name="createdBy" column="createdBy" type="string"/>
<many-to-one name="tellerConfig" class="TellerConfiguration" column="tellerConfig" fetch="select" lazy="false"/>
</class>
</hibernate-mapping>
xml testInput
<hibernate-mapping>
<class name="TestInput" table="testInput">
<meta attribute="class-description">
This class contains the testCases input details.
</meta>
<id name="id" type="int" column="idtestInput">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"/>
<property name="description" column="description" type="string"/>
<many-to-one name="testCase" class="TestCase" column="testCase" fetch="select" cascade="all" lazy="false" />
</class>
Change the constraint on the foreign key fk02 from ´NO ACTION´ to 'SET NULL'
FOREIGN KEY (idtestcase)
REFERENCES testCases(idtestCase)
ON DELETE SET NULL

Attribute "column" must be declared for element type "one-to-many"

i would like to create a dynamique web project with hibernate 3.In this project i have 2 classes and relation with them. The first class is Ecole and this is the attributs
package essai1;
import java.util.HashSet;
import java.util.Set;
public class Ecole {
private int id_ecole;
private String nom_ecole;
private Set<Etudiant> etudiants = new HashSet<>();
public Set<Etudiant> getEtudiants() {
return etudiants;
}
public void setEtudiants(Set<Etudiant> etudiants) {
this.etudiants = etudiants;
}
public int getId_ecole() {
return id_ecole;
}
public void setId_ecole(int id_ecole) {
this.id_ecole = id_ecole;
}
public String getNom_ecole() {
return nom_ecole;
}
public void setNom_ecole(String nom_ecole) {
this.nom_ecole = nom_ecole;
}
public Ecole() {
super();
}}
the second class has this attributs
package essai1;
public class Etudiant {
private int id_etudiant;
private String nom_etudiant;
private String prenom_etudiant;
private Ecole ecole;
public int getId_etudiant() {
return id_etudiant;
}
public void setId_etudiant(int id_etudiant) {
this.id_etudiant = id_etudiant;
}
public String getNom_etudiant() {
return nom_etudiant;
}
public void setNom_etudiant(String nom_etudiant) {
this.nom_etudiant = nom_etudiant;
}
public String getPrenom_etudiant() {
return prenom_etudiant;
}
public void setPrenom_etudiant(String prenom_etudiant) {
this.prenom_etudiant = prenom_etudiant;
}
public Ecole getEcole() {
return ecole;
}
public void setEcole(Ecole ecole) {
this.ecole = ecole;
}
public Etudiant() {
super();
}}
I have the folder of the mapping Ecole.hbm.xml through which i create this 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 name="essai1.Ecole" table="ECOLE">
<id name="id_ecole" type="java.lang.Integer" column="id_ecole">
<generator class="increment" />
</id>
<property name="nom_ecole" type="java.lang.String">
<column name="nom_ecole" />
</property>
<set name="etudiants" inverse="true" table="ETUDIANT" cascade="all">
<key>
<column name="id_ecole" not-null="true"></column>
</key>
<one-to-many class="essai1.Etudiant" column="idEtudiant" />
</set>
<!-- <bag name="etudiants" table="Etudiant" lazy="true" inverse="true"
cascade="all"> <key column="id_ecole" not-null="true" /> <one-to-many class="essai1.Etudiant">
<column name="idEtudint" ></column> </one-to-many> </bag> -->
</class>
</hibernate-mapping>
In this file i have the problem of the mapping between the class of Ecole and the class Etudiant in the ligne one-to-many that i can't to add the attribute column="idEtudiant" in this tag
the file of hibernate.cfg.xml is here
<?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.url">jdbc:mysql://localhost:3306/essaihibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<mapping resource="map/Ecole.hbm.xml" />
<mapping resource="map/Etudiant.hbm.xml"/>
</session-factory>
</hibernate-configuration>
the file of mapping of Etudiant.hbm.xml is clearly and it has no problem and this is the code
<?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 name="essai1.Etudiant" table="Etudiant">
<id name="idEtudiant" type="java.lang.Integer" column="idEtudiant">
<generator class="increment" />
</id>
<property name="nomEtudiant" type="java.lang.String">
<column name="nomEtudiant" />
</property>
<property name="prenomEtudiant" type="java.lang.String">
<column name="prenomEtudiant" />
</property>
<many-to-one name="essai1.ecole">
<column name="id_ecole" />
</many-to-one>
</class>
</hibernate-mapping>
the file of the hibernateUtil.java is there also
package util;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateUtil {
public static final SessionFactory sessionFactory;
static {
try {
// Création de la SessionFactory à partir de hibernate.cfg.xml
sessionFactory = new Configuration().configure("map/hibernate.cfg.xml").buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
// public static final ThreadLocal session = new ThreadLocal();
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
the jars were download :
antlr-2.7.6.jar
asm-1.3.3.jar
cglib-nodep-2.1_3.jar
jta.jar
commons-collections-3.2.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar
ehcache-1.2.3.jar
hibernate3.jar
log4j.jar
mysql-connector-java-5.0.4-bin.jar
the database
create database essaihibernate; use essaihibernate; CREATE TABLE `essaihibernate`.`ECOLE` ( `id_ecole` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, `nom_ecole` TEXT NOT NULL, PRIMARY KEY (`id_ecole`) );
and the second table Etudiant is there
CREATE TABLE `essaihibernate`.`ETUDIANT` ( `id_etudiant` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, `nom_etudiant` TEXT NOT NULL, `prenom_etudiant` TEXT NOT NULL, `id_ecole` INTEGER UNSIGNED NOT NULL, PRIMARY KEY (`id_etudiant`), CONSTRAINT `FK_ETUDIANT_1` FOREIGN KEY `FK_ETUDIANT_1` (`id_ecole`) REFERENCES `ecole` (`id_ecole`) ON DELETE RESTRICT ON UPDATE RESTRICT );
the document imposes this orders of this all instructions but i can to mapped in my database because i have a problem with the column in the file Ecole.hbm.xml at the ligne 17
<one-to-many class="essai1.Etudiant" column="idEtudiant" />
the erreur is Attribute "column" must be declared for element type "one-to-many"
What can I do? I am very disappointed. help me my friend I am waiting for you
This, from the Etudiant class
private int id_etudiant;
private String nom_etudiant;
private String prenom_etudiant;
is not what you have defined in the corresponding xml file, Etudiant.hbm.xml

No data type for node: org.hibernate.hql.internal.ast.tree.IdentNode \-[IDENT] IdentNode: 'locationCode' {originalText=locationCode}

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 ?

org.hibernate.NonUniqueResultException: query did not return a unique result: 462

I'm working on an application with Spring using SpringMVC,, i'm encountering the following error and i don't know how to deal with it .
now i have this message in Console :
org.hibernate.TypeMismatchException: Provided id of the wrong type. Expected: class java.lang.Integer, got class java.lang.String
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:86)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:878)
at org.hibernate.impl.SessionImpl.load(SessionImpl.java:795)
at org.hibernate.impl.SessionImpl.load(SessionImpl.java:788)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:301)
at com.sun.proxy.$Proxy11.load(Unknown Source)
at com.my.dao.DepartementImplDB.getDepartementByNom(DepartementImplDB.java:54)
at com.my.dao.DepartementImplDB.addDepartement(DepartementImplDB.java:29)
at com.my.service.DepartementImplMetier.create(DepartementImplMetier.java:57)
at com.my.controller.ImportController.Read(ImportController.java:279)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:710)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:167)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:563)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
this is my ImportController class
/**
* #author Ilias
*/
package com.my.controller;
//import ...
import com.my.dao.Departement;
#Controller
public class ImportController {
DepartementImplMetier dbD = new DepartementImplMetier();
#RequestMapping(value="/read")
public String Read(Model model,#RequestParam CommonsMultipartFile[] fileUpload)
throws IOException, EncryptedDocumentException, InvalidFormatException, java.text.ParseException
{
liste = extraire(modelnom);
for(int m=0, i=29;i<liste.size();i=i+29){//i=i+29
Employe employe= new Employe();
Departement departement = new Departement();
if(i % 29 == 0) m++;
//... Some code here
String dep = (String)liste.get(29*m+13).toString();
Departement d = new Departement();
departement.setNomDepartement(dep);
boolean bool=true;
List<Departement> departements = dbD.getAll();
boolean depbool = true;
for(int j=0;j< departements.size();j++){
if(departements.get(j).getNomDepartement() == dep )
{
depbool = false;
}
if(depbool){
try {
dbD.create(departement);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
for(int n=0;n<employes.size();n++){
if(employes.get(n).getMatriculeMY() == (int)mat )
{
bool= false;
}
}
if(bool){
try {
dbD.create(departement);
dbE.create(employe);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
}
return "redirect";
}}
}
this is my Employe.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 5 ao?t 2015 11:05:44 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.my.dao.Employe" table="EMPLOYE">
<id name="id" type="int">
<column name="ID" />
<generator class="native" />
</id>
<property name="nomEmploye" type="java.lang.String">
<column name="NOMEMPLOYE" />
</property>
<property name="prenomEmploye" type="java.lang.String">
<column name="PRENOMEMPLOYE" />
</property>
<property name="matriculeMY" type="int">
<column name="MATRICULEMY" />
</property>
<property name="adresse" type="java.lang.String">
<column name="ADRESSE" />
</property>
<property name="sexe" type="java.lang.String">
<column name="SEXE" />
</property>
<property name="cin" type="java.lang.String">
<column name="CIN" />
</property>
<property name="dateNaissance" type="java.lang.String">
<column name="DATENAISSANCE" />
</property>
<property name="situationFamiliale" type="java.lang.String">
<column name="SITUATIONFAMILIALE" />
</property>
<property name="dateEntree" type="java.lang.String">
<column name="DATEENTREE" />
</property>
<property name="dateSortie" type="java.lang.String">
<column name="DATESORTIE" />
</property>
<property name="numCIMR" type="java.lang.String">
<column name="NUMCIMR" />
</property>
<property name="numCNSS" type="java.lang.String">
<column name="NUMCNSS" />
</property>
<property name="numMUT" type="java.lang.String">
<column name="NUMMUT" />
</property>
<property name="profile" type="java.lang.String">
<column name="PROFILE" />
</property>
<property name="resteConge" type="java.lang.String">
<column name="RESTECONGE" />
</property>
<property name="banque" type="java.lang.String">
<column name="BANQUE" />
</property>
<property name="numCpteBanc" type="java.lang.String">
<column name="NUMCPTEBANC" />
</property>
<!-- <property name="fonction" type="java.lang.String">
<column name="FONCTION" />
</property> -->
<property name="salaire" type="float">
<column name="SALAIRE" />
</property>
<property name="indTransport" type="float">
<column name="INDTRANSPORT" />
</property>
<property name="indRepresent" type="float">
<column name="INDREPRESENT" />
</property>
<property name="indPanier" type="float">
<column name="INDPANIER" />
</property>
<many-to-one name="eDepartement" class="com.my.dao.Departement" access="field" fetch="join">
<column name="EDEPARTEMENT" />
</many-to-one>
<many-to-one name="eFonction" class="com.my.dao.Fonction" access="field" fetch="join">
<column name="EFONCTION" />
</many-to-one>
<many-to-one name="eService" class="com.my.dao.Service" access="field" fetch="join">
<column name="ESERVICE" />
</many-to-one>
<many-to-one name="eTypePaiement" class="com.my.dao.TypePaiement" access="field" fetch="join">
<column name="ETYPEPAIEMENT" />
</many-to-one>
<many-to-one name="eModePaiement" class="com.my.dao.ModePaiement" access="field" fetch="join">
<column name="EMODEPAIEMENT" />
</many-to-one>
</class>
</hibernate-mapping>
this is my Departement.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 5 ao?t 2015 11:05:44 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.my.dao.Departement" table="DEPARTEMENT">
<id name="id" type="int">
<column name="ID" />
<generator class="native" />
</id>
<property name="nomDepartement" type="java.lang.String">
<column name="NOMDEPARTEMENT" />
</property>
<set name="Employe" inverse="true">
<key column="ID" not-null="true"/>
<one-to-many class="com.my.dao.Employe" />
</set>
</class>
</hibernate-mapping>
after debuging, the problem is here :
boolean depbool = true;
for(int j=0;j< departements.size();j++){
if(departements.get(j).getNomDepartement() == dep )
{
depbool = false;
}
if(depbool){
try {
dbD.create(departement);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
exactely here :
dbD.create(departement);
this DepartementImplDB class
package com.my.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import com.my.util.HibernateUtil;
/**
* #author Ilias
*
*/
public class DepartementImplDB implements DepartementDao {
/**
* #see com.my.dao.DepartementDao#addDepartement(com.my.dao.Departement)
*/
#Override
public int addDepartement(Departement D) {
// TODO Auto-generated method stub
Session session = HibernateUtil.getInstance().getSessionFactory().getCurrentSession();
session.beginTransaction();System.out.println("********");
session.save(D);System.out.println("departement implement metier");
session.getTransaction().commit();
D=this.getDepartementByNom(D.getNomDepartement());
return D.getId();
}
/**
* #see com.my.dao.DepartementDao#getDepartementById(int)
*/
#Override
public Departement getDepartementById(int id) {
// TODO Auto-generated method stub
Session session = HibernateUtil.getInstance().getSessionFactory().getCurrentSession();
Departement dept = new Departement();
try {
session.beginTransaction();
dept = (Departement) session.load(Departement.class, id);
} catch (HibernateException e) {
//LOGGER.error(e);
e.printStackTrace();
if (session.getTransaction().isActive()) {
session.getTransaction().rollback();
}
}
return dept;
}
/**
* #see com.my.dao.DepartementDao#getDepartementByNom(java.lang.String)
*/
#Override
public Departement getDepartementByNom(String nomDepartement) {
Session session = HibernateUtil.getInstance().getSessionFactory().getCurrentSession();
Departement result = new Departement();
try {
session.beginTransaction();
Criteria criteria = session.createCriteria(Departement.class);
criteria.add(Restrictions.eq("nomDepartement", nomDepartement).ignoreCase());
result = (Departement) criteria.uniqueResult();
session.getTransaction().commit();
} catch (HibernateException e) {
//LOGGER.error(e);
e.printStackTrace();
if (session.getTransaction().isActive()) {
session.getTransaction().rollback();
}
}
return result;
}
/**
* #see com.my.dao.DepartementDao#deleteDepartement(int)
*/
#Override
public void deleteDepartement(int id) {
// TODO Auto-generated method stub
Session session = HibernateUtil.getInstance().getSessionFactory().getCurrentSession();
session.beginTransaction();
Departement dept = (Departement) session.load(Departement.class, id);
session.delete(dept);
session.getTransaction().commit();
}
/**
* #see com.my.dao.DepartementDao#updateDepartement(com.my.dao.Departement)
*/
#Override
public void updateDepartement(Departement D) {
// TODO Auto-generated method stub
}
/**
* #see com.my.dao.DepartementDao#getAllDepartement()
*/
#Override
public List<Departement> getAllDepartement() {
// TODO Auto-generated method stub
Session session = HibernateUtil.getInstance().getSessionFactory().getCurrentSession();
session.beginTransaction();
return session.createQuery("from Departement").list();
}
}
this is what i want to do (UML): imgur
this is the link of my last error for more infos : Link
can some one help ?
Your question is a real mess... but if you read the exception:
Provided id of the wrong type. Expected: class java.lang.Integer, got class java.lang.String
Anf after you take a look to your Departement class, it has only 2 fields and one set (according to the hibernate mapping):
int id;
String nomDepartament;
Set employees;
That only can mean, youre passing the nomDepartament field instead of id somewhere in your code...
But as far as you are not providing, the Departement class or DepartementImplMetier.create() method, that is the one causing the exception I cannot say more...
So... start here focus your problems, and provide only important parts of the code.

Getting org.hibernate.MappingException

This is my first question in Stackoverflow. I'd hope be clear. I'm getting troubles with Hibernate mapping and I don't know where the error is. When I tried to run a HQL like
from Sensor
I get the following exception
org.hibernate.MappingException: Association references unmapped class: sipiaHibernate.TipoSensor
at org.hibernate.cfg.HbmBinder.bindCollectionSecondPass(HbmBinder.java:2380)
at org.hibernate.cfg.HbmBinder$CollectionSecondPass.secondPass(HbmBinder.java:2662)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:43)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1130)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:324)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1286)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
I'm working on netbeans 7 with openjdk6, hibernet 3.2.5 and MySQL database. I have all the POJO's class in the package sipiaHibernate. All the tables mentioned in the configuration files are in my database. I generated the POJO classes & the mapping files using the netbeans hibernet utility.
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.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:3306/gatewaysipia</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">xxxxxxxxx</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>
<property name="hibernate.jdbc.batch_size">0</property>
<mapping resource="sipiaHibernate/TipoSensor.hbm.xml"/>
<mapping resource="sipiaHibernate/Mote.hbm.xml"/>
<mapping resource="sipiaHibernate/LogDataInd.hbm.xml"/>
<mapping resource="sipiaHibernate/ModeloSensor.hbm.xml"/>
<mapping resource="sipiaHibernate/Usuario.hbm.xml"/>
<mapping resource="sipiaHibernate/Proyecto.hbm.xml"/>
<mapping resource="sipiaHibernate/DatosProyecto.hbm.xml"/>
<mapping resource="sipiaHibernate/ServerVariables.hbm.xml"/>
<mapping resource="sipiaHibernate/LogMoteStart.hbm.xml"/>
<mapping resource="sipiaHibernate/Sensor.hbm.xml"/>
<mapping resource="sipiaHibernate/SensorConstantes.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernate.reveng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
<schema-selection match-catalog="gatewaysipia"/>
<table-filter match-name="modelo_sensor"/>
<table-filter match-name="server_variables"/>
<table-filter match-name="log_mote_start"/>
<table-filter match-name="mote"/>
<table-filter match-name="datos_proyecto"/>
<table-filter match-name="proyecto_has_usuario"/>
<table-filter match-name="tipo_sensor"/>
<table-filter match-name="log_data_ind"/>
<table-filter match-name="usuario"/>
<table-filter match-name="sensor_constantes"/>
<table-filter match-name="sensor"/>
<table-filter match-name="proyecto"/>
</hibernate-reverse-engineering>
The mapping xml files are:
Sensor.hbm.xml
<!-- language: lang-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 06/08/2012 18:34:16 by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="sipiaHibernate.Sensor" table="sensor" catalog="gatewaysipia">
<id name="idsensor" type="java.lang.Long">
<column name="idsensor" />
<generator class="identity" />
</id>
<many-to-one name="modeloSensor" class="sipiaHibernate.ModeloSensor" fetch="select">
<column name="modelo_sensor_idmodelo_sensor" not-null="true" />
</many-to-one>
<many-to-one name="mote" class="sipiaHibernate.Mote" fetch="select">
<column name="mote_idMote" not-null="true" />
</many-to-one>
<many-to-one name="proyecto" class="sipiaHibernate.Proyecto" fetch="select">
<column name="proyecto_idproyecto" />
</many-to-one>
<property name="dirSensor" type="short">
<column name="dir_sensor" not-null="true">
<comment>el nro de entrada analogica/digital a la cual el sensor esta conectado en el mote</comment>
</column>
</property>
<property name="etiqueta" type="string">
<column name="etiqueta" length="100" not-null="true">
<comment>etiqueta/label dada por el usuario</comment>
</column>
</property>
<property name="ubicacion" type="string">
<column name="ubicacion" length="100" not-null="true">
<comment>ubicacion texto libre dada por el usuario</comment>
</column>
</property>
<property name="gpsLatitud" type="big_decimal">
<column name="gps_latitud" precision="8" scale="6" />
</property>
<property name="gpsLongitud" type="big_decimal">
<column name="gps_longitud" precision="8" scale="6" />
</property>
<property name="estadoSensor" type="string">
<column name="estado_sensor" length="9" not-null="true" />
</property>
<set name="datosProyectos" inverse="true">
<key>
<column name="sensor_idsensor" not-null="true" />
</key>
<one-to-many class="sipiaHibernate.DatosProyecto" />
</set>
</class>
</hibernate-mapping>
ModeloSensor.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 06/08/2012 18:34:16 by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="sipiaHibernate.ModeloSensor" table="modelo_sensor" catalog="gatewaysipia">
<id name="idmodeloSensor" type="java.lang.Long">
<column name="idmodelo_sensor" />
<generator class="identity" />
</id>
<many-to-one name="tipoSensor" entity-name="sipiaHibernate.TipoSensor" class="sipiaHibernate.TipoSensor" fetch="select">
<column name="tipo_sensor_idtipo_sensor" not-null="true" />
</many-to-one>
<property name="descripcionModelo" type="string">
<column name="descripcion_modelo" length="100">
<comment>Indica el modelo del sensor, por ej, PT100, etc</comment>
</column>
</property>
<set name="tipoSensors" inverse="true">
<key>
<column name="idtipo_sensor" not-null="true" unique="true" />
</key>
<one-to-many class="sipiaHibernate.TipoSensor" />
</set>
<set name="sensors" inverse="true">
<key>
<column name="modelo_sensor_idmodelo_sensor" not-null="true" />
</key>
<one-to-many entity-name="sipiaHibernate.Sensor" class="sipiaHibernate.Sensor" />
</set>
</class>
</hibernate-mapping>
TipoSensor.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 06/08/2012 18:34:16 by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="sipiaHibernate.TipoSensor" table="tipo_sensor" catalog="gatewaysipia">
<id name="idtipoSensor" type="java.lang.Long">
<column name="idtipo_sensor" />
<generator class="identity" />
</id>
<many-to-one name="modeloSensor" class="sipiaHibernate.ModeloSensor" update="false" insert="false" fetch="select">
<column name="idtipo_sensor" not-null="true" unique="true" />
</many-to-one>
<property name="tipoDescripcion" type="string">
<column name="tipo_descripcion" length="45" />
</property>
<property name="unidad" type="string">
<column name="unidad" length="45" />
</property>
<property name="valorMinimo" type="java.lang.Float">
<column name="valor_minimo" precision="12" scale="0" />
</property>
<property name="valorMaximo" type="java.lang.Float">
<column name="valor_maximo" precision="12" scale="0" />
</property>
<set name="modeloSensors" inverse="true">
<key>
<column name="tipo_sensor_idtipo_sensor" not-null="true"/>
</key>
<one-to-many entity-name="sipiaHibernate.ModeloSensor" class="sipiaHibernate.ModeloSensor" />
</set>
</class>
</hibernate-mapping>
Sensor POJO Class
package sipiaHibernate;
// Generated 06/08/2012 18:34:16 by Hibernate Tools 3.2.1.GA
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
/**
* Sensor generated by hbm2java
*/
public class Sensor implements java.io.Serializable {
private Long idsensor;
private ModeloSensor modeloSensor;
private Mote mote;
private Proyecto proyecto;
private short dirSensor;
private String etiqueta;
private String ubicacion;
private BigDecimal gpsLatitud;
private BigDecimal gpsLongitud;
private String estadoSensor;
private Set datosProyectos = new HashSet(0);
public Sensor() {
}
public Sensor(ModeloSensor modeloSensor, Mote mote, short dirSensor, String etiqueta, String ubicacion, String estadoSensor) {
this.modeloSensor = modeloSensor;
this.mote = mote;
this.dirSensor = dirSensor;
this.etiqueta = etiqueta;
this.ubicacion = ubicacion;
this.estadoSensor = estadoSensor;
}
public Sensor(ModeloSensor modeloSensor, Mote mote, Proyecto proyecto, short dirSensor, String etiqueta, String ubicacion, BigDecimal gpsLatitud, BigDecimal gpsLongitud, String estadoSensor, Set datosProyectos) {
this.modeloSensor = modeloSensor;
this.mote = mote;
this.proyecto = proyecto;
this.dirSensor = dirSensor;
this.etiqueta = etiqueta;
this.ubicacion = ubicacion;
this.gpsLatitud = gpsLatitud;
this.gpsLongitud = gpsLongitud;
this.estadoSensor = estadoSensor;
this.datosProyectos = datosProyectos;
}
public Long getIdsensor() {
return this.idsensor;
}
public void setIdsensor(Long idsensor) {
this.idsensor = idsensor;
}
public ModeloSensor getModeloSensor() {
return this.modeloSensor;
}
public void setModeloSensor(ModeloSensor modeloSensor) {
this.modeloSensor = modeloSensor;
}
public Mote getMote() {
return this.mote;
}
public void setMote(Mote mote) {
this.mote = mote;
}
public Proyecto getProyecto() {
return this.proyecto;
}
public void setProyecto(Proyecto proyecto) {
this.proyecto = proyecto;
}
public short getDirSensor() {
return this.dirSensor;
}
public void setDirSensor(short dirSensor) {
this.dirSensor = dirSensor;
}
public String getEtiqueta() {
return this.etiqueta;
}
public void setEtiqueta(String etiqueta) {
this.etiqueta = etiqueta;
}
public String getUbicacion() {
return this.ubicacion;
}
public void setUbicacion(String ubicacion) {
this.ubicacion = ubicacion;
}
public BigDecimal getGpsLatitud() {
return this.gpsLatitud;
}
public void setGpsLatitud(BigDecimal gpsLatitud) {
this.gpsLatitud = gpsLatitud;
}
public BigDecimal getGpsLongitud() {
return this.gpsLongitud;
}
public void setGpsLongitud(BigDecimal gpsLongitud) {
this.gpsLongitud = gpsLongitud;
}
public String getEstadoSensor() {
return this.estadoSensor;
}
public void setEstadoSensor(String estadoSensor) {
this.estadoSensor = estadoSensor;
}
public Set getDatosProyectos() {
return this.datosProyectos;
}
public void setDatosProyectos(Set datosProyectos) {
this.datosProyectos = datosProyectos;
}
}
TipoSensor POJO Class
package sipiaHibernate;
// Generated 23/08/2012 15:10:47 by Hibernate Tools 3.2.1.GA
import java.util.HashSet;
import java.util.Set;
/**
* TipoSensor generated by hbm2java
*/
public class TipoSensor implements java.io.Serializable {
private Long idtipoSensor;
private ModeloSensor modeloSensor;
private String tipoDescripcion;
private String unidad;
private Float valorMinimo;
private Float valorMaximo;
private Set modeloSensors = new HashSet(0);
public TipoSensor() {
}
public TipoSensor(ModeloSensor modeloSensor) {
this.modeloSensor = modeloSensor;
}
public TipoSensor(ModeloSensor modeloSensor, String tipoDescripcion, String unidad, Float valorMinimo, Float valorMaximo, Set modeloSensors) {
this.modeloSensor = modeloSensor;
this.tipoDescripcion = tipoDescripcion;
this.unidad = unidad;
this.valorMinimo = valorMinimo;
this.valorMaximo = valorMaximo;
this.modeloSensors = modeloSensors;
}
public Long getIdtipoSensor() {
return this.idtipoSensor;
}
public void setIdtipoSensor(Long idtipoSensor) {
this.idtipoSensor = idtipoSensor;
}
public ModeloSensor getModeloSensor() {
return this.modeloSensor;
}
public void setModeloSensor(ModeloSensor modeloSensor) {
this.modeloSensor = modeloSensor;
}
public String getTipoDescripcion() {
return this.tipoDescripcion;
}
public void setTipoDescripcion(String tipoDescripcion) {
this.tipoDescripcion = tipoDescripcion;
}
public String getUnidad() {
return this.unidad;
}
public void setUnidad(String unidad) {
this.unidad = unidad;
}
public Float getValorMinimo() {
return this.valorMinimo;
}
public void setValorMinimo(Float valorMinimo) {
this.valorMinimo = valorMinimo;
}
public Float getValorMaximo() {
return this.valorMaximo;
}
public void setValorMaximo(Float valorMaximo) {
this.valorMaximo = valorMaximo;
}
public Set getModeloSensors() {
return this.modeloSensors;
}
public void setModeloSensors(Set modeloSensors) {
this.modeloSensors = modeloSensors;
}
}
I'm going to appreciate your help. Thanks in advance
Exists your TipoSensor class? The mapping hibernate not found your class

Categories

Resources