gpt4 book ai didi

java - JPA:当我尝试保留一个对象时出现奇怪的错误

转载 作者:搜寻专家 更新时间:2023-11-01 01:19:32 24 4
gpt4 key购买 nike

我在 UserGroup 之间建立了一个 OneToMany 关系
Group.java

@Entity
public class Group {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String groupid;

@ManyToOne
@JoinColumn(name="USER_FK")
private User user;
...
}

用户.java

@Entity
public class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String userId;

private String password;

private String fname;

private String lname;

@OneToMany(mappedBy="user", cascade=CascadeType.ALL)
private List<Group> groups;

public void addGroup(Group group){
if(this.groups == null){
this.groups = new ArrayList<Group>();
}
this.groups.add(group);
group.setUser(this);
}
}

所以当我尝试持久化对象时

    User user = em.find(User.class, 1L);
user.addGroup(group);
persist(user);

我明白了

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 (ID, GROUPID, USER_FK) VALUES (2501, 'fdsaf', 1)' at line 1
Error Code: 1064
Call: INSERT INTO GROUP (ID, GROUPID, USER_FK) VALUES (?, ?, ?)
bind => [2501, fdsaf, 1]
Query: InsertObjectQuery(org.xdrawings.entity.Group@a1c)

如您所见,它尝试插入正确的值,但不知何故它被标记为语法错误。我认为它缺少 GROUP 周围的单引号,但由于它在后台进行查询,我不知道如何修复它。请注意,我对同一项目中的其他实体做了完全相同的事情,并且效果很好。好沮丧!!

最佳答案

GROUP 确实是保留关键字,您必须对其进行转义。在 JPA 2.0 中,有一种标准化的方法来指定定界标识符。来自 JPA 2.0 规范:

2.13 Naming of Database Objects

...

To specify delimited identifiers, one of the following approaches must be used:

  • It is possible to specify that all database identifiers in use for a persistence unit be treated as delimited identifiers by specifying the <delimited-identifiers/> element within the persistence-unit-defaults element of the object/relational xml mapping file. If the <delimited-identifiers/> element is specified, it cannot be overridden.
  • It is possible to specify on a per-name basis that a name for a database object is to be interpreted as a delimited identifier as follows:
    • Using annotations, a name is specified as a delimited identifier by enclosing the name within double quotes, whereby the inner quotes are escaped, e.g., @Table(name="\"customer\"").
    • When using XML, a name is specified as a delimited identifier by use of double quotes, e.g., <table name="&quot;customer&quot;"/>

所以这样的事情应该可行:

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

关于java - JPA:当我尝试保留一个对象时出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3462477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com