0

我正在尝试使用 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)的子树意外结束。 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.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:254) 在 org.hibernate.hql.ast 的 org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:231) .QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185)

和:

15:10:55,622 错误解析器:56 - 无效路径:'l.device1' 15:10:55,628 调试错误计数器:51 - 无效路径:'l.device1' 无效路径:org.hibernate.hql 中的'l.device1' .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.爪哇:3722)

4

1 回答 1

2

您的 HQL 查询中有两个语法错误:

  1. 没有 from 子句。select Link as l where...是无效的。正确的语法是select l from Link as l where ...或简单地select l from Link l where....
  2. Link 实体的device1(和device2字段)字段的类型为Device。你不能将它与身份证进行比较。要么将其与Device实例进行比较,要么将 的 IDdevice1与 ID:where l.device1 = :someDeviceInstanceContainingTheIdYouSearchFor或进行比较where l.device1.id = :someDeviceId
于 2012-06-03T13:46:46.647 回答