始终对JPA @Id使用原始对象包装而不是原始类型? [英] Always use primitive object wrappers for JPA @Id instead of primitive type?

查看:832
本文介绍了始终对JPA @Id使用原始对象包装而不是原始类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现与Spring Data JPA一起使用原始类型作为JPA的对象@Id的问题. 我在父级与Cascade.ALL有父/子关系,而子级有PK,而PK也是父级的FK.

I've found the issue with using primitive type as an object @Id for JPA in conjunction with Spring Data JPA. I have parent/child relationship with Cascade.ALL on the parent side, and child has PK which at the same time is also parent's FK.

class Parent {
    @Id
    private long id;

    @OneToOne(mappedBy = "parent", cascade = ALL)
    private Child child;
}

class Child {
    @Id
    @OneToOne
    private Parent parent;
}

所以,当我跑步时:

...
Parent parent = new Parent();
Child child  = new Child(parent);
parent.setChild(child);  
em.persist(parent)
...

一切正常.但是我使用Spring Data JPA来持久化实体,所以我改为运行:

everything works fine. But I used Spring Data JPA to persist the entity, so I run instead:

parentRepository.save(parent); // instead of em.persist(parent);

并且此失败,但有以下异常:

and this one was failed with the following exception:

Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: Parent

问题是Spring Data JPA save()方法检查实体是否为新实体,如果是新实体,则使用 em.persist(),否则 em.merge().

The problem was that Spring Data JPA save() method checks whether the entity is new, and if it is new then em.persist() is used otherwise em.merge() is used.

这里有趣的部分是Spring如何检查实体是否为新实体:

The interesting part here how Spring checks whether the entity is new or not:

getId(entity) == null;

当然,这是错误的,因为我将long用作@Id的类型,并且long的默认值是0.当我将long更改为Long时,Spring Data JPA也可以使用.

And, of course, this was false, because I used long as the type for @Id, and the default value for long is 0. When I changed long to Long everything works with Spring Data JPA also.

因此,建议的做法是始终对原始类型(例如Long而不是long)使用对象包装而不是原始类型.任何将其描述为推荐做法的第三方资源都很好.

So is it the recommended practice always to use object wrappers for the primitive types (like Long instead of long) instead of primitive types. Any 3rd party resource describing this as the recommended practice would be very nice.

推荐答案

我会说是的,由于您遇到的情况,建议使用对象类型而不是基元.无法通过实体标识符来区分该实体是新实体还是现有实体.我已经使用了hibernate多年了,而且我总是使用对象作为标识符.

I would say yes it is recommended to use object types instead of primitives because of the case you are seeing. There is no way of distinguishing if the entity is new or pre existing with a primitive identifier. I have used hibernate for years and I always use objects for identifiers.

这篇关于始终对JPA @Id使用原始对象包装而不是原始类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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