我正在尝试使用HQL从数据库中发出选择
这是代码:
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;
}
和链接实体:
@Id
@Column(name = "id")
@GeneratedValue
private int id;
@ManyToOne
@JoinColumn(name="device1_id")
private Device device1;
@ManyToOne
@JoinColumn(name="device2_id")
private Device device2;
设备实体:
@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;
但我得到一个例外:
15:10:55,570 DEBUG ErrorCounter:51 - :0:0:子树意外结束 :0:0:子树的意外结束 在org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3117) 在org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:720) 在org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:571) 在org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:288) 在org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:231) 在org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:254) 在org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185)
和
15:10:54,622 ERROR PARSER:56 - 路径无效:'l.device1' 15:10:54,628 DEBUG ErrorCounter:51 - 路径无效:'l.device1' 路径无效:'l.device1' 在org.hibernate.hql.ast.util.LiteralProcessor.lookupConstant(LiteralProcessor.java:135) 在org.hibernate.hql.ast.tree.DotNode.resolve(DotNode.java:216) 在org.hibernate.hql.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:117) 在org.hibernate.hql.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:113) 在org.hibernate.hql.ast.HqlSqlWalker.resolve(HqlSqlWalker.java:854) 在org.hibernate.hql.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1293) 在org.hibernate.hql.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4243) 在org.hibernate.hql.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:3722)
答案 0 :(得分:2)
您的HQL查询中有两个语法错误:
select Link as l where...
无效。正确的语法是select l from Link as l where ...
或只是select l from Link l where...
。device1
(和device2
字段)字段属于Device
类型。您无法将其与ID进行比较。您可以将其与Device
个实例进行比较,也可以将device1
的ID与ID where l.device1 = :someDeviceInstanceContainingTheIdYouSearchFor
或where l.device1.id = :someDeviceId
进行比较。