在 DerbyDB 上使用 jpa 自动生成 Primary_key 时出现问题
我有 jpa 注释的实体类,如:
@Configurable
@Entity
@Table(name="PLAYERS")
public class Player
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="ID")
private Integer id;
@Column(name="NAME")
private String name;
@PersistenceContext
public transient EntityManager entityManager;
...
}
这一直工作得很好,直到我决定使用如下语法创建带有备份的 yaml 数据的表:
createNativeQuery("INSERT INTO PLAYERS ...")
成功创建后,当我尝试使用以下命令创建实体时:
Player player = new Player();
player.setName("new player");
player.persist();
我收到错误:
SQL Error: -1, SQLState: 23505
与 Primary_keys 的重复相关,因为为新实体生成的 id = 1(与从备份数据检索的行相同)。当然,我可以使用 jpa/java 语法从备份文件中检索数据,但在这种情况下,我无法控制插入数据的主键等。 如何解决这个问题?有没有办法在插入备份数据后更新 id_generator ?
I have jpa annotated entity class like:
@Configurable
@Entity
@Table(name="PLAYERS")
public class Player
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="ID")
private Integer id;
@Column(name="NAME")
private String name;
@PersistenceContext
public transient EntityManager entityManager;
...
}
This has worked fine until I decided to create table with backuped yaml data using syntax like:
createNativeQuery("INSERT INTO PLAYERS ...")
After successful creation when I try to create an entity with:
Player player = new Player();
player.setName("new player");
player.persist();
i got error:
SQL Error: -1, SQLState: 23505
related to the duplication of primary_keys, because id generated for new entity = 1 (the same as row retrived from backuped data). Of course I can retrive data from backup file by using jpa/java syntax but in this case I have no control over primary keys of inserted data etc.
How to solve this problem ? Is there any way to update id_generator after the insertion of backuped data ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您手动插入数据,因此需要更改表以更改标识列的起始值:
其中 1234 是备份数据的最大 id。
更多详细信息,请参阅 ALTER TABLE 语句 的文档:
Because you inserted data manually, you need to alter the table to change the start value of the identity column:
Where 1234 is the max id of your backup data.
More details in the documentation of the ALTER TABLE statement: