Error SQL syntax? - java

I am using hibernate in my java program and I got some troubles using it ..
Here is my xml:
<hibernate-mapping>
<class name="revEngMapping.TestNetwork" table="testNetwork">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="networkElementId" type="string">
<column name="networkElement_id" length="45" />
</property>
<property name="date" type="string">
<column name="Date" length="45" />
</property>
<property name="oid" type="string">
<column name="Oid" length="150" />
</property>
<property name="value" type="string">
<column name="Value" length="200" />
</property>
</class>
here is my java class:
public class TestNetwork implements java.io.Serializable {
private Integer id;
private String networkElementId;
private String date;
private String oid;
private String value;
public TestNetwork() {
}
public TestNetwork(String networkElementId, String date, String oid,
String value) {
this.networkElementId = networkElementId;
this.date = date;
this.oid = oid;
this.value = value;
}
Then its just getters and setters, and in my main, I just want to display it:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Criteria crit = session.createCriteria(TestNetwork.class);
List resultList=crit.list();
for(int i=0;i<resultList.size();i++)
System.out.println(((TestNetwork)resultList.get(i)).getId()+" "+((TestNetwork)resultList.get(i)).getDate());
session.getTransaction().commit();
In my console it says that I have an SQL error ..
10:20:54,626 WARN JDBCExceptionReporter:233 - SQL Error: 1064, SQLState: 42000
10:20:54,628 ERROR JDBCExceptionReporter:234 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.testNetwork this_' at line 1
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.loader.Loader.doList(Loader.java:2536)
Hope s.one can help. thanks

mysql requires you to use backticks `` when accessing table names & columns, please back ticks while defining
eg..
<property name="someProperty" column="`dbColumnName`"/>
this should solve your problem..
Anantha Sharma

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

how to resolve "IllegalArgumentException occurred while calling setter for property"?

I'm trying get all the entries from Messages table using criteria
Criteria getCriteria = session.createCriteria(MessageAttributes.class);
List<MessageAttributes> unProcessedJcbMessagesList=getCriteria.list();
I'm getiing following exception when I'm trying run above criteria.
FieldId is the foreign key from AvailableFields(AvailableFieldsIs) table.
IllegalArgumentException occurred while calling setter for property [com.alu.jcb.model.MessageAttributes.fieldId (expected type = com.alu.jcb.model.AvailableFields)]; target = [com.alu.jcb.model.MessageAttributes#1cf3877], property value = [2]
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:123)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.setPropertyValues(AbstractEntityTuplizer.java:713)
at org.hibernate.tuple.entity.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:362)
at org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:4718)
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:188)
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:144)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1115)
at org.hibernate.loader.Loader.processResultSet(Loader.java:973)
at org.hibernate.loader.Loader.doQuery(Loader.java:921)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
at org.hibernate.loader.Loader.doList(Loader.java:2554)
at org.hibernate.loader.Loader.doList(Loader.java:2540)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)
at org.hibernate.loader.Loader.list(Loader.java:2365)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1718)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380)
at com.alu.jcb.messageProcessor.Test.main(Test.java:23)
Caused by: java.lang.IllegalArgumentException: argument type mismatch
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.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:68)
... 17 more
Beans
MessageAttributes.java
public class MessageAttributes {
private long messageAttributeId=1L;
private AvailableFields fieldId;
private String value;
//getters and setters
}
AvailableFields.java
public class AvailableFields {
private long availableFieldsId=1L;
private Instance instance;
private String fieldDisplayName;
//getters and setters
}
HBM files
MessageAttributes.hbm.xml
<hibernate-mapping package="com.alu.jcb.model">
<class name="MessageAttributes" table="MESSAGE_ATTRIBUTES">
<id name="messageAttributeId" column="message_attribute_id" type="long">
<generator class="sequence" />
</id>
<many-to-one name="fieldId" class="com.alu.jcb.model.AvailableFields" fetch="select">
<column name="field_id" not-null="true" />
</many-to-one>
<property name="value" type="string" column="value" />
</class>
</hibernate-mapping>
AvailableFields.hbm.xml
<hibernate-mapping package="com.alu.jcb.model">
<class name="AvailableFields" table="AVAILABLE_FIELDS">
<id name="availableFieldsId" column="available_fields_id" type="java.lang.Long">
<generator class="sequence" />
</id>
<many-to-one name="instance" class="com.alu.jcb.model.Instance" fetch="select">
<column name="instance_id" not-null="true" />
</many-to-one>
<property name="fieldDisplayName" type="string" column="field_display_name" not-null="true"/>
</class>
</hibernate-mapping>
Please help me
The error means something wrong with setter of fieldId. It should be like this
public void setFieldId(AvailableFields fieldId) {
this.fieldId=fieldId;
}
but it seems in your case incorrect class (guess long) is used in the setter.
SQLQuery sqlquery=session.createSQLQuery(queryString);
sqlquery.addScalar("fieldId ", IntegerType.INSTANCE);
I was receiving this error of
IllegalArgumentException occurred while calling setter for property
Version (type expected is Long but received 0)
because instead of using
Query query = sess.createSQLQuery(sqlQueryStr).addEntity(instance.getClass().getName());
retval = query.list();
I was doing
Query query = sess.createSQLQuery(sqlQueryStr)
.setResultTransformer(Transformers.aliasToBean(instance.getClass()));
retval = query.list();
In case it helps anyone.

