合并不在数据库中的数据

合并不在数据库中的数据

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

问题描述

我的问题与中介绍的相同或。我需要手动设置默认自动生成的值(为什么?导入旧数据)。如中所述,使用Hibernate的 entity = em.merge(实体)可以做到这一点。



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



有什么想法?

解决方案


$ b

  @XmlAttribute 
@Id
@Basic(可选= 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)抛出HibernateException {
if(obj == null)抛出新的HibernateException(new NullPointerException()); ((((EntityWithId)obj).getId())== null){
Serializable id = super.generate(session,obj);

if
return id;
} else {
return((EntityWithId)obj).getId();


$ b $ / code $ / pre

您基本上定义了您自己的ID生成器(基于Identity策略),并且如果ID未设置,则将生成委派给默认生成器。

主要缺点是它会限制您Hibernate作为JPA提供程序......但它与我的MySQL项目完美地兼容


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.

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.

Any ideas?

解决方案

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;

and

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();

    }
}

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.

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

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

09-02 19:55