开发者

The same objects in JPA

开发者 https://www.devze.com 2022-12-22 15:47 出处:网络
I have entity model like this (using EclipseLink and JPA 2.0): @Entity class A { @Id @GeneratedValue(strategy = GenerationType.AUTO)

I have entity model like this (using EclipseLink and JPA 2.0):

@Entity
    class A {
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      Long id;
      //equals, hashCode autogenerated by nb.

    }

And:

@Entity
        class B {
             @Id
              @GeneratedValue(strategy = GenerationType.AUTO)
开发者_如何转开发              Long id;

             @ManyToOne
             A a;
              //equals, hashCode autogenerated by nb.
        }

I query all objects of type A, and all objects of type B, which have not null reference on B.a field. All objects are managed. For instance, lets take Collection<A> aObjects, Collection<B> bObjects.

Consider that aObjects.get(0).equals(bObjects.get(0).a), and a != null. How can I ensure that aObjects.get(0) == bObjects.get(0).a ?

I have equal / identical objects, but I would rather prefer the same object.


JPA doesn't work that way. The entity instances that you get back from the JPA API are "hydrated" containers representing the persistent data. The java objects themselves are not special, they're just transient data holders.

From that perspective, object identity is not important, object equality is.

If your application requires object identity in this fashion, you're going to be fighting a losing battle, since JPA is just not designed to bend in that direction.

0

精彩评论

暂无评论...
验证码 换一张
取 消