I have a query where i am joining two tables ROuteMaster and RouteHalts.
When i perform inner join i am getting
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: on near line 1,
column 169 [SELECT rm.id , rm.routeCode , rm.startPlaceId , rm.endPlaceId ,
rm.active, rm.linkedRoute FROM com.oprs.pojo.routes.RouteMaster rm INNER JOIN
RouteHalts rh on rm.id = rh.routeId WHERE rh.placeId = :PlaceId
ORDER BY rm.id ASC]
I searched through the site and found similar question and the response for it. the question referred was
Hibernate: org.hibernate.hql.ast.QuerySyntaxException: unexpected token
I have many-to-one mapping in RouteHalts for RouteMaster, I have defined getter and setter methods for RouteMaster in RouteHalts
<many-to-one name="RouteMaster" class="com.oprs.pojo.routes.RouteMaster"
fetch="join"
foreign-key="id" column="ROUTE_ID" insert="false"
update="false" lazy="false" />
but still getting the same error. Can please some one guide me.
Mapping files
<hibernate-mapping package="com.oprs.pojo.routes">
<!-- Hibernate mapping for RouteMaster table -->
<class name="RouteMaster" table="OPRS_ROUTE_MASTER">
<id name="id" column="ROUTE_ID" type="java.lang.Long">
<generator class="assigned" />
</id>
<property name="startPlaceId" column="START_PLACE_ID"/>
<property name="endPlaceId" column="END_PLACE_ID"/>
<property name="routeCode" column="ROUTE_CODE"/>
<property name="routeName" column="ROUTE_NAME"/>
<property name="active" column="IS_ACTIVE"/>
<property name="linkedRoute" column="LINKED_ROUTE"/>
<property name="returnRouteId" column="RET_ROUTE_ID"/>
<!-- Auditor Information -->
<component name="auditor" class="com.oprs.pojo.base.Auditor">
<property name="createdBy" column="CREATED_BY" />
<property name="createdDate" column="CREATED_DATE" />
<property name="modifiedBy" column="MODIFIED_BY" />
<property name="modifiedDate" column="MODIFIED_DATE" />
</component>
<many-to-one name="RouteHalts" class="com.oprs.pojo.routes.RouteHalts" fetch="join"
foreign-key="routeId" column="ROUTE_ID" insert="false"
update="false" lazy="false" />
</class>
<!-- Hibernate mapping for RouteHalts table -->
<class name="RouteHalts" table="OPRS_ROUTE_HALTS">
<id name="id" column="HALTS_ID" type="java.lang.Long">
<generator class="assigned" />
</id>
<property name="routeId" column="ROUTE_ID"/>
<property name="placeId" column="PLACE_ID"/>
<property name="seqNo" column="SEQ_NO"/>
<property name="distanceKM" column="DISTANCE_KM"/>
<property name="border" column="IS_BORDER"/>
<property name="tolls" column="NO_OF_TOLLS"/>
<!-- Auditor Information -->
<component name="auditor" class="com.oprs.pojo.base.Auditor">
<property name="createdBy" column="CREATED_BY" />
<property name="createdDate" column="CREATED_DATE" />
<property name="modifiedBy" column="MODIFIED_BY" />
<property name="modifiedDate" column="MODIFIED_DATE" />
</component>
</class>
POJO of Route Master
public class RouteMaster extends Persistent {
private static final long serialVersionUID = -5710336066048392949L;
private Long startPlaceId;
private Long endPlaceId;
private Long returnRouteId;
private String startPlaceCode;
private String endPlaceCode;
private String startPlaceName;
private String endPlaceName;
private String routeCode;
private String routeName;
private String active;
private Auditor auditor;
private boolean revervseRoute;
private String linkedRoute = AppConstants.N;
private Map<Double, RouteHalts> haltsMap;
private RouteHalts routeHalts;
public RouteHalts getRouteHalts() {
return routeHalts;
}
public void setRouteHalts(RouteHalts routeHalts) {
this.routeHalts = routeHalts;
}
public Long getStartPlaceId() {
return startPlaceId;
}
public void setStartPlaceId(Long startPlaceId) {
this.startPlaceId = startPlaceId;
}
public Long getEndPlaceId() {
return endPlaceId;
}
public void setEndPlaceId(Long endPlaceId) {
this.endPlaceId = endPlaceId;
}
public String getStartPlaceCode() {
return startPlaceCode;
}
public void setStartPlaceCode(String startPlaceCode) {
this.startPlaceCode = startPlaceCode;
}
public String getEndPlaceCode() {
return endPlaceCode;
}
public void setEndPlaceCode(String endPlaceCode) {
this.endPlaceCode = endPlaceCode;
}
public Long getReturnRouteId() {
return returnRouteId;
}
public void setReturnRouteId(Long returnRouteId) {
this.returnRouteId = returnRouteId;
}
public String getRouteCode() {
return routeCode;
}
public void setRouteCode(String routeCode) {
this.routeCode = routeCode;
}
public Auditor getAuditor() {
return auditor;
}
public void setAuditor(Auditor auditor) {
this.auditor = auditor;
}
public String getStartPlaceName() {
return startPlaceName;
}
public void setStartPlaceName(String startPlaceName) {
this.startPlaceName = startPlaceName;
}
public String getEndPlaceName() {
return endPlaceName;
}
public void setEndPlaceName(String endPlaceName) {
this.endPlaceName = endPlaceName;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public Map<Double, RouteHalts> getHaltsMap() {
return haltsMap;
}
public void setHaltsMap(Map<Double, RouteHalts> haltsMap) {
this.haltsMap = haltsMap;
}
public boolean isRevervseRoute() {
return revervseRoute;
}
public void setRevervseRoute(boolean revervseRoute) {
this.revervseRoute = revervseRoute;
}
public String getLinkedRoute() {
return linkedRoute;
}
public void setLinkedRoute(String linkedRoute) {
this.linkedRoute = linkedRoute;
}
public String getRouteName() {
return routeName;
}
public void setRouteName(String routeName) {
this.routeName = routeName;
}
}
POJO of RouteHalts
public class RouteHalts extends Persistent {
private static final long serialVersionUID = -1491637903595290895L;
private Long placeId;
private Long routeId;
private String placeCode;
private Double seqNo;
private Double distanceKM;
private boolean border;
private Auditor auditor;
private String placeName;
private String stateCode;
private String stopType;
private String departureTime;
private Integer tolls;
private String platformNo;
private Long stopTypeId;
private Integer linkSequenceNo;
private String actualTime;
private int arrivalDay;
public String getStateCode() {
return stateCode;
}
public void setStateCode(String stateCode) {
this.stateCode = stateCode;
}
public Long getRouteId() {
return routeId;
}
public void setRouteId(Long routeId) {
this.routeId = routeId;
}
public Long getPlaceId() {
return placeId;
}
public void setPlaceId(Long placeId) {
this.placeId = placeId;
}
public String getPlaceCode() {
return placeCode;
}
public void setPlaceCode(String placeCode) {
this.placeCode = placeCode;
}
public Double getDistanceKM() {
return distanceKM;
}
public void setDistanceKM(Double distanceKM) {
this.distanceKM = distanceKM;
}
public boolean isBorder() {
return border;
}
public void setBorder(boolean border) {
this.border = border;
}
public Auditor getAuditor() {
return auditor;
}
public void setAuditor(Auditor auditor) {
this.auditor = auditor;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public Double getSeqNo() {
return seqNo;
}
public void setSeqNo(Double seqNo) {
this.seqNo = seqNo;
}
public String getStopType() {
return stopType;
}
public void setStopType(String stopType) {
this.stopType = stopType;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public Integer getTolls() {
return tolls;
}
public void setTolls(Integer tolls) {
this.tolls = tolls;
}
public String getPlatformNo() {
return platformNo;
}
public void setPlatformNo(String platformNo) {
this.platformNo = platformNo;
}
public Long getStopTypeId() {
return stopTypeId;
}
public void setStopTypeId(Long stopTypeId) {
this.stopTypeId = stopTypeId;
}
public Integer getLinkSequenceNo() {
return linkSequenceNo;
}
public void setLinkSequenceNo(Integer linkSequenceNo) {
this.linkSequenceNo = linkSequenceNo;
}
public int getArrivalDay() {
return arrivalDay;
}
public void setArrivalDay(int arrivalDay) {
this.arrivalDay = arrivalDay;
}
public String getActualTime() {
return actualTime;
}
public void setActualTime(String actualTime) {
this.actualTime = actualTime;
}
}
You should not use explicit "JOIN ON" in HQL. Instead you can use implicit joining in HQL:
SELECT rm.id , rm.routeCode , rm.startPlaceId , rm.endPlaceId , rm.active , rm.linkedRoute
FROM com.abhibus.oprs.pojo.routes.RouteMaster rm
INNER JOIN rm.routeHalts rh WHERE rh.placeId = :PlaceId ORDER BY rm.id ASC
or you can use Theta style for writing join:
SELECT rm.id , rm.routeCode , rm.startPlaceId , rm.endPlaceId , rm.active , rm.linkedRoute
FROM com.abhibus.oprs.pojo.routes.RouteMaster rm, RouteHalts rh
WHERE rm.id = rh.routeId AND rh.placeId = :PlaceId ORDER BY rm.id ASC
Also you can execute your query as native SQL query, not HQL query. For this you should use
session.createSQLQuery(queryText);
instead of
session.createQuery(queryText);
And by the way, may be in your case in is better to fetch whole entity, not separated fields (columns)? For this you can use:
select rm from ...
This will return the List<RouteMaster> insted of List<Object[]>.
Change your query likes this;
SELECT rm.id, rm.routeCode, rm.startPlaceId, rm.endPlaceId, rm.active, rm.linkedRoute
FROM RouteMaster rm
INNER JOIN rm.routeHalts AS rh ON rm.id = rh.routeId
WHERE rh.placeId = :PlaceId
ORDER BY rm.id ASC
Related
i have problem when insert to my database. here my setup for insert to my database.
First, I have method for getExecutionReport
first what i import
import com.dxtr.hibernate.DAOInsert;
import com.dxtr.hibernate.newOrderSingleEntity;
private void getExecutionReport(quickfix.Message message, String tipeMessage) {
// TODO Auto-generated method stub
try {
System.out.print("Message "+ message);
System.out.print("getExecutionReport "+tipeMessage);
newOrderSingleEntity newordersingleObj = new newOrderSingleEntity();
newordersingleObj.setSymbol(message.getString(Symbol.FIELD));
System.out.print(" symbol "+message.getString(Symbol.FIELD));
newordersingleObj.setMsgType(tipeMessage);
System.out.print(" tipeMessage "+tipeMessage);
newordersingleObj.setBodyLength(216);
System.out.print(" Body Length "+216);
newordersingleObj.setFixProtocol("FIX.4.2");
System.out.print("FixProtocol +FIX.4.2");
newordersingleObj.setTransactTime(message.getString(TransactTime.FIELD));
System.out.print(" time " +message.getString(TransactTime.FIELD));
newordersingleObj.setClOrdID(message.getString(ClOrdID.FIELD));
System.out.print(" ClOrdID "+message.getString(ClOrdID.FIELD));
newordersingleObj.setOrderID(message.getString(OrderID.FIELD));
System.out.print(" OrderID "+message.getString(OrderID.FIELD));
newordersingleObj.setExecID(message.getString(ExecID.FIELD));
System.out.print(" ExecID "+message.getString(ExecID.FIELD));
newordersingleObj.setExecTransType(message.getString(ExecTransType.FIELD));
System.out.print(" ExecTransType "+message.getString(ExecTransType.FIELD));
newordersingleObj.setOrdType(message.getString(OrdType.FIELD));
System.out.print(" OrdType "+message.getString(OrdType.FIELD));
newordersingleObj.setExecType(message.getString(ExecType.FIELD));
System.out.print(" ExecType "+message.getString(ExecType.FIELD));
newordersingleObj.setOrdStatus(message.getString(OrdStatus.FIELD));
System.out.print(" OrdStatus "+message.getString(OrdStatus.FIELD));
newordersingleObj.setSide(message.getInt(Side.FIELD));
System.out.print(" Side "+message.getInt(Side.FIELD));
newordersingleObj.setOrderQty(message.getDouble(OrderQty.FIELD));
System.out.print(" OrderQty "+message.getDouble(OrderQty.FIELD));
newordersingleObj.setLeavesQty(message.getDouble(LeavesQty.FIELD));
System.out.print(" LeavesQty "+message.getDouble(LeavesQty.FIELD));
newordersingleObj.setCumQty(message.getDouble(CumQty.FIELD));
System.out.print(" CumQty "+message.getDouble(CumQty.FIELD));
newordersingleObj.setLastShares(message.getInt(LastShares.FIELD));
System.out.print(" LastQty "+message.getInt(LastShares.FIELD));
System.out.print("sebelum insert ke db");
DAOInsert.newOrderSingleInsert(newordersingleObj);
} catch (FieldNotFound e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this code ok. but when i want to insert to my database my data cannot insert it.
here my entity
package com.dxtr.hibernate;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="New_Single_Order_Response",schema="dxtr_trades")
public class newOrderSingleEntity implements Serializable{
private static final long serialVersionUID = -1234424538928L;
#Id
#Column(name="response_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#Column(name="Fix_Protocol")
private String FixProtocol;
#Column(name="BodyLength")
private Integer BodyLength;
#Column(name="MsgSeqNum")
private Integer MsgSeqNum;
#Column(name="MsgType")
private String MsgType;
#Column(name="SenderCompId")
private String SenderCompId;
#Column(name="SendingTime")
private String SendingTime;
#Column(name="TargetCompID")
private String TargetCompID;
#Column(name="AveragePrice")
private Double AveragePrice;
#Column(name="ClOrdID")
private String ClOrdID;
#Column(name="CumQty")
private double CumQty;
#Column(name="Currency")
private String Currency;
#Column(name="ExecID")
private String ExecID;
#Column(name="LastShares")
private double LastShares;
#Column(name="OrderQty")
private Double OrderQty;
#Column(name="OrdStatus")
private String OrdStatus;
#Column(name="OrdType")
private String OrdType;
#Column(name="Side")
private Integer Side;
#Column(name="Symbol")
private String Symbol;
#Column(name="TransactTime")
private String TransactTime;
#Column(name="ExecType")
private String ExecType;
#Column(name="LeavesQty")
private double LeavesQty;
#Column(name="CheckSum")
private Integer CheckSum;
#Column(name="ExecTransType")
private String ExecTransType;
#Column(name="OrderID")
private String OrderID;
public Integer getResponse_ID() {
return this.id;
}
public void setResponse_ID(Integer id) {
this.id = id;
}
public String getFixProtocol() {
return this.FixProtocol;
}
public void setFixProtocol(String FixProtocol) {
this.FixProtocol = FixProtocol;
}
public Integer getBodyLength() {
return this.BodyLength;
}
public void setBodyLength(Integer BodyLength) {
this.BodyLength = BodyLength;
}
public Integer getMsgSeqNum() {
return this.MsgSeqNum;
}
public void setMsgSeqNum(Integer MsgSeqNum) {
this.MsgSeqNum = MsgSeqNum;
}
public String getMsgType() {
return this.MsgType;
}
public void setMsgType(String MsgType) {
this.MsgType = MsgType;
}
public String getSenderCompId() {
return this.SenderCompId;
}
public void setSenderCompId(String SenderCompId) {
this.SenderCompId = SenderCompId;
}
public String getSendingTime() {
return this.SendingTime;
}
public void setBodyLength(String SendingTime) {
this.SendingTime = SendingTime;
}
public String getTargetCompID() {
return this.TargetCompID;
}
public void setTargetCompID(String TargetCompID) {
this.TargetCompID = TargetCompID;
}
public Double getAveragePrice() {
return this.AveragePrice;
}
public void setAveragePrice(Double AveragePrice) {
this.AveragePrice = AveragePrice;
}
public String getClOrdID() {
return this.ClOrdID;
}
public void setClOrdID(String ClOrdID) {
this.ClOrdID = ClOrdID;
}
public double getCumQty() {
return this.CumQty;
}
public void setCumQty(double CumQty) {
this.CumQty = CumQty;
}
public String getCurrency() {
return this.Currency;
}
public void setCurrency(String Currency) {
this.Currency = Currency;
}
public String getExecID() {
return this.ExecID;
}
public void setExecID(String ExecID) {
this.ExecID = ExecID;
}
public double getLastShares() {
return this.LastShares;
}
public void setLastShares(double LastShares) {
this.LastShares = LastShares;
}
public Double getOrderQty() {
return this.OrderQty;
}
public void setOrderQty(Double OrderQty) {
this.OrderQty = OrderQty;
}
public String getExecType() {
return this.ExecType;
}
public void setExecType(String ExecType) {
this.ExecType = ExecType;
}
public String getOrdStatus() {
return this.OrdStatus;
}
public void setOrdStatus(String OrdStatus) {
this.OrdStatus = OrdStatus;
}
public String getOrdType() {
return this.OrdType;
}
public void setOrdType(String OrdType) {
this.OrdType = OrdType;
}
public Integer getSide() {
return this.Side;
}
public void setSide(Integer Side) {
this.Side = Side;
}
public String getSymbol() {
return this.Symbol;
}
public void setSymbol(String Symbol) {
this.Symbol = Symbol;
}
public String getTransactTime() {
return this.TransactTime;
}
public void setTransactTime(String TransactTime) {
this.TransactTime = TransactTime;
}
public double getLeavesQty() {
return this.LeavesQty;
}
public void setLeavesQty(double LeavesQty) {
this.LeavesQty = LeavesQty;
}
public Integer getCheckSum() {
return this.CheckSum;
}
public void setCheckSum(Integer CheckSum) {
this.CheckSum = CheckSum;
}
public String getExecTransType() {
return this.ExecTransType;
}
public void setExecTransType(String ExecTransType) {
this.ExecTransType = ExecTransType;
}
public String getOrderID() {
return this.OrderID;
}
public void setOrderID(String OrderID) {
this.OrderID = OrderID;
}
public String toString() {
return "OrderDetail?= Id: " + this.id + ", ClOrdID: " + this.ClOrdID + ", ExecID No.: " + this.ExecID + ", Symbol: " + this.Symbol;
}
}
and here my class for insert to database
package com.dxtr.hibernate;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import quickfix.StringField;
public class DAOInsert {
private DAOInsert dAOInsert;
static Session sessionObj;
static SessionFactory sessionFactoryObj;
public final static Logger logger = Logger.getLogger(DAOInsert.class);
// This Method Is Used To Create The Hibernate's SessionFactory Object
public static SessionFactory buildSessionFactory() {
// Creating Configuration Instance & Passing Hibernate Configuration File
Configuration configObj = new Configuration();
configObj.configure("hibernate.cfg.xml");
// Since Hibernate Version 4.x, ServiceRegistry Is Being Used
ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build();
// Creating Hibernate SessionFactory Instance
sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
return sessionFactoryObj;
}
public static void newOrderSingleInsert(newOrderSingleEntity newordersingleObj){
int count = 0;
try {
System.out.print("sudah di DAOInsert");
// Getting Session Object From SessionFactory
sessionObj = buildSessionFactory().openSession();
// Getting Transaction Object From Session Object
sessionObj.beginTransaction();
sessionObj.persist(newordersingleObj);
System.out.print(sessionObj.contains(newordersingleObj));
// Creating Transaction Entities
// newordersingleObj = new NewOrderSingle();
//newordersingleObj.setFixProtocol("FIX.4.2");
//newordersingleObj.setBodyLength(250);
//sessionObj.save(newordersingleObj);
//Committing The Transactions To The Database
sessionObj.getTransaction().commit();
//logger.info("\nSuccessfully Created '" + count + "' Records In The Database!\n");
} catch(Exception e) {
if(null != sessionObj.getTransaction()) {
logger.info("\n.......Transaction Is Being Rolled Back.......\n");
sessionObj.getTransaction().rollback();
}
e.printStackTrace();
} finally {
if(sessionObj != null) {
sessionObj.close();
}
}
}
}
i have also set persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="FastMatch" transaction-type="RESOURCE_LOCAL">
<class>com.dxtr.hibernate.newOrderSingleEntity</class>
<properties>
<property name="eclipselink.logging.level" value="INFO"/>
<property name="eclipselink.logging.level.sql" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://trades/tradesnew />
<property name="javax.persistence.jdbc.user" value="user" />
<property name="javax.persistence.jdbc.password" value="password" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="eclipselink.logging.level.connection" value="FINEST"/>
</properties>
</persistence-unit>
</persistence>
and also i have 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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://url/trades</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.dxtr.hibernate.newOrderSingleEntity"></mapping>
</session-factory>
</hibernate-configuration>
but when i want to insert to my database this data cannot insert it.. but i don't know where is the error... i have catch the error using
catch(Exception e) {
if(null != sessionObj.getTransaction()) {
logger.info("\n.......Transaction Is Being Rolled Back.......\n");
sessionObj.getTransaction().rollback();
}
e.printStackTrace();
} finally {
if(sessionObj != null) {
sessionObj.close();
}
but there is no error in my console print... so where is the problem from my code ?
for information i use mysql5.7 version and using aws
best regards,
Fuad
I would suggest you enable MySQL logs, then follow the instructions at https://dev.mysql.com/doc/refman/5.7/en/server-logs.html and be sure to flush the logs. The logs should be at /bar/log/MySQL
I am using hibernate in building a Restful Web Service (CRUD) in Java.
The problem is that when I return the data (GET) in some table that has some kind of relationship, I get the following error:
HTTP Status 500 - Internal Server Error
Type Exception Report
Message java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
When removing the bidirectional mapping created by hibernate on either side (table) the server returns to normal operation.
I use the Gson library to return and receive my requests in the JSON form.
Would anyone know how to solve this?
Thank you all for your help.
Here is a part of my controller code:
#GET
#Path("getConvenio")
#Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public String getConvenioList() {
Gson gson = new Gson();
List<Tbconveniado> l = new ArrayList();
try {
l = new ArrayList(op.getConveniadoList());
} catch (Exception ex) {
ex.printStackTrace();
}
return gson.toJson(l);
}
Following is the implementation of the "getConveniadoList" method that is present in the ConvenioOperations class:
public class ConvenioOperations {
public void setConvenio(Tbconveniado tb) {
Session s = HibernateUtil.getSessionFactory().openSession();
Transaction tx = s.beginTransaction();
s.saveOrUpdate(tb);
tx.commit();
s.close();
}
public List<Tbconveniado> getConveniadoList(){
Session s = HibernateUtil.getSessionFactory().openSession();
Transaction tx = s.beginTransaction();
List<Tbconveniado> l = null;
Query q = s.createQuery("from Tbconveniado c");
l = q.list();
tx.commit();
s.close();
return l;
}
}
Finally, the mapping and the class generated by hibernate to the table "Tbconveniado"
<hibernate-mapping>
<class name="pojos.Tbconveniado" table="tbconveniado" catalog="sindicatodb" optimistic-lock="version" >
<id name="idConveniado" type="int">
<column name="idConveniado" />
<generator class="assigned" />
</id>
<!-- foreign key -->
<many-to-one name="tbramo" class="pojos.Tbramo" fetch="select">
<column name="ramo" not-null="true" />
</many-to-one>
<property name="nome" type="string">
<column name="nome" length="100" />
</property>
<property name="dataConvenio" type="date">
<column name="dataConvenio" length="10" />
</property>
<property name="dataLimite" type="date">
<column name="dataLimite" length="10" />
</property>
<property name="endereco" type="string">
<column name="endereco" length="100" />
</property>
<property name="bairro" type="string">
<column name="bairro" length="100" />
</property>
<property name="cep" type="string">
<column name="cep" length="20" />
</property>
<property name="telefone" type="string">
<column name="telefone" length="20" />
</property>
<property name="cnpj" type="string">
<column name="cnpj" length="15" />
</property>
<property name="cidade" type="string">
<column name="cidade" length="100" />
</property>
<property name="status" type="java.lang.Integer">
<column name="status" />
</property>
<property name="email" type="string">
<column name="email" length="100" />
</property>
</class>
</hibernate-mapping>
Java Class for XML above:
public class Tbconveniado implements java.io.Serializable {
private int idConveniado;
private Tbramo tbramo;
private String nome;
private Date dataConvenio;
private Date dataLimite;
private String endereco;
private String bairro;
private String cep;
private String telefone;
private String cnpj;
private String cidade;
private Integer status;
private String email;
public Tbconveniado() {
}
public Tbconveniado(int idConveniado, Tbramo tbramo) {
this.idConveniado = idConveniado;
this.tbramo = tbramo;
}
public Tbconveniado(int idConveniado, Tbramo tbramo, String nome, Date dataConvenio, Date dataLimite, String endereco, String bairro, String cep, String telefone, String cnpj, String cidade, Integer status, String email) {
this.idConveniado = idConveniado;
this.tbramo = tbramo;
this.nome = nome;
this.dataConvenio = dataConvenio;
this.dataLimite = dataLimite;
this.endereco = endereco;
this.bairro = bairro;
this.cep = cep;
this.telefone = telefone;
this.cnpj = cnpj;
this.cidade = cidade;
this.status = status;
this.email = email;
}
public int getIdConveniado() {
return this.idConveniado;
}
public void setIdConveniado(int idConveniado) {
this.idConveniado = idConveniado;
}
public Tbramo getTbramo() {
return this.tbramo;
}
public void setTbramo(Tbramo tbramo) {
this.tbramo = tbramo;
}
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Date getDataConvenio() {
return this.dataConvenio;
}
public void setDataConvenio(Date dataConvenio) {
this.dataConvenio = dataConvenio;
}
public Date getDataLimite() {
return this.dataLimite;
}
public void setDataLimite(Date dataLimite) {
this.dataLimite = dataLimite;
}
public String getEndereco() {
return this.endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getBairro() {
return this.bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getCep() {
return this.cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getTelefone() {
return this.telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getCnpj() {
return this.cnpj;
}
public void setCnpj(String cnpj) {
this.cnpj = cnpj;
}
public String getCidade() {
return this.cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public Integer getStatus() {
return this.status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
}
I have situation where a movie can have lots of reviews, but a review is only ever related to one movie. I have had the issue as stated below, but as I have now tried so many permutations, I am actually little confused, so before I mess with my code anymore I thought it best to ask here.
Q.How should this be set up? Can I just hard set an movie_id as an int, in the review before I save a review? Or do I need to have a MovieDTO movie object as one of the objects in ReviewDTO class? And when I create a review object to be saved, that I call review.setMovie(someMovieObject)?
So here is what was going on in my code with errors:
First it complained that a not-null movie reference was not set (Hibernate : not-null property references a null or transient value), so after not being able to fix it, someone suggested to remove the constraint, to see if it would work.
Now it complains "java.lang.Integer cannot be cast to java.lang.String", but i am confused where there is the type mismatch? Class<->Hibernate or Hibernate<->DB?
Very confused, can someone please shed some light...? Thanks in advance.
package edu.unsw.comp9321.jdbc;
public class ReviewDTO {
private int id;
private String review;
private String rating;
private int client_id;
private int movie_id;
public ReviewDTO() {
}
public ReviewDTO(int id, String review, String rating, int client_id, int movie_id) {
super();
this.id = id;
this.review = review;
this.rating = rating;
this.client_id = client_id;
this.movie_id = movie_id;
}
public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public int getClient_id() {
return client_id;
}
public void setClient_id(String client_id) {
this.client_id = new Integer(client_id);
}
public int getMovie_id() {
return movie_id;
}
public void setMovie_id(int movie_id) {
this.movie_id = movie_id;
}
}
package edu.unsw.comp9321.jdbc;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.OneToMany;
public class MovieDTO implements Comparable {
private int id;
private String title;
private String poster;
private String director;
private String actors;
private String synopsis;
private String release_date;
private int cinema_id;
private Set<GenreDTO> genres = new HashSet<GenreDTO>();
private Set<ReviewDTO> reviews = new HashSet<ReviewDTO>();
private double rating;
public MovieDTO() {
}
public MovieDTO(int id, String title, String poster, String director,
String actors, String synopsis, String release_date, double rating) {
super();
this.id = id;
this.title = title;
this.poster = poster;
this.director = director;
this.actors = actors;
this.synopsis = synopsis;
this.release_date = release_date;
this.rating = rating;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPoster() {
return poster;
}
public void setPoster(String poster) {
this.poster = poster;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getActors() {
return actors;
}
public void setActors(String actors) {
this.actors = actors;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public String getRelease_date() {
return release_date;
}
public void setRelease_date(String release_date) {
this.release_date = release_date;
}
public Set<GenreDTO> getGenres() {
return genres;
}
public void setGenres(Set<GenreDTO> genres) {
this.genres = genres;
}
public Set<ReviewDTO> getReviews() {
return reviews;
}
public void setReviews(Set<ReviewDTO> reviews) {
this.reviews = reviews;
}
public int getCinema_id() {
return cinema_id;
}
public void setCinema_id(int cinema_id) {
this.cinema_id = cinema_id;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
#Override
public int compareTo(Object o) {
MovieDTO other = (MovieDTO) o;
if (this.rating > other.rating) return -1;
if (this.rating < other.rating) return 1;
return 0;
}
}
<?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="edu.unsw.comp9321.jdbc.ReviewDTO" table="Review" >
<id column="id" name="id">
<generator class="identity" />
</id>
<property column="review" name="review" type="string" />
<property column="rating" name="rating" type="string" />
<property column="client_id" name="client_id" type="string" />
<property column="movie_id" name="movie_id" type="string" />
</class>
</hibernate-mapping>
<?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="edu.unsw.comp9321.jdbc.MovieDTO" table="Movie" >
<id column="id" name="id">
<generator class="identity" />
</id>
<property column="title" name="title" type="string" />
<property column="poster" name="poster" type="string" />
<property column="director" name="director" type="string" />
<property column="actors" name="actors" type="string" />
<property column="synopsis" name="synopsis" type="string" />
<property column="release_date" name="release_date" type="string" />
<set name="genres" table="MovieHasGenre" >
<key column="movie_id" not-null="true" />
<many-to-many class="edu.unsw.comp9321.jdbc.GenreDTO" column="genre_id" />
</set>
<set name="reviews" table="Review" >
<key column="movie_id" />
<one-to-many class="edu.unsw.comp9321.jdbc.ReviewDTO" />
</set>
</class>
</hibernate-mapping>
The first error you receive is because you define <key column="movie_id" not-null="true" /> which means movie_id can not be null inside the GenreDTO of that MovieDTO. Somewhere in your code that value is null when trying to persist (not enough code shown to tell you where.)
The second error is because you define <property column="movie_id" name="movie_id" type="string" /> but in your ReviewDTO movie_id is an int. They should be the same.
As for your question, whether you should use movie_id or a MovieDTO in your ReviewDTO. That depends on a few things. Bi-directional relationships are fine (meaning ReviewDTO has a MovieDTO attached to it while that same MovieDTO has that same ReviewDTO in it's list of Reviews. However scale-ability and performance issues will happen if you have millions of entities. On the contrary leaving just movie_id Integer means anytime you want the MovieDTO object from a ReviewDTO you will have another database call... however this may not be too costly because if it was bi-directional, that call would have happened regardless.
I am getting following exception at query.can you please tell mw whats wrong is in my code?
org.hibernate.MappingException: No Dialect mapping for JDBC type: -1
at org.hibernate.dialect.TypeNames.get(TypeNames.java:79)
at org.hibernate.dialect.TypeNames.get(TypeNames.java:104)
at org.hibernate.dialect.Dialect.getHibernateTypeName(Dialect.java:393)
at org.hibernate.loader.custom.CustomLoader$Metadata.getHibernateType(CustomLoader.java:582
at org.hibernate.loader.custom.CustomLoader$ScalarResultColumnProcessor.performDiscovery(Custom Loader.java:508)
at org.hibernate.loader.custom.CustomLoader.autoDiscoverTypes(CustomLoader.java:524)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1821)
at org.hibernate.loader.Loader.doQuery(Loader.java:697)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
at org.hibernate.loader.Loader.doList(Loader.java:2232)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129)
at org.hibernate.loader.Loader.list(Loader.java:2124)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:312)
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1723)
at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165)
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:175)
at com.bdisys.promorphics.dao.impl.BlogDaoImpl.getTopBlogsQuesByDate(BlogDaoImpl.java:126)
at org.apache.jsp.Mydetails_jsp._jspService(Mydetails_jsp.java:935)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:381)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
at java.lang.Thread.run(Unknown Source)
Blog.java :
#SuppressWarnings("serial")
#Entity
#Table(name="blog")
public class Blog extends BaseDomain {
#Column(name="blog_title")
private String blogTitle;
#Column(name="blog_text",columnDefinition="TEXT")
private String blogText;
#Enumerated(EnumType.STRING)
#Column(name="blog_status")
private Status blogStatus;
#OneToOne
#JoinColumn(name="created_by", nullable=false)
private User createdBy;
#OneToOne
#JoinColumn(name="blog_category", nullable=false)
private BlogCategory blogCategory;
#Temporal(TemporalType.DATE)
#Column(name="created_date")
private Date createdDate;
#Column(name="likes")
private Long likes;
#Column(name="uploads")
private String uploads;
#Column(name="youtube_link")
private String youTubeLik;
#Column(name="moderator_comment")
private String moderatorComment;
#Lob
#Column(name="blog_description")
private String blog_desc;
#ManyToOne
#JoinColumn(name="users")
private User users;
public User getUsers() {
return users;
}
public void setUsers(User users) {
this.users = users;
}
public String getBlog_desc() {
return blog_desc;
}
public void setBlog_desc(String blog_desc) {
this.blog_desc = blog_desc;
}
public String getBlogTitle() {
return blogTitle;
}
public void setBlogTitle(String blogTitle) {
this.blogTitle = blogTitle;
}
public String getBlogText() {
return blogText;
}
public void setBlogText(String blogText) {
this.blogText = blogText;
}
public Status getBlogStatus() {
return blogStatus;
}
public void setBlogStatus(Status blogStatus) {
this.blogStatus = blogStatus;
}
public User getCreatedBy() {
return createdBy;
}
public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
}
public BlogCategory getBlogCategory() {
return blogCategory;
}
public void setBlogCategory(BlogCategory blogCategory) {
this.blogCategory = blogCategory;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Long getLikes() {
return likes;
}
public void setLikes(Long likes) {
this.likes = likes;
}
public String getUploads() {
return uploads;
}
public void setUploads(String uploads) {
this.uploads = uploads;
}
public String getYouTubeLik() {
return youTubeLik;
}
public void setYouTubeLik(String youTubeLik) {
this.youTubeLik = youTubeLik;
}
public String getModeratorComment() {
return moderatorComment;
}
public void setModeratorComment(String moderatorComment) {
this.moderatorComment = moderatorComment;
}
}
Askquestions.java :
#SuppressWarnings("serial")
#Entity
#Table(name="askquestions")
public class Askquestions extends BaseDomain {
#Column(length = 100, name = "id_subscribers")
private String idSubscribers;
#Column(length = 100, name = "is_anonymous")
private String isAnonymous;
#Column(length = 100, name = "display_name")
private String displayName;
#Temporal(TemporalType.DATE)
#Column(length = 100, name = "created_on")
private Date createdQuesOn;
#Lob
#Column(name = "ask_question")
private String askQuestion;
#Column(length = 100, name = "ask_to_whom")
private String askToWhom;
#Lob
#Column(name="question_of_day")
private String questionOfDay;
#ManyToOne
#JoinColumn(name="ask_category")
private Askcategory askcategory;
#ManyToOne
#JoinColumn(name="users")
private User users;
public User getUsers() {
return users;
}
public void setUsers(User users) {
this.users = users;
}
public Askcategory getAskcategory() {
return askcategory;
}
public void setAskcategory(Askcategory askcategory) {
this.askcategory = askcategory;
}
public String getQuestionOfDay() {
return questionOfDay;
}
public void setQuestionOfDay(String questionOfDay) {
this.questionOfDay = questionOfDay;
}
public String getIdSubscribers() {
return idSubscribers;
}
public void setIdSubscribers(String idSubscribers) {
this.idSubscribers = idSubscribers;
}
public String getIsAnonymous() {
return isAnonymous;
}
public void setIsAnonymous(String isAnonymous) {
this.isAnonymous = isAnonymous;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getAskQuestion() {
return askQuestion;
}
public void setAskQuestion(String askQuestion) {
this.askQuestion = askQuestion;
}
public String getAskToWhom() {
return askToWhom;
}
public void setAskToWhom(String askToWhom) {
this.askToWhom = askToWhom;
}
public Date getCreatedQuesOn() {
return createdQuesOn;
}
public void setCreatedQuesOn(Date createdQuesOn) {
this.createdQuesOn = createdQuesOn;
}
}
BlogDaoimpl Method:this query is not getting executed while other small queries are getting executed.why is it happening????
String sql = " select title , date from (select blog_title as title ,created_date as date from blog union select ask_question as title , created_on as date from askquestions ) as aa order by date desc";
SQLQuery query = getSession().createSQLQuery(sql);
return query.list();
hibrnate.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.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- <property name="hibernate.connection.password">websitebdi</property>
<property name="hibernate.connection.url">jdbc:mysql://184.172.182.251:3306/bdiwebsite</property>
<property name="hibernate.connection.username">bdiwebsite</property> -->
<property name="hibernate.connection.password">MAYbdiSYS2008</property>
<property name="hibernate.connection.url">jdbc:mysql://115.119.114.10:3306/bdisystems</property>
<property name="hibernate.connection.username">admin</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">false</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<property name="hibernate.connection.provider_class">
org.hibernate.connection.C3P0ConnectionProvider
</property>
<!-- The maximum number of connections -->
<property name="hibernate.c3p0.max_size">20</property>
<!-- The minimum number of connections -->
<property name="hibernate.c3p0.min_size">5</property>
<!-- Get a connection timeout , If you exceed this time , Throws an exception, in milliseconds -->
<property name="hibernate.c3p0.timeout">120</property>
<!-- The maximum number of PreparedStatement -->
<property name="hibernate.c3p0.max_statements">100</property>
<!-- Every 120 seconds checking connection idle connection in the pool, the unit is in seconds -->
<property name="hibernate.c3p0.idle_test_period">120</property>
<!-- When connection pooling connections inside out, look at the new C3P0 get the number of connections -->
<property name="hibernate.c3p0.acquire_increment">2</property>
<!-- Always verify the connection -->
<property name="hibernate.c3p0.validate">true</property>
<!--
<property name="hibernate.c3p0.max_size">100</property>
<property name="hibernate.c3p0.min_size">0</property>
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.idle_test_period">300</property>
<property name="hibernate.c3p0.max_statements">0</property>
<property name="hibernate.c3p0.timeout">100</property>
-->
<!-- Mapping Classes -->
<mapping class="com.bdisys.promorphics.domain.BlogCategory"/>
<mapping class="com.bdisys.promorphics.domain.Blog"/>
<mapping class="com.bdisys.promorphics.domain.Career"/>
<mapping class="com.bdisys.promorphics.domain.Partners"/>
<mapping class="com.bdisys.promorphics.domain.Askcategory"/>
<mapping class="com.bdisys.promorphics.domain.Askquestions"/>
<mapping class="com.bdisys.promorphics.domain.Askanswers"/>
</session-factory>
</hibernate-configuration>
Create a custom Dialect (extending MySQLDialect) and in your constructor add
registerHibernateType(Types.LONGVARCHAR, TextType.INSTANCE.getName());
public class MySQLDialect extends MySQLDialect {
public AGOSQLServerDialect() {
super();
registerHibernateType(Types.LONGVARCHAR, TextType.INSTANCE.getName());
}
}
Remember to change dialect class into Hibernate config file
<property name="hibernate.dialect">path.to.YourDialect</property>
my code like like this:
I want to select data in two tables
// ArrayList<DetailType> list = null;
SessionFactory sf = null;
Session ses = null;
try {
Configuration cfg = new Configuration().configure();
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(
cfg.getProperties()).buildServiceRegistry();
sf = cfg.buildSessionFactory(sr);
ses = sf.openSession();
// 执行查询语句
String hql = "select new DetailVoMain(d.d_id,d.d_name,m.m_name)"
+ "from MainType m, DetailType d "
+ "where d.d_main_id = m.m_id";
Query query = ses.createQuery(hql);
List<?> list = query.list();
for (int i = 0; i < list.size(); i++) {
DetailVoMain detailType = (DetailVoMain) list.get(i);
System.out.println("dId-------->" + detailType.getdId());
System.out.println("dNam-------->" + detailType.getdName());
System.out.println("mNam-------->" + detailType.getmName());
}
} catch (HibernateException e) {
System.out.println("hibernate exception");
e.printStackTrace();
} finally {
ses.close();
sf.close();
}
and myeclipese give me the error message:
hibernate exception
org.hibernate.QueryException: could not resolve property: d_id of: com.xunfang.em_mallServer.bean.DetailType [select new DetailVoMain(d.d_id,d.d_name,m.m_name)from com.xunfang.em_mallServer.bean.MainType m, com.xunfang.em_mallServer.bean.DetailType d where d.d_main_id = m.m_id]
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:77)
at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1968)
at org.hibernate.hql.internal.ast.tree.FromElementType.getPropertyType(FromElementType.java:313)
at org.hibernate.hql.internal.ast.tree.FromElement.getPropertyType(FromElement.java:490)
at org.hibernate.hql.internal.ast.tree.DotNode.getDataType(DotNode.java:616)
at org.hibernate.hql.internal.ast.tree.DotNode.prepareLhs(DotNode.java:267)
at org.hibernate.hql.internal.ast.tree.DotNode.resolve(DotNode.java:214)
at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:119)
at org.hibernate.hql.internal.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:115)
at org.hibernate.hql.internal.ast.tree.DotNode.resolveSelectExpression(DotNode.java:678)
at org.hibernate.hql.internal.ast.HqlSqlWalker.resolveSelectExpression(HqlSqlWalker.java:893)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2208)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.constructor(HqlSqlBaseWalker.java:2502)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2275)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExprList(HqlSqlBaseWalker.java:2145)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectClause(HqlSqlBaseWalker.java:1451)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:571)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:249)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:184)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:137)
at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:105)
at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:80)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1778)
at com.xunfang.em_mallServer.util.Test.main(Test.java:39)
please help me,i test all the night!
my MainType entity like this:
public class MainType {
private String mId; // 编号
private String mName; // 类别名称
public String getmId() {
return mId;
}
public void setmId(String mId) {
this.mId = mId;
}
public String getmName() {
return mName;
}
and mapping like this:
<hibernate-mapping package="com.xunfang.em_mallServer.bean">
<class name="MainType" table="t_main_type"> <!-- 设置表名和字段对应数据 -->
<id name="mId" column="m_id" type="string">
</id>
<property name="mName" column="m_name" type="string"></property>
</class>
DetailType entity like this:
public class DetailType {
/**
* 小类编号
*/
private String dId;
/**
* 小类名称
*/
private String dName;
/**
* 归属大类编号
*/
private String dMainId;
public String getdId() {
return dId;
}
public void setdId(String dId) {
this.dId = dId;
}
public String getdName() {
return dName;
}
public void setdName(String dName) {
this.dName = dName;
}
public String getdMainId() {
return dMainId;
}
public void setdMainId(String dMainId) {
this.dMainId = dMainId;
}
and the mapping:
<hibernate-mapping package="com.xunfang.em_mallServer.bean">
<class name="DetailType" table="t_detail_type"> <!-- 设置表名和字段对应数据 -->
<id name="dId" column="d_id" type="string">
</id>
<property name="dName" column="d_name" type="string"></property>
<property name="dMainId" column="d_main_id" type="string"></property>
</class>
thank you for help me!
You should write HQL correct, use mapping property, for example dId (instead of d_id).
You need to add relationship between your entities (i.e. OneToMany, ManyToOne).
After that you can join another entity in your hql.