0
votes

I am using JPA 2.1 and Hibernate for implementation.

Take a sample example :

I have a parent entity(call it Parent) and a child entity ( call it Child ).

UniqueKey Embeddable :

@Embeddable
@EqualsAndHashCode
@Data
@NoArgsConstructor
public class UniqueKey implements Serializable {

    public UniqueKey(String id1, String id2) {
        this.id1 = id1;
        this.id2 = id2;
    }

    @Column(name = "id1")
    private String id1;

    @Column(name = "id2")
    private String id2;
}

Parent Entity :

@Entity
@Table(name = "parent", uniqueConstraints = {
        @UniqueConstraint(columnNames = {
                "id1",
                "id2"
        })
})
public class Parent implements Serializable {
   @Id
   private UniqueKey key;

   @OneToOne(fetch = FetchType.LAZY)
    @JoinColumns({
            @JoinColumn(name = "id1", referencedColumnName = "id1", insertable = false,
                    updatable = false),
            @JoinColumn(name = "id2", referencedColumnName = "id2", insertable = false,
                    updatable = false)
    })
    private Child child;
}

Child Entity :

public class Child implements Serializable {
   @EmbeddedId
   private UniqueKey key;

   @Column(name = "name")
   private String name;
}

For some query on Parent I need child and for some case I don't need.

I am trying to fetching by uniqueKey but not calling getChild() but it is still fetch child data along with parent.

After referring this answer. It says in case of @OneToOne it always fetch data eagerly even if we define fetch = FetchType.LAZY .As this is very old answer so I don't know if it also happen with JPA 2.1 .

If it also happen in JPA 2.1 then what are other way for Fetch lazy using JPA criteriaBuilder ?

1

1 Answers

0
votes
  1. Lazy @OnetoOne relations to actually work
  2. If you need to select UniqueKey of from parent without fetching child — you may try following:

    class UniqueKeyDto { private String s1; private String s2; UniqueKeyDto(String s1, String s2){ // omitted } }

And then use JPQL query like this:

SELECT NEW UniqueKeyDto(p.child.key.s1, p.child.key.s2) FROM Parent p WHERE <conditions here>

This query can be obviously optimized, but I'm not sure which JPA implementations can do this in reality.

If your implementation doesn't support this kind of optimizations then your way — is native query. It's perfectly fine to make native queries sometimes :)