Hibernate:从可调用的自定义插入接收生成的 ID
我有一个带有
@Entity
@SQLInsert(callable = true, sql = "{ call sp_InsertEntity(?, ?, ?) }")
public class Entity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "entity_id")
private int entityId;
...
}
sp_InsertEntity 的实体类执行标准 INSERT 并返回@@IDENTITY。 但是在session.save(entity)entityId值仍然是0之后。
如何强制Hibernate使用返回值或输出参数或@@IDENTITY或SCOPE_IDENTITY()来初始化生成的ID?
I have an entity class with
@Entity
@SQLInsert(callable = true, sql = "{ call sp_InsertEntity(?, ?, ?) }")
public class Entity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "entity_id")
private int entityId;
...
}
sp_InsertEntity does standard INSERT and returns @@IDENTITY.
But after session.save(entity) entityId value remains 0.
How to force Hibernate using the returned value or an output parameter or @@IDENTITY or SCOPE_IDENTITY() for the generated ID initialization?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许是为了向遇到同样问题的其他人澄清一下 - 当您使用
false
时,hibernate 将不会自动生成其 SELECT SCOPE_IDENTITY() 在您的过程之后(这显然首先不起作用,因为该选择与插入不在同一范围内),因此您必须手动添加在存储过程中插入后选择 SCOPE_IDENTITY()。以这种方式编写插入存储过程还将使它们与实体框架处理事物的方式兼容,这是一个很好的优点。
Maybe to clarify it a bit for others that run into the same problem - when you use
<property name="jdbc.use_get_generated_keys">false</property>
, hibernate will not automatically generate its SELECT SCOPE_IDENTITY() after your procedure (which obviously doesn't work in the first place, because that select isn't in the same scope as the insert), hence you have to manually add the SELECT SCOPE_IDENTITY() after the insert within the stored procedure.Writing your insert stored procedures in this way will also make them compatible with how Entity Framework handles things, which is a nice plus.