2

我有两个实体用户和组:

@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...
}

它是多对多单向的。它生成表格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...
4

2 回答 2

5

只要您告诉 JPA 提供者这些名称必须被解释为定界标识符,您就可以将orGroup用于数据库对象。User

使用 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 节“数据库对象的命名”
于 2010-09-05T21:01:18.940 回答
2

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

尝试将其称为其他名称,例如“用户组”。

于 2010-09-05T14:44:41.763 回答