how to use hibernate hql to select datas in two tables? - java

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.

Related

"java.lang.IllegalArgumentException: Unable to locate Attribute with the the given name", although attribute is set

Hibernate 5.6 with Spring 5.3 here.
When creating predicates to fetch data from a table with this code:
CriteriaBuilder cb = this.getSession().getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(aliasToBeanClass);
Root root = cq.from(aliasToBeanClass); // aliasToBeanClass is set to UmsUserRoleVOImpl
predicates.add(cb.equal(root.get(key), value)); // key is set to "userName" - this line is causing the exception
I get this error:
java.lang.IllegalArgumentException: Unable to locate Attribute with
the the given name [userName] on this ManagedType
[com.myapp.ums.business.impl.UmsUserRoleVOImpl]
But the attribute userName is included in my VO, as well as a public setter and it's mapped in my .hbm.xml file:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.myapp.ums.business.impl.UmsUserRoleVOImpl" table="ums_t_user_role"
proxy="com.myapp.ums.common.business.UmsUserRoleVO">
<composite-id>
<key-property name="userName" type="java.lang.String" column="fk_user_id"/>
<key-property name="roleName" type="java.lang.String" column="fk_role_id"/>
</composite-id>
</class>
</hibernate-mapping>
This is my VO:
public class UmsUserRoleVOImpl extends AbstractBasePropertiesImpl implements UmsUserRoleVO {
private static final long serialVersionUID = 2393634151578825216L;
private String roleName;
private String userName;
private List<PmPropertyVO> properties;
public UmsUserRoleVOImpl() {
}
#Get(AbstractBaseProperties.ROWGUID)
#Override
public Long getRowguid() {
return super.getRowguid();
}
#Set(AbstractBaseProperties.ROWGUID)
#Override
public void setRowguid(final Long rowguid) {
super.setRowguid(rowguid);
}
#Get(UmsUserRoleVO.ROLE_NAME)
public String getRoleName() {
return roleName;
}
#Set(UmsUserRoleVO.ROLE_NAME)
public void setRoleName(String roleName) {
this.roleName = roleName;
}
#GetCollection(value = UmsUserRoleVO.PROPERTIES, defaultObject = "com.myapp.pm.business.impl.PmPropertyVOImpl")
public List<PmPropertyVO> getProperties() {
return properties;
}
#SetCollection(value = UmsUserRoleVO.PROPERTIES, defaultObject = "com.myapp.pm.business.impl.PmPropertyVOImpl")
public void setProperties(List<PmPropertyVO> properties) {
this.properties = properties;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof UmsUserRoleVOImpl)) {
return false;
}
UmsUserRoleVOImpl user = (UmsUserRoleVOImpl) o;
if (!(roleName.equals(user.getRoleName()))) {
return false;
}
return userName.equals(user.getUserName());
}
public int hashCode() {
int result = 17;
result = 29 * result + (roleName != null ? roleName.hashCode() : 0);
result = 29 * result + (userName != null ? userName.hashCode() : 0);
return result;
}
public String toString() {
return roleName + " " + userName;
}
#Get(UmsUserRoleVO.USER_NAME)
public String getUserName() {
return this.userName;
}
#Set(UmsUserRoleVO.USER_NAME)
public void setUserName(String userName) {
this.userName = userName;
}
There seems to be something wrong with the mapping, because Hibernate does not find any attribute of the UmsUserRoleVOImpl:
Any idea what could be causing this error?

Can not cast java.lang.Object to custom object

