Getting org.hibernate.MappingException - java

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

Related

Hibernate Query not returning anything, despite rows being present on the table

I have created this new entity on my project, and mapped it by using an hibernate.hbm.xml file, but the query never returns anything despite rows being present inside the Table. I get no errors during deploy, so i think the mapping is correct, but i don't understand why it never returns anything.
This is my code:
Entity(the getters and setters are present, i just didn't add them for brevity)
package com.rmm.lpo.be.data.model.po;
import java.util.Date;
public class ManageIotRequest implements java.io.Serializable, com.enel.framework.be.data.model.po.PersistentObject{
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private Long lotCode;
private String transformerCode;
private String creatorUserId;
private Boolean pushLpDataRequired;
private String deviceSelectionMode;
private String fileName;
private String fileType;
private Boolean flDiscarded;
private Date completionDate;
private String errorCode;
private String detailedErrorCode;
private Date creationDate;
private Date pDate; ```
HBM MAPPING
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN">
<!-- Generated 24 nov 2021, 17:10:37 by Hibernate Tools 3.4.0.CR1 -->
-<hibernate-mapping>
-<class dynamic-insert="true" dynamic-update="true" schema="LPO" table="MANAGE_IOT_REQUEST" name="com.rmm.lpo.be.data.model.po.ManageIotRequest">
<meta inherit="false" attribute="implements">com.enel.framework.be.data.model.po.PersistentObject</meta>
<comment>User request for changing Iot desired configuration</comment>
-<id name="id" type="java.lang.Long">
<column name="ID"/>
-<generator class="org.hibernate.id.enhanced.SequenceStyleGenerator">
<param name="optimizer">none</param>
<param name="sequence_name">SQ_LPO_ID</param>
<param name="increment_size">1</param>
</generator>
</id>
-<property name="lotCode" type="java.lang.Long">
-<column name="LOT_CODE" not-null="true" scale="0" precision="12">
<comment>Identification of the Lot</comment>
</column>
</property>
-<property name="transformerCode" type="string">
-<column name="TRANSFORMER_CODE" length="64">
<comment>Identification of the Transformer</comment>
</column>
</property>
-<property name="creatorUserId" type="string">
-<column name="CREATOR_USER_ID" length="16">
<comment>Identification of the user creator</comment>
</column>
</property>
-<property name="pushLpDataRequired" type="java.lang.Boolean">
-<column name="PUSH_LP_DATA_REQUIRED">
<comment>Number that identify the acquisition type. 1 = PUSH, 0 =PULL</comment>
</column>
</property>
-<property name="deviceSelectionMode" type="string">
-<column name="DEVICE_SELECTION_MODE" length="16">
<comment>String that identify the device selection mode</comment>
</column>
</property>
-<property name="fileName" type="string">
-<column name="FILE_NAME" length="256">
<comment>Name of the file that is used for the request</comment>
</column>
</property>
-<property name="fileType" type="string">
-<column name="FILE_TYPE" length="16">
<comment>Type of data contained in the file used for deviceselection</comment>
</column>
</property>
-<property name="flDiscarded" type="java.lang.Boolean">
-<column name="FL_DISCARDED">
<comment>1 = discarded request, 0 = executed request</comment>
</column>
</property>
-<property name="errorCode" type="string">
-<column name="ERROR_CODE" length="16">
<comment>String for technical errors</comment>
</column>
</property>
-<property name="detailedErrorCode" type="string">
-<column name="DETAILED_ERROR_CODE" length="16">
<comment>String for technical errors</comment>
</column>
</property>
-<property name="completionDate" type="java.util.Date">
-<column name="COMPLETION_DATE">
<comment>date/time of creation of the LPO</comment>
</column>
</property>
-<property name="creationDate" type="java.util.Date">
-<column name="CREATION_DATE" not-null="true">
<comment>date/time of creation of the LPO</comment>
</column>
</property>
-<property name="pDate" type="java.util.Date">
-<column name="PDATE" not-null="true">
<comment>PDATE</comment>
</column>
</property>
</class>
</hibernate-mapping>
and this is my DAO:
package com.rmm.lpo.be.data.dao;
#Named("manageIotRequestDao")
public class ManageIotRequestDaoImpl extends TwoBeatBaseHibernateCrudDao<ManageIotRequest, Long>
implements ManageIotRequestDao {
private ManageIotRequestPOConverter manageIotRequestPOConverter;
private static final String LOT_SEQUENCE = "SQ_MANAGE_IOT_REQUEST_LOT_CODE";
#Inject
public ManageIotRequestDaoImpl(
#Named("manageIotRequestPOConverter") ManageIotRequestPOConverter manageIotRequestPOConverter) {
this.manageIotRequestPOConverter = manageIotRequestPOConverter;
}
#Override
public List<ManageIotRequestBO> getIotRequestByLotCode(Long lotCode) throws DaoException {
List<ManageIotRequestBO> result = new ArrayList<ManageIotRequestBO>();
try {
logger.debug("getIotRequestByLotId starts with input: lotCode = {}", lotCode);
Query query=sessionFactory.getCurrentSession().createQuery("select m from com.enel.twobeat.rmm.lpo.be.data.model.po.ManageIotRequest m where m.lotCode = :lotCode");
query.setParameter("lotCode", lotCode);
List<ManageIotRequest> listPo = query.list();
if (listPo != null) {
for (ManageIotRequest po : listPo) {
ManageIotRequestBO bo = (ManageIotRequestBO) manageIotRequestPOConverter.convertPOtoBO(po);
result.add(bo);
}
}
logger.debug("getIotRequestByLotId ends with result = {}", result);
} catch (HibernateException | ConverterException e) {
throw new DaoException(e.getMessage(), e);
}
return result;
}
}
What am i doing wrong? I've also ran a query with no where conditions, just a simple select star, but it still returns nothing.
I checked my hibernate.cfg.xml file, and i found out that i hadn't mapped the entity there with the mapped-resource tag..could this be the problem?

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

Caused by: org.hibernate.MappingException: Duplicate property mapping of element found in

I am trying one-to-one mapping from statusHistoryLogs to element in hibernate. I am new in Hibernate. I have added one to one mapping in element.hbm.xml also.
I am getting the following error: Duplicate property mapping of element found in com.ot.entry.members.StatusHistoryLog.
Please guide me, where I am going wrong. Please correct my code.
StatusHistoryLog.hbm.xml
<hibernate-mapping>
<class dynamic-insert="true" dynamic-update="true" name="com.ot.entry.members.StatusHistoryLog" table="status_history_logs">
<id name="id" type="long">
<column name="id" sql-type="integer"/>
<generator class="native"/>
</id>
<property name="element" length="11" column="element_id" type="integer" />
<property name="status" length="11" column="status_id" type="integer" />
<one-to-one name="element" class="com.ot.entry.members.Element" constrained="true"/>
<property name="period" type="period">
<column name="start_date" not-null="true"/>
<column name="end_date"/>
</property>
</class>
</hibernate-mapping>
element.hbm.xml
<hibernate-mapping>
<class dynamic-insert="true" dynamic-update="true" name="com.ot.entry.members.Element" abstract="true" table="members">
<id name="id" type="long">
<column name="id" sql-type="integer"/>
<generator class="native"/>
</id>
<discriminator column="subclass" type="string" length="1"/>
<property name="name" length="100" column="name" type="string" not-null="true"/>
<property name="creationDate" column="creation_date" type="calendar" not-null="true"/>
<many-to-one name="group" class="com.ot.entry.groups.Group">
<column name="group_id" not-null="true" sql-type="integer"/>
</many-to-one>
<property name="status" column="status" not-null="false" length="1">
<type name="com.paynet.utils.hibernate.StringValuedEnumType">
<param name="enumClassName">com.ot.entry.members.Element$Status</param>
</type>
</property>
<property name="email" length="100" column="email" type="string" index="ix_email"/>
<property name="notificationLanguage" column="notification_language" length="6" not-null="false">
<type name="com.paynet.utils.hibernate.StringValuedEnumType">
<param name="enumClassName">com.ot.entry.settings.LocalSettings$Language</param>
</type>
</property>
<one-to-one name="user" cascade="all" class="com.ot.entry.access.User" />
<one-to-one name="statusHistoryLogs" cascade="all" class="com.ot.entry.members.StatusHistoryLog" />
<bag name="groupHistoryLogs" cascade="delete" inverse="true" order-by="start_date">
<key>
<column name="element_id" sql-type="integer"/>
</key>
<one-to-many class="com.ot.entry.groups.GroupHistoryLog"/>
</class>
</hibernate-mapping>
StatusHistoryLog.java
public class StatusHistoryLog extends Entity {
private static final long serialVersionUID = 68407121216377438L;
private Element element;
private Status status;
private Period period;
public Element getElement() {
return element;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Period getPeriod() {
return period;
}
public void setElement(final Element element) {
this.element = element;
}
public void setPeriod(final Period period) {
this.period = period;
}
#Override
public String toString() {
String string = getId() + ": " + getStatus().getValue() + " - begin: " + period.getBegin();
if (period.getEnd() != null) {
string += " - end: " + period.getEnd();
}
return string;
}
}
<property name="element" length="11" column="element_id" type="integer" />
should be
<property name="elementId" length="11" column="element_id" type="integer" />

Inserting many rows with hibernate is very slow

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

Display value from db in web page using hibernate

I have a simple web application which retrives all enterys from a db table and when clicked on shows more details from other tables. I am using hibernate to map the tables but i am having a problem displaying values from foreign keys. For example i want to display the actors name associated with a movie instead of "movie.Actor#5514f9"
<h:outputText value="Actors"/>
<h:outputText value="#{movieController.selected.actors}" title="Actors"/>
Is the code i am using to display the values.
My movieController class is
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package movie;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
/**
*
* #author Shane
*/
#ManagedBean(name = "movieController")
#SessionScoped
public class MovieController {
int startId;
int endId;
DataModel movieTitles;
MovieHelper helper;
//private int recordCount = 1000;
private int pageSize = 10;
private Movie current;
private int selectedItemIndex;
public List getActors() {
List actors = new ArrayList();
return actors;
}
/** Creates a new instance of MovieController */
public MovieController() {
helper = new MovieHelper();
startId = 1;
endId = 1000000;
}
public MovieController(int startId, int endId) {
helper = new MovieHelper();
this.startId = startId;
this.endId = endId;
}
public Movie getSelected() {
if (current == null) {
current = new Movie();
selectedItemIndex = -1;
}
return current;
}
public DataModel getMovieTitles() {
if (movieTitles == null) {
movieTitles = new ListDataModel(helper.getMovieTitles(startId, endId));
}
return movieTitles;
}
void recreateModel() {
movieTitles = null;
}
// The following methods that are used for page navigation
public boolean isHasNextPage() {
helper = new MovieHelper();
if (endId + pageSize <= helper.getRecordCount()) {
return true;
}
return false;
}
public boolean isHasPreviousPage() {
if (startId - pageSize > 0) {
return true;
}
return false;
}
public String next() {
startId = endId + 1;
endId = endId + pageSize;
recreateModel();
return "index";
}
public String previous() {
startId = startId - pageSize;
endId = endId - pageSize;
recreateModel();
return "index";
}
public int getPageSize() {
return pageSize;
}
public String prepareView() {
current = (Movie) getMovieTitles().getRowData();
return "browse";
}
public String prepareList() {
recreateModel();
return "index";
}
}
And my Movie.hbm.xml file is
<?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 26-Oct-2011 22:41:19 by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="movie.Movie" table="movie" catalog="movieserver">
<id name="id" type="int">
<column name="Id" />
<generator class="assigned" />
</id>
<property name="title" type="string">
<column name="Title" length="75" />
</property>
<property name="rating" type="string">
<column name="Rating" length="25" />
</property>
<property name="plot" type="string">
<column name="Plot" />
</property>
<property name="poster" type="string">
<column name="Poster" length="150" />
</property>
<property name="runtime" type="string">
<column name="Runtime" length="15" />
</property>
<property name="votes" type="string">
<column name="Votes" length="15" />
</property>
<property name="released" type="string">
<column name="Released" length="15" />
</property>
<property name="year" type="string">
<column name="Year" length="15" />
</property>
<property name="rated" type="string">
<column name="Rated" length="15" />
</property>
<property name="director" type="string">
<column name="Director" length="100" />
</property>
<set name="genres" inverse="false" table="movie_genre">
<key>
<column name="MovieId" not-null="true" />
</key>
<many-to-many entity-name="movie.Genre">
<column name="GenreId" not-null="true" />
</many-to-many>
</set>
<set name="writers" inverse="false" table="movie_writer">
<key>
<column name="MovieId" not-null="true" />
</key>
<many-to-many entity-name="movie.Writer">
<column name="WriterId" not-null="true" />
</many-to-many>
</set>
<set name="actors" inverse="false" table="movie_actor">
<key>
<column name="MovieId" not-null="true" />
</key>
<many-to-many entity-name="movie.Actor">
<column name="ActorId" not-null="true" />
</many-to-many>
</set>
</class>
</hibernate-mapping>
my current ouput is:
[movie.Actor#7b7bee, movie.Actor#10580fa, movie.Actor#3c6b88, movie.Actor#56a1b6]
but i am wondering how to display the actors name instead of the index of the actor?
any help on this would be great, thanks
Actors is a collection (set) in your case. You should iterate throw actors set and display name for each actor in collection.
"[<className>#<hashCode1>, <className>#<hashCode2>, ...]" - this is a string which method AbstractCollection.toString() returns (the movie actors set is AbstractCollection).
In turn "<className>#<hashCode>" - is a string which method Object.toString() returns (the object of class movie.Actor).
You could override method movie.Actor#toString() and make it return actor name. Then your page will render string like this: "[actor name1, actor name2, ...]".
But the correct approach is to use JSF components like <h:dataTable .../> or iterate through actor set with JSTL <c:forEach .../>.

Categories

Resources