Display value from db in web page using hibernate - java

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 .../>.

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?

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" />

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

Multiple occurrence of custom CompositeUserType in Hibernate causing MappingException

Hi I have the following code:
public class Trail {
private int trailID;
private Location startLocation;
private Location destination;
// Getters and setters
}
which Location is a custom DB type, it's not a table
public class LocationType implements org.hibernate.usertype.CompositeUserType {
#Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {
if ( value == null ) {
DoubleType.INSTANCE.set(st, null, index, session);
DoubleType.INSTANCE.set(st, null, index+1, session);
DoubleType.INSTANCE.set(st, null, index+2, session);
StringType.INSTANCE.set(st, null, index+3, session);
} else {
final Location loc = (Location) value;
DoubleType.INSTANCE.set(st, loc.getLatitude(), index, session);
DoubleType.INSTANCE.set(st, loc.getLongitude(), index+1, session);
DoubleType.INSTANCE.set(st, loc.getAltitude(), index+2, session);
StringType.INSTANCE.set(st, loc.getDescription(), index+3, session);
}
}
// Other functions
}
and this is my Location class
public class Location implements Serializable {
...
}
The Trail.hbm.xml looks like this:
<hibernate-mapping package="com.mytest.walking">
<class name="Trail" table="TB_Trail" dynamic-insert="true">
<id name="TrailID" column="TrailID" >
<generator class="native"/>
</id>
<property name="StartLocation" type="LocationType" >
<column name="latitude" />
<column name="longitude" />
<column name="altitude" />
<column name="description" />
</property>
<property name="Destination" type="LocationType" >
<column name="latitude" />
<column name="longitude" />
<column name="altitude" />
<column name="description" />
</property>
</class>
</hibernate-mapping>
Then I got the following exception
Caused by: org.hibernate.MappingException: property mapping has wrong number of columns: com.mytest.walking.Trail.Destination type: com.mytest.walking.LocationType
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:468)
at org.hibernate.mapping.RootClass.validate(RootClass.java:268)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1287)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1729)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1775)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:184)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:314)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
Can someone point me to the right direction on how to get rid of this exception?
why not use a componentmapping
<component name="StartLocation" >
<property name="..." column="latitude" />
<property name="..." column="longitude" />
<property name="..." column="altitude" />
<property name="..." column="description" />
</property>
<component name="Destination" >
<property name="..." column="latitude" />
<property name="..." column="longitude" />
<property name="..." column="altitude" />
<property name="..." column="description" />
</property>
I found the answer. Just name the columns differently. They don't need to be same as the custom type name.
<hibernate-mapping package="com.mytest.walking">
<class name="Trail" table="TB_Trail" dynamic-insert="true">
<id name="TrailID" column="TrailID" >
<generator class="native"/>
</id>
<property name="StartLocation" type="LocationType" >
<column name="StartLocationLatitude" />
<column name="StartLocationLongitude" />
<column name="StartLocationAltitude" />
<column name="StartLocationDescription" />
</property>
<property name="Destination" type="LocationType" >
<column name="DestinationLatitude" />
<column name="DestinationLongitude" />
<column name="DestinationAltitude" />
<column name="DestinationDescription" />
</property>
</class>
</hibernate-mapping>

Categories

Resources