在jpa中保存对象之前,我如何知道id [英] How do I know th id before saving an object in jpa

查看:908
本文介绍了在jpa中保存对象之前,我如何知道id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个新对象。我想在保存之前知道id。可能吗?或者还有另一种方式吗?我使用jpa作为orm和oracle作为数据库。

I have a new object. I want to know id before saving it. Is it possible? Or there is another way for this? I am using jpa as orm and oracle as database.

@Id
@Basic(optional = false)
@Column(name = "ID", nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "woTypeSeq")
private Long id;

我的实体中有一个代码字段。如果用户没有为代码字段输入值,我想将代码设置为实体的id。如果我持久化实体,当然我可以获取id并将代码值设置为id,但这是额外的查询数据库。

I have a code field in my entity. If the user doesn't enter a value for the code field, I want to set code as entity's id. If I persist entity, of course i can get id and set code value as id, but this is extra query database.

我想做类似的事情

if(entity.getCode()==null) {
   entity.setCode(entity.getId);
   jpaDao.saveOrUpdate(entity);
}


推荐答案

经过长时间的研究,最后我找到了解决方案。

After long researching about this, finally I found a solution.

事实上,如果你在jpa中使用 序列生成器 ,你肯定无法在保存之前获取实体的id数据库,因为下一个id将由数据库序列分配。

In fact, if you use sequence generator in jpa, certainly you cannot obtain entity's id before saving it in database, because next id will be assigned by database sequence.

如果您使用 自定义生成器 ,有一种方法可以获取ID,您可以在之前获取ID保存。这是一个简单的实现:

There is one way to obtain the id if you use a custom generator, you can get the id before saving. Here is simple implementation:

public class CustomGenerator extends IdentityGenerator implements Configurable {

    private IdentifierGenerator defaultGenerator;

    public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
        Long idValue = (Long)defaultGenerator.generate(session, object);
        //idValue will be assigned your entity id
        return idValue;
    }

    @Override
    public void configure(Type type, Properties params, Dialect d) throws MappingException {
        DefaultIdentifierGeneratorFactory dd = new DefaultIdentifierGeneratorFactory();
        dd.setDialect(d);
        defaultGenerator = dd.createIdentifierGenerator("sequence", type, params);
    }
}

使用CustomGenerator作为id字段:

Using CustomGenerator for id field:

@Id
@Basic(optional = false)
@Column(name = "ID", nullable = false)
@GenericGenerator(name = "seq_id", strategy = "com.yoncabt.abys.core.listener.CustomGenerator", parameters = { @Parameter(name = "sequence", value = "II_FIRM_DOC_PRM_SEQ") })
@GeneratedValue(generator = "seq_id")
private Long id;

这篇关于在jpa中保存对象之前,我如何知道id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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