简体   繁体   English

JPA @GeneratedValue和@Id

[英]JPA @GeneratedValue and @Id

In my Entity there's a field called id, marked with the annoation @Id (which I set manually) and know I wanted to know, is there a possibility to auto generate a Unique Id (with @GeneratedValue) but I also want to set the ID manually and when not set it should generate it auotmatically. 在我的实体中,有一个名为id的字段,标有注释@Id(我手动设置),并且知道我想知道,有可能自动生成唯一ID(使用@GeneratedValue),但我也想设置手动设置ID,如果未设置,则应自动生成。

Example: 例:

@Id
@GeneratedValue
private long id;

creation of the entity 实体的创建

new Entity(someid) //Once with ID and no generated value
new Entity() //Second without ID and generated unique value

I hope you can understand me. 希望你能理解我。

Well I don't think that this would work. 好吧,我认为这行不通。 JPA automatically generates your id value and is responsible for the @GeneratedValue . JPA自动生成您的id值,并负责@GeneratedValue Ask yourself 'what happens if there is already an existing entity with the id 100. And I create manually a new entity with tne id 100'. 问自己“如果已经存在一个ID为100的实体,会发生什么情况。我手动创建一个ID为100的新实体”。 Intuitively I would say that JPA (or the implementation) throws an expection. 直观地说,我会说JPA(或实现)引发了期望。

While writing the above answer I got the idea of writing your own generator (not tried at all, just coded down here at stackoverflow. 在编写上述答案时,我想到了编写自己的生成器的想法(根本没有尝试过,只是在stackoverflow此处进行了编码。

You can pass your own implementation of a generator to the @GeneratedValue annotation 您可以将自己的生成器实现传递给@GeneratedValue批注

@Id
@GeneratedValue(startegy = GenerationType.IDENTITY, generator="generatedIdOrCustomId")
@GenericGenerator(name="generatedIdOrCustomId", strategy="GeneratedIdOrCustomId")
private Long id;
...

And the custom implementation should look like this: 自定义实现应如下所示:

public class GeneratedIdOrCustomId extends IdentityGenerator {

@Override
public Serializable generate(SessionImplementor session, Object obj) throws HibernateException {
    if (((YourEntity) obj).getId() == null) {
        // the id is null, let JPA create an id.
        return super.generate(session, obj);
    } else {
        // the id is set and should not be generated by JPA.
        return ((YourEntity) obj).getId();
    }
}

The generate method is just a quick and dirty implementation. generate方法只是一种快速而肮脏的实现。 You'll have to check for example also if the obj == null and throw a (Hibernate)Exception in this case. 例如,在这种情况下,您还必须检查obj == null并抛出(Hibernate)Exception

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM