为什么会出现此JPQL语法异常?

时间:2017-07-21 13:31:16

标签: java jpa

异常错误代码

EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpabook");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
TypedQuery<Member> query = em.createQuery("select m from Member m",Member.class);
List<Member> memberList = query.getResultList();

实体类

@Entity
@Table(name="MEMBER")
public class Member {
    @Id
    @Column(name="MEMBER_ID")
    private String id;
    @Column(name="USERNAME")
    private String username;
    @ManyToOne
    @JoinColumn(name="TEAM_ID", referencedColumnName = "TEAM_ID")
    private Team team;

    public Member() {
    }

    public Member(String id, String username) {
        this.id = id;
        this.username = username;
    }

    public String getId() {
        return id;
    }

    public Member setId(String id) {
        this.id = id;
        return this;
    }

    public String getUsername() {
        return username;
    }

    public Member setUsername(String username) {
        this.username = username;
        return this;
    }

    public Team getTeam() {
        return team;
    }

    public Member setTeam(Team team) {
        this.team = team;
        team.getMembers().add(this);
        return this;
    }

    @Override
    public String toString() {
        return "Member{" +
                "id='" + id + '\'' +
                ", username='" + username + '\'' +
                ", team=" + team +
                '}';
    }

}

异常消息

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: Member near line 1, column 15 [select m from Member m]

的pom.xml

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.10.Final</version>
</dependency>

我不知道为什么会出现这种异常,因为语法看起来很好。我们使用jpa作为团队项目。但上述问题仅适用于某些团队成员。我不知道什么环境会影响这种例外。

我知道Hibernate支持JPQL标准。

2 个答案:

答案 0 :(得分:0)

我不知道原因,但我解决了这个问题。问题是必须在包中声明实体类。如果在默认包中声明了实体类,则JPQL无法识别它。如果您知道问题的原因,我将非常感谢您的意见。

答案 1 :(得分:-1)

TypedQuery<Member> query = em.createQuery("from Member");

你试试看。不要使用select m子句。