Hibernate : Strange TypeCast Exception Thrown While retrieving records in Java from postgres database table

I am facing a strange type cast error ( Compile Time Error )
As soon as I retrieve the data from the journey table it throws following exception as it does not recognize the Object gotten from the list.
I don't know why it is complaining like this, As the object, is already of journey type and I made a list of templatized with "Journey" type, every record is supposed to be journey.
"INFO: HHH000397: Using ASTQueryTranslatorFactory
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to de.db.journeyTracker.model.journey
"
Code :
public static void findalljourney(Session session )
{
String qryAllJourney = "SELECT j.id , j.operatingday, j.linename, j.scheduledeparture, j.scheduledeparturestopname FROM journey j";
Query query = session.createQuery(qryAllJourney);
List<journey> allJourney;
allJourney = query.list();
for (int i = 0; i < allJourney.size(); i++)
{
String JourneyId = allJourney.get(i).getJourneyid().toString(); /// TypeCast Exception Occured...
}
Following is the Model class for journey.
public class journey
{
int id ;
String journeyid ;
String linename ;
Date operatingday ;
Date realtimearrival;
String realtimearrivalstopname;
String realtimearrivalstopnumber ;
Date realtimedeparture ;
String realtimedeparturestopname ;
String realtimedeparturestopnumber;
Date schedulearrival ;
String schedulearrivalstopname ;
String schedulearrivalstopnumber ;
Date scheduledeparture ;
String scheduledeparturestopname ;
String scheduledeparturestopnumber ;
int arrivaldelay ;
String direction ;
String journeyoperator ;
String schedulevehicletype ;
String vehicleid ;
Double distancerealtime;
int maximumspeedrealtime ;
Boolean calledatallstops ;
int departuredelay ;
int maximumdelay;
int minimumdelay ;
String phonenumber ;
int comment_id ;
Boolean arrivaldelayprojection ;
Boolean departuredelayprojection;
Boolean maximumdelayprojection ;
Boolean maximumspeedrealtimedataincomplete;
Boolean minmaxdelaydataincomplete ;
Boolean minimumdelayprojection ;
Boolean realtimearrivalprojection ;
Boolean realtimedepartureprojection ;
}
Following is hibernate config file corresponding to above journey model
<?xml version="1.0"?>
<hibernate-mapping>
<class name="de.db.journeyTracker.model.journey" table="JOURNEY">
<id name="id" type="int">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="journeyid" type="java.lang.String">
<column name="JOURNEYID" />
</property>
<property name="linename" type="java.lang.String">
<column name="LINENAME" />
</property>
<property name="operatingday" type="java.util.Date">
<column name="OPERATINGDAY" />
</property>
<property name="realtimearrival" type="java.util.Date">
<column name="REALTIMEARRIVAL" />
</property>
<property name="realtimearrivalstopname" type="java.lang.String">
<column name="REALTIMEARRIVALSTOPNAME" />
</property>
<property name="realtimearrivalstopnumber" type="java.lang.String">
<column name="REALTIMEARRIVALSTOPNUMBER" />
</property>
<property name="realtimedeparture" type="java.util.Date">
<column name="REALTIMEDEPARTURE" />
</property>
<property name="realtimedeparturestopname" type="java.lang.String">
<column name="REALTIMEDEPARTURESTOPNAME" />
</property>
<property name="realtimedeparturestopnumber" type="java.lang.String">
<column name="REALTIMEDEPARTURESTOPNUMBER" />
</property>
<property name="schedulearrival" type="java.util.Date">
<column name="SCHEDULEARRIVAL" />
</property>
<property name="schedulearrivalstopname" type="java.lang.String">
<column name="SCHEDULEARRIVALSTOPNAME" />
</property>
<property name="schedulearrivalstopnumber" type="java.lang.String">
<column name="SCHEDULEARRIVALSTOPNUMBER" />
</property>
<property name="scheduledeparture" type="java.util.Date">
<column name="SCHEDULEDEPARTURE" />
</property>
<property name="scheduledeparturestopname" type="java.lang.String">
<column name="SCHEDULEDEPARTURESTOPNAME" />
</property>
<property name="scheduledeparturestopnumber" type="java.lang.String">
<column name="SCHEDULEDEPARTURESTOPNUMBER" />
</property>
<property name="arrivaldelay" type="int">
<column name="ARRIVALDELAY" />
</property>
<property name="direction" type="java.lang.String">
<column name="DIRECTION" />
</property>
<property name="journeyoperator" type="java.lang.String">
<column name="JOURNEYOPERATOR" />
</property>
<property name="schedulevehicletype" type="java.lang.String">
<column name="SCHEDULEVEHICLETYPE" />
</property>
<property name="vehicleid" type="java.lang.String">
<column name="VEHICLEID" />
</property>
<property name="distancerealtime" type="java.lang.Double">
<column name="DISTANCEREALTIME" />
</property>
<property name="maximumspeedrealtime" type="int">
<column name="MAXIMUMSPEEDREALTIME" />
</property>
<property name="calledatallstops" type="java.lang.Boolean">
<column name="CALLEDATALLSTOPS" />
</property>
<property name="departuredelay" type="int">
<column name="DEPARTUREDELAY" />
</property>
<property name="maximumdelay" type="int">
<column name="MAXIMUMDELAY" />
</property>
<property name="minimumdelay" type="int">
<column name="MINIMUMDELAY" />
</property>
<property name="phonenumber" type="java.lang.String">
<column name="PHONENUMBER" />
</property>
<property name="comment_id" type="int">
<column name="COMMENT_ID" />
</property>
<property name="arrivaldelayprojection" type="java.lang.Boolean">
<column name="ARRIVALDELAYPROJECTION" />
</property>
<property name="departuredelayprojection" type="java.lang.Boolean">
<column name="DEPARTUREDELAYPROJECTION" />
</property>
<property name="maximumdelayprojection" type="java.lang.Boolean">
<column name="MAXIMUMDELAYPROJECTION" />
</property>
<property name="maximumspeedrealtimedataincomplete" type="java.lang.Boolean">
<column name="MAXIMUMSPEEDREALTIMEDATAINCOMPLETE" />
</property>
<property name="minmaxdelaydataincomplete" type="java.lang.Boolean">
<column name="MINMAXDELAYDATAINCOMPLETE" />
</property>
<property name="minimumdelayprojection" type="java.lang.Boolean">
<column name="MINIMUMDELAYPROJECTION" />
</property>
<property name="realtimearrivalprojection" type="java.lang.Boolean">
<column name="REALTIMEARRIVALPROJECTION" />
</property>
<property name="realtimedepartureprojection" type="java.lang.Boolean">
<column name="REALTIMEDEPARTUREPROJECTION" />
</property>
</class>
</hibernate-mapping>
and following is the main 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 >
<!-- Database connection settings -->
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/newTestDB</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.username">postgres</property>
<property name="connection.password">usman123</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- SQL dialect - generate SQL for a particular database -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Echo all executed SQL statements -->
<property name="show_sql">false</property>
<!-- Automatic schema creation (begin) ===
<property name="hibernate.hbm2ddl.auto">create</property>
Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Mapping resource configuration files -->
<mapping resource="de/db/journeyTracker/model/TestTable.hbm.xml"/>
<mapping resource="de/db/journeyTracker/model/gpspos.hbm.xml"/>
<mapping resource="de/db/journeyTracker/model/journey.hbm.xml"/>
<mapping resource="de/db/journeyTracker/model/trip.hbm.xml"/>
</session-factory> </hibernate-configuration>
Edit:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to de.db.journeyTracker.model.journey
at de.db.journeyTracker.model.journey.findalljourney(journey.java:323)
I tried the following code.. AS you suggested .. But Still it is giving the exception
List<Object[]> allJourney;
allJourney = query.list();
int Count = 0;
for (Object[] Journey : allJourney)
{
String strJourneyId = ((journey) Journey[0]).getJourneyid().toString();
String strOperatingDay = ((journey) Journey[0]).getOperatingday().toString();
String strLineName = ((journey) Journey[0]).getLinename();
String strSchedualeDeparture = ((journey) Journey[0]).getScheduledeparture().toString();
String strSchedualeDepartureStopName = ((journey) Journey[0]).getScheduledeparturestopname();
System.out.println(strJourneyId + " " + strOperatingDay + " " + strLineName + " " + strSchedualeDeparture + " " + strSchedualeDepartureStopName);
}
In Hibernate by using HSQL query
Try this type of query
1>String qryAllJourney = "from journey j";
this will return all journey table records without any typecasting exception.
Or - assuming that the class journey has an appropriate constructor - as an actual typesafe Java object:
String qryAllJourney = "select new journey(j.id , j.operatingday, j.linename, j.scheduledeparture, j.scheduledeparturestopname) from journey ";
If you want more details go through this link.
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html
This query:
SELECT j.id , j.operatingday, j.linename,
j.scheduledeparture, j.scheduledeparturestopname
FROM journey j
does not select List of Journey instances. Instead it selects List of Object arrays. Elements of array match to values in select list:
[0] = j.id
[1] = j.operatingday
...
Use following instead:
SELECT j FROM journey j
But if you want to stick with returned array, go for:
List<Object[]> allJourney = query.list();
//do what ever you need to do with result:
for (Object[] row: allJourney) {
Integer id = (Integer) row[0];
Date operatingday = (Date) row[1];
}
This should be a hsql query!
String qryAllJourney = "SELECT j.id , j.operatingday, j.linename, j.scheduledeparture, j.scheduledeparturestopname FROM journey j";
It should be something like this;
String qryAllJourney = "from Journey";

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