在 Hibernate 中绕过 GeneratedValue(合并不在 db 中的数据?) [英] Bypass GeneratedValue in Hibernate (merge data not in db?)

查看:25
本文介绍了在 Hibernate 中绕过 GeneratedValue(合并不在 db 中的数据?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与[1][2].我需要手动设置默认自动生成的值(为什么?导入旧数据).如 [1] 中所述,使用 Hibernate 的 entity = em.merge(entity) 可以解决问题.

My problem is the same as described in [1] or [2]. I need to manually set a by default auto-generated value (why? importing old data). As described in [1] using Hibernate's entity = em.merge(entity) will do the trick.

不幸的是,我没有.我既没有收到错误,也没有收到任何其他警告.该实体只是不会出现在数据库中.我使用的是 Spring 和 Hibernate EntityManager 3.5.3-Final.

Unfortunately for me it does not. I neither get an error nor any other warning. The entity is just not going to appear in the database. I'm using Spring and Hibernate EntityManager 3.5.3-Final.

有什么想法吗?

推荐答案

它适用于我的项目,代码如下:

it works on my project with the following code:

@XmlAttribute
@Id
@Basic(optional = false)
@GeneratedValue(strategy=GenerationType.IDENTITY, generator="IdOrGenerated")
@GenericGenerator(name="IdOrGenerated",
                  strategy="....UseIdOrGenerate"
)
@Column(name = "ID", nullable = false)
private Integer id;

import org.hibernate.id.IdentityGenerator;
...
public class UseIdOrGenerate extends IdentityGenerator {
private static final Logger log = Logger.getLogger(UseIdOrGenerate.class.getName());

@Override
public Serializable generate(SessionImplementor session, Object obj) throws HibernateException {
    if (obj == null) throw new HibernateException(new NullPointerException()) ;

    if ((((EntityWithId) obj).getId()) == null) {
        Serializable id = super.generate(session, obj) ;
        return id;
    } else {
        return ((EntityWithId) obj).getId();

    }
}

基本上定义自己的 ID 生成器(基于身份策略),如果未设置 ID,则将生成委托给默认生成器.

where you basically define your own ID generator (based on the Identity strategy), and if the ID is not set, you delegate the generation to the default generator.

主要缺点是它将您绑定到 Hibernate 作为 JPA 提供程序......但它与我的 MySQL 项目完美配合

The main drawback is that it bounds you to Hibernate as JPA provider ... but it works perfectly with my MySQL project

这篇关于在 Hibernate 中绕过 GeneratedValue(合并不在 db 中的数据?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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