I was trying to fetch hql query result assigned to custom class by casting the Object reference. but it throws for exception. But i have seen developers casting object reference returned from query to custom class reference without any issues.
What i wanted is,
//Address class
package car;
public class Address {
private int addId;
private String city;
private String country;
public String getCity() {
return city;
}
public int getAddId() {
return addId;
}
public void setAddId(int addId) {
this.addId = addId;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
//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 = "car.Address" table = "studentAddress">
<id name = "addId">
<generator class = "assigned"/>
</id>
<property name = "city" column = "city"/>
<property name = "country" column = "country" />
</class>
</hibernate-mapping>
//Test class
public class Main {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("retail\\resources\\hibernate.cfg.xml");
SessionFactory s = cfg.buildSessionFactory();
Session ss = s.openSession();
Transaction t = ss.beginTransaction();
Student stu = new Student();
stu.setSid(11);
stu.setName("Thanweer");
stu.setAge(28);
Address a = new Address();
a.setAddId(22);
a.setCity("Colombo");
a.setCountry("Sri Lanka");
Query q = ss.createQuery("select city,country from Address a where a.city = 'Colombo'" );
Address a2 = (Address)q.uniqueResult();
System.out.println(a2.getAddId()+" "+a2.getCity()+" "+a2.getCountry());
}
}
Exception Occurs is :
INFO: HHH000232: Schema update complete
Hibernate: select address0_.city as col_0_0_, address0_.country as col_1_0_ from studentAddress address0_ where address0_.city='Colombo'
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to car.Address
at test.Main.main(Main.java:36)
Following HQL
select city,country from Address a where a.city = 'Colombo'
selects List of Object arrays. Thats why [Ljava.lang.Object;For further details please refer to this question.
In each array index 0 contains String city and index 1 contains String country. With uniqueResult() result is no more list, but simply array of objects. When Address is preferred, one should select Address as follows:
Query q = ss.createQuery("select a from Address a where a.city = 'Colombo'" );
Address a2 = (Address)q.uniqueResult();

MYSQL SQL syntax error while i use hibernate

I am using hibernate as a persistence layer, here is the sample of my code, but here my hql queries:
Query q = s.createQuery("from Login where name=:user and passw =:passw");
q.setParameter("user",username);
q.setParameter("passw", passw);
Query q = s.createSQLQuery("SELECT * from Good where Good.supplier =:supl AND Good.name =:gname AND Good.dates >=:sdate and Good.dates <=:fdate").addEntity(Good.class);
q.setParameter("supl",sup);
q.setParameter("gname", gname);
q.setParameter("sdate", sdate);
q.setParameter("fdate",fdate);
sdate and fdate parametrs are string, are they ok in this case? it throws this exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '.login login0_ where login0_.name='Tom'' at line 1
Login.hbm.xml
<hibernate-mapping>
<class name="kz.bimash.FoodSec.model.Login" table="login" catalog="foodsec">
<id name="id" type="java.lang.Integer">
<column name="Id" />
<generator class="increment" />
</id>
<property name="name" type="string">
<column name="name" length="50" not-null="true" unique="true" />
</property>
<property name="passw" type="string">
<column name="passw" length="50" not-null="true" />
</property>
<property name="type" type="string">
<column name="type" length="45" not-null="true" />
</property>
<property name="userId" type="int">
<column name="userId" not-null="true" />
</property>
</class>
Login pojo class
public class Login implements java.io.Serializable {
private Integer id;
private String name;
private String passw;
private String type;
private int userId;
public Login() {
}
public Login(String username, String password, String type, int userId) {
this.name = username;
this.passw = password;
this.type = type;
this.userId = userId;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String username) {
this.name = username;
}
public String getPassw() {
return this.passw;
}
public void setPassw(String password) {
this.passw = password;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public int getUserId() {
return this.userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
Login DAO class
#Repository
public class LoginDAO {
#Autowired
private SessionFactory sf;
#SuppressWarnings("empty-statement")
public String[] Authorise(String username, String passw){
Session s = sf.getCurrentSession();
s.beginTransaction();
Query q = s.createQuery("from Login where name=:user and passw =:passw");
q.setParameter("user",username);
q.setParameter("passw", passw);
q.setMaxResults(1);
String[] str = null;
Login login = null;
for(Iterator it = q.iterate(); it.hasNext();){
login = (Login)it.next();
}
if(login != null){
str = new String[]{login.getType(), String.valueOf(login.getUserId())};
}
s.getTransaction().commit();
return str;
}
public boolean checkLogin(String username){
Session s = sf.getCurrentSession();
s.beginTransaction();
// String s_sql ="SELECT * FROM Login WHERE NAME="+username;
Query q = s.createQuery("from Login where name = :usern");
q.setParameter("usern", username);
// Query q=s.createSQLQuery(s_sql);
List<Login> logins =null;
logins= (List<Login>)q.list();
s.getTransaction().commit();
if(logins !=null)
return true;
else
return false;
}
}
There's a problem with the following segment of the code:
Query q = s.createSQLQuery("SELECT * from Good where Good.supplier =:supl AND Good.name =:gname AND Good.dates >=:sdate and Good.dates <=:fdate").addEntity(Good.class);
You are writing an SQL & not an HQL. That is why you have used session.createSQLQuery(...) and not session.createQuery(...). createSQLQuery(...) always returns a reference of org.hibernate.SQLQuery, while you have assigned it to a variable of Query.
I'm surprised why didn't you get a Compile-time error.
Try to assign it to a SQLQuery variable & check whether it's working or not.

Hibernate Query Syntax exception : org.hibernate.hql.ast.QuerySyntaxException: unexpected token

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

Error trying to execute a stored procedure with Hibernate and PostgreSQL

I'm trying to execute a stored procedure with hibernate (Java Persistence API) and postgreSQL. My mapping file looks as follows:
<?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>
<sql-query name="getnotificaciones" callable="true">
<return alias="notificacion"
class="tempranillo.entidades.sistemanotificaciones.NotificacionDB" lock-mode="read">
<return-property name="fecha" column="fecha"/>
<return-property name="notificacion" column="notificacioncolumn"/>
<return-property name="xmlnotificacion" column="xmlcolumn"/>
</return>
{call getnotificaciones(:idusuario)}
</sql-query>
</hibernate-mapping>
The stored procedure is shown below:
CREATE OR REPLACE FUNCTION getNotificaciones(idusuario int4,
OUT fecha date,
OUT notificacioncolumn varchar,
OUT xmlcolumn xml
)
RETURNS SETOF record
AS $$
SELECT
INFONOT.fecha,
INFONOT.notificacion,
xmlelement (name notificacion, xmlattributes(current_date as "fecha",
INFONOT.xmlTipoNotificacion as "tipoNotificacion"),
xmlelement (name infovino,
xmlforest(
tvinos.idvino,
tvinos.nombre,
tvinos.tipovino,
tvinos.anio,
tvinos.variedad,
tvinos.zona,
tvinos.pais)
),
xmlelement (name infousuario,
xmlforest(
tusuarios.idusuario,
tusuarios.ALIAS)
),
xmlelement (name infologro,
xmlforest(
tlogros.idlogro,
tlogros.nombrelogro,
tlogros.descripcion
)
)
)
FROM
public.tusuarios
INNER JOIN
(SELECT DISTINCT(xpath('//Notificacion/usuarioOrigina
/id/text()',xmlnotificacion::xml))[1]::varchar::int4 as xmlidusuario,
(xpath('//Notificacion/vino/idvino/text()',xmlnotificacion::xml
[1]::varchar::int4 as XMLIDVINO,
(xpath('//Notificacion/tipoNotificacion/text()',xmlnotificacion::xml
[1]::varchar as xmlTipoNotificacion,
(xpath('//Notificacion/Logro/IdLogro/text()',xmlnotificacion::xml
[1]::varchar::int4 as xmlIdLogro,
public.tnotificacion.idnotificacion,
public.tnotificacion.fecha,
public.tnotificacion.notificacion
FROM
public.tamistad RIGHT OUTER JOIN public.tnotificacion ON
(public.tamistad.idamigo= public.tnotificacion.idusuario)
WHERE (public.tamistad.idusuario = $1 OR public.tnotificacion.idusuario = $1) AND
public.tnotificacion.xmlnotificacion IS NOT NULL) AS INFONOT
ON (public.tusuarios.idusuario = INFONOT.xmlidusuario)
LEFT OUTER JOIN public.tvinos
on (public.tvinos.idvino = INFONOT.xmlidvino)
LEFT OUTER JOIN public.tlogros
on (public.tlogros.idlogro = INFONOT.xmlIdLogro)
ORDER BY
INFONOT.fecha DESC;
$$ LANGUAGE SQL;
The entity declared in java as follows:
package tempranillo.entidades.sistemanotificaciones;
public class NotificacionDB implements Serializable {
public NotificacionDB() {
}
public NotificacionDB(int idusuario,
Date fecha,
String notificacion) {
this.idusuario = idusuario;
this.fecha = fecha;
this.notificacion = notificacion;
}
public NotificacionDB(int idusuario,
Date fecha,
String notificacion,
String xmlnotificacion) {
this.idusuario = idusuario;
this.fecha = fecha;
this.notificacion = notificacion;
this.xmlnotificacion = xmlnotificacion;
}
private int idnotificacion;
public int getIdnotificacion() {
return idnotificacion;
}
private void setIdnotificacion(int idnotificacion) {
this.idnotificacion = idnotificacion;
}
private int idusuario;
public int getIdusuario() {
return idusuario;
}
public void setIdusuario(int idusuario) {
this.idusuario = idusuario;
}
private Date fecha;
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
private String notificacion;
public String getNotificacion() {
return notificacion;
}
public void setNotificacion(String notificacion) {
this.notificacion = notificacion;
}
private String xmlnotificacion;
public String getXmlnotificacion() {
return xmlnotificacion;
}
public void setXmlnotificacion(String xmlnotificacion) {
this.xmlnotificacion = xmlnotificacion;
}
}
When I try to execute the following code:
Query query = sesion.getNamedQuery("getnotificaciones");
query.setInteger("idusuario", idusuario);
List listanotificaciones = query.list();
I always get the same error: There is a problema with the postgreSQLDialect.
I tried with select * from getnotificaciones (:idusuario) but in this case I get "could not execute query" error message.
Can anyone help me?
It seems like Java can not take your RETURNS SETOF recordand you could find some references for that part.

Categories

Resources