分析查询时出现语法错误(JPA)



我正在尝试使用以下代码

Query query;
query = entityManager.createQuery("SELECT g.name FROM group g INNER JOIN user_group ug INNER JOIN user u ON u.id = ug.userid AND ug.groupoid = g.id AND u.name = ?1 AND u.password = ?2");
query.setParameter(1, user.getName());
query.setParameter(2, user.getPassword());
Object result = (Object) query.getSingleResult();
String name = (String) result;

当我运行代码时,我得到了以下异常

Caused by: Exception [EclipseLink-8023] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Syntax error parsing the query [SELECT g.name FROM group g INNER JOIN user_group ug INNER JOIN user u ON u.id = ug.userid AND ug.groupoid = g.id AND u.name = ?1 AND u.password = ?2].
Internal Exception: org.eclipse.persistence.internal.libraries.antlr.runtime.EarlyExitException
    at org.eclipse.persistence.exceptions.JPQLException.syntaxError(JPQLException.java:352)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.handleRecognitionException(JPQLParser.java:354)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.addError(JPQLParser.java:246)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.reportError(JPQLParser.java:363)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.joinAssociationPathExpression(JPQLParser.java:2746)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.join(JPQLParser.java:2364)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.identificationVariableDeclaration(JPQLParser.java:2179)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.fromClause(JPQLParser.java:2043)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.selectStatement(JPQLParser.java:364)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.antlr.JPQLParser.document(JPQLParser.java:281)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.parse(JPQLParser.java:134)
    at org.eclipse.persistence.internal.jpa.parsing.jpql.JPQLParser.buildParseTree(JPQLParser.java:95)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:215)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:190)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:142)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:126)
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1475)
    ... 71 more

当我在mysql控制台上运行sql代码时,它是有效的。我想我没有正确地执行JPQL。

有人知道如何进行正确的查询吗?

编辑:我的小组课程是:

    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model.entities;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
 *
 * @author Felipe
 */
@Entity
@Table(name = &quot;grupo&quot;)
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = &quot;Grupo.findAll&quot;, query = &quot;SELECT g FROM Grupo g&quot;),
    @NamedQuery(name = &quot;Grupo.findById&quot;, query = &quot;SELECT g FROM Grupo g WHERE g.id = :id&quot;),
    @NamedQuery(name = &quot;Grupo.findByNome&quot;, query = &quot;SELECT g FROM Grupo g WHERE g.nome = :nome&quot;)})
public class Grupo implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = &quot;Id&quot;)
    private Integer id;
    @Size(max = 255)
    @Column(name = &quot;Nome&quot;)
    private String nome;
    @JoinTable(name = &quot;usuario_grupo&quot;, joinColumns = {
        @JoinColumn(name = &quot;GrupoID&quot;, referencedColumnName = &quot;Id&quot;)}, inverseJoinColumns = {
        @JoinColumn(name = &quot;UsuarioID&quot;, referencedColumnName = &quot;Id&quot;)})
    @ManyToMany(fetch = FetchType.EAGER)
    private Collection&lt;Usuario&gt; usuarioCollection;
    public Grupo() {
    }
    public Grupo(Integer id) {
        this.id = id;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    @XmlTransient
    public Collection&lt;Usuario&gt; getUsuarioCollection() {
        return usuarioCollection;
    }
    public void setUsuarioCollection(Collection&lt;Usuario&gt; usuarioCollection) {
        this.usuarioCollection = usuarioCollection;
    }
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }
    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Grupo)) {
            return false;
        }
        Grupo other = (Grupo) object;
        if ((this.id == null &amp;&amp; other.id != null) || (this.id != null &amp;&amp; !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }
    @Override
    public String toString() {
        return &quot;model.entities.Grupo[ id=&quot; + id + &quot; ]&quot;;
    }
}

我的User类是:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model.entities;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
 *
 * @author Felipe
 */
@Entity
@Table(name = &quot;usuario&quot;)
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = &quot;Usuario.findAll&quot;, query = &quot;SELECT u FROM Usuario u&quot;),
    @NamedQuery(name = &quot;Usuario.findById&quot;, query = &quot;SELECT u FROM Usuario u WHERE u.id = :id&quot;),
    @NamedQuery(name = &quot;Usuario.findBySenha&quot;, query = &quot;SELECT u FROM Usuario u WHERE u.senha = :senha&quot;),
    @NamedQuery(name = &quot;Usuario.findByNome&quot;, query = &quot;SELECT u FROM Usuario u WHERE u.nome = :nome&quot;)})
public class Usuario implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = &quot;Id&quot;)
    private Integer id;
    @Size(max = 255)
    @Column(name = &quot;Senha&quot;)
    private String senha;
    @Size(max = 255)
    @Column(name = &quot;Nome&quot;)
    private String nome;
    @ManyToMany(mappedBy = &quot;usuarioCollection&quot;, fetch = FetchType.EAGER)
    private Collection&lt;Grupo&gt; grupoCollection;
    public Usuario() {
    }
    public Usuario(Integer id) {
        this.id = id;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getSenha() {
        return senha;
    }
    public void setSenha(String senha) {
        this.senha = senha;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    @XmlTransient
    public Collection&lt;Grupo&gt; getGrupoCollection() {
        return grupoCollection;
    }
    public void setGrupoCollection(Collection&lt;Grupo&gt; grupoCollection) {
        this.grupoCollection = grupoCollection;
    }
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }
    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Usuario)) {
            return false;
        }
        Usuario other = (Usuario) object;
        if ((this.id == null &amp;&amp; other.id != null) || (this.id != null &amp;&amp; !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }
    @Override
    public String toString() {
        return &quot;model.entities.Usuario[ id=&quot; + id + &quot; ]&quot;;
    }
}

注意:这些类是由Netbeans生成的。注2:有些名字是用葡萄牙语写的。

实际上,如果你想通过用户名和密码获得组名,你可以如下重写查询:

SELECT g.nome FROM Grupo g INNER JOIN g.usuarioCollection u 
WHERE u.nome = ?1 AND u.senha = ?2

由于在JPQL中使用的是对象,而不是表,因此JOIN子句association fields是用@OneToMany@ManyToMany注释的字段。

您有FROM group ggroup不是保留字吗?

您的查询是SQL查询,而不是JPQL查询。JPQL!=SQL。我还建议不要通过用户名+密码来查询用户,因为这相当昂贵。相反,按用户的主键查询用户。您的查询应该如下所示:

select g.name from group g where :user in g.users

:user参数应该是一个用户实体。你可以这样设置:

query.setParameter("user", user);

话虽如此,请告诉我,"密码"栏只包含加密和加盐的密码。

最新更新