使用休眠将null保存为id [英] Saving null as id, with hibernate

查看:42
本文介绍了使用休眠将null保存为id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我处于一个奇怪的位置,需要将 @Entity @Id 保存为 null

I'm in a strange position where I need to save @Id of an @Entity as null

整个项目是使用休眠和实体构建的.但是对于这个旧实体,表本身就有一个触发器来生成ID.

The whole project is build using hibernate and entities. But for this one legacy entity, there is a trigger in the table itself to generate ID.

结果是,尝试插入非null的任何内容都会导致错误.

As a result, trying to insert anything but null will result in an error.

当尝试对id为null的实体进行 .save()时,休眠将抛出

When trying to .save() an entity with null id, hibernate will throw

org.springframework.orm.jpa.JpaSystemException: ids for this class must be manually assigned before calling save()

澄清,我需要做 .save(),其中ID列为空,因为:

Clarification, i need to do .save() where ID column is null because:

表中的触发器将(在任何插入之前)检查ID是否为null,然后执行SELECT获取最后一个ID并将其递增1,最后将此新行插入到表中.如果ID不为空,则触发器将出错.

Trigger in the table will (before any insert) check if ID is null, then do SELECT to get the last ID and increment that by 1 and finally insert this new row to table. The trigger will error in case ID is anything but null.

推荐答案

只需将ID标记为由基础数据库自动生成:

Just mark the id as autogenerated by the underlying database:

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

GenerationType.IDENTITY 通常用于将PK设置为自动增量的情况,但从JPA的角度来看,它只是在移动生成数据库引擎的ID.在您的情况下,使用触发器就可以做到这一点.

GenerationType.IDENTITY is generally designed for when the PK is set as auto increment but, from the JPA point of view, it is just moving the duty of generating the id to the database engine. And thats happening in your case by the usage of a trigger.

这篇关于使用休眠将null保存为id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