JPQL MySQLSyntaxErrorException:您的SQL语法中有错误

时间:2010-09-05 14:41:29

标签: java exception orm jpa-2.0 jpql

我有两个实体User和Group:

@Entity
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    private String username;
    private String password;
    private String email;
    @ManyToMany
    @JoinTable(name="user_group", joinColumns={@JoinColumn(name="USERNAME")}, inverseJoinColumns={@JoinColumn(name="ID")})
    private List<Group> group;

    // getters and setters...
}

@Entity
public class Group implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    private String id;

    // getters and setters...
}

它是ManyToMany单向的。它生成表useruser_group。现在我有简单的查询:

Query q = em.createQuery("select g from Group g");
List<Group> usersGroup = q.getResultList();

抛出异常:

Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP' at line 1
Error Code: 1064
Call: SELECT ID FROM GROUP
Query: ReadAllQuery(referenceClass=Group sql="SELECT ID FROM GROUP")
... stack trace...

2 个答案:

答案 0 :(得分:5)

只要告诉JPA提供程序必须将这些名称解释为分隔标识符,就可以对数据库对象使用GroupUser

使用JPA 2.0和注释,通过将名称括在双引号内,将名称指定为分隔标识符,从而对内引号进行转义:

@Entity
@Table(name="\"User\"")
public class User implements Serializable {
    ...
}

@Entity
@Table(name="\"Group\"")
public class Group implements Serializable {
    ...
}

参考

  • JPA 2.0规范
    • 第2.13节“数据库对象的命名”

答案 1 :(得分:2)

不要将您的用户组实体称为“群组”。它是MySQL语法中的保留字,用于聚合为GROUP BY

尝试将其称为其他内容,例如“UserGroup”。