I am trying to issue a select from database using HQL
here is the code:
public Collection<Link> getAllLinksForDevice(Device device) {
Session session = sessionFactory.getCurrentSession();
String hql = "SELECT Link as l WHERE l.device1 = :deviceId OR l.device2 = :deviceId";
Query query = session.createQuery(hql); <-- Fails here!!
query.setParameter("deviceId",device.getId());
Collection<Link> linkList = query.list();
return linkList;
}
and the link entity:
@Id
@Column(name = "id")
@GeneratedValue
private int id;
@ManyToOne
@JoinColumn(name="device1_id")
private Device device1;
@ManyToOne
@JoinColumn(name="device2_id")
private Device device2;
The device Entity:
@Entity
@Table(name = "device")
public class Device {
@Id
@Column(name = "id")
@GeneratedValue
private int id;
@Column(name = "dns_Name")
private String dnsName;
@Column(name = "ip_address_v4")
private String ipV4;
@Column(name = "device_type")
private int deviceType;
@ManyToOne
@JoinColumn(name="area_id")
private Area area;
But I get an exception:
15:10:55,570 DEBUG ErrorCounter:51 – :0:0: unexpected end of subtree
:0:0: unexpected end of subtree
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3117)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:720)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:571)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:288)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:231)
at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:254)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185)
and:
15:10:55,622 ERROR PARSER:56 – Invalid path: ‘l.device1’
15:10:55,628 DEBUG ErrorCounter:51 – Invalid path: ‘l.device1’
Invalid path: ‘l.device1’
at org.hibernate.hql.ast.util.LiteralProcessor.lookupConstant(LiteralProcessor.java:135)
at org.hibernate.hql.ast.tree.DotNode.resolve(DotNode.java:216)
at org.hibernate.hql.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:117)
at org.hibernate.hql.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:113)
at org.hibernate.hql.ast.HqlSqlWalker.resolve(HqlSqlWalker.java:854)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1293)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4243)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:3722)
You have two syntax errors in your HQL query:
select Link as l where...is invalid. The proper syntax isselect l from Link as l where ...or simplyselect l from Link l where....device1(anddevice2field) field of the Link entity is of typeDevice. You can’t compare it with an ID. Either you compare it with aDeviceinstance, or you compare the ID ofdevice1with an ID:where l.device1 = :someDeviceInstanceContainingTheIdYouSearchFororwhere l.device1.id = :someDeviceId.