带连接的Hibernate查询:QuerySyntaxException:意外令牌

时间:2015-03-15 15:28:55

标签: java database hibernate join orm

我想使用join进行查询,我测试了但是我有这个错误

  

org.hibernate.hql.ast.QuerySyntaxException:意外令牌..

我做了:

public List <Card>getCard(Client c) {
        ClientDAO cd = new ClientDAO();
        List<Card> ca = getSessionFactory().getCurrentSession().createQuery("select ca.column1,e.column2 from card ca join ens e on ca.ide=e.ide where ca.idclient="+ cd.getClient(c).getIdclient()).list();//this is a method to get the current client
        return ca;

1 个答案:

答案 0 :(得分:0)

您使用SQL语法编写HQL查询。如果Card实体具有ens关联,您可以编写如下查询:

List<Card> ca = getSessionFactory().getCurrentSession()
    .createQuery(
        "select ca " +
                "from Card ca " +
                "join fetch ca.ens " +
                "where ca.idclient = :idclient")
        .setParameter("idclient", cd.getClient(c).getIdclient())
        .list();
    return ca;
}

如果您想要SQL查询,由于您有投影,您可以改为编写本机查询:

List<Object[]> ca = getSessionFactory().getCurrentSession()
    .createSQLQuery(
        "select ca.column1, e.column2 " +
        "from card ca " +
        "join ens e on ca.ide=e.ide " +
        "where ca.idclient = :idclient")
    .setParameter("idclient", cd.getClient(c).getIdclient())
.list();

在这种情况下,您获得List Object[]。每个Object[]都与选定的行相关联,每个数组元素都是一个列值。