仅在持久性为null时如何生成ID

加尔·索辛

我有两个使用两个不同数据库的组件,但是该实体在两个数据库中,并且我希望它始终具有相同的ID。

因此,基本上,当ID为null时,我希望它可以自动生成,如果不为null,则使用ID。

我正在使用休眠模式。

@Id
@Column(name = COLUMN_ID, unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
    return id;
}

有什么建议么?

克里斯蒂安·贝科夫(Christian Beikov)

为此,您需要一个自定义序列生成器:

public class SetableSequenceGenerator extends SequenceStyleGenerator {

    /**
     * Custom id generation. If id is set on the
     * com.curecomp.common.hibernate.api.Entity instance then use the set one,
     * if id is 'null' or '0' then generate one.
     */
    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object obj) {
        if ((obj != null) && (obj instanceof Entity)) {
            Entity<? extends Serializable> entity = (Entity<? extends Serializable>) obj;
            if ((entity.getId() == null) || (entity.getId().equals(0))) {
                return super.generate(session, obj);
            }
            return entity.getId();
        }
        return super.generate(session, obj);
    }
}

作为策略,您可以指定序列生成器类的FQN

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章