2

Problem Statement:in JPA hibernate I execute a method

Contact contact = entityManager.find(Contact.class, Integer.valueOf(contactId));

As expected EntityManager fires a select query to get an object of contact, but after that it fires another select query to get customer object which I do not want.
Customer object is an child object in contact object.
contact entiry has an foreign key customerId.

Requirment: I want entityManager to fire one select query get the contact object and do nothing after that no second select query neither a join query. contact object:

@Entity
@Table(name = "contact")
public class Contact {
    @JsonProperty("contactId")
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "Id")
    int contactId;

    @Column(name = "firstname")
    @JsonProperty("firstName")
    String firstName;

    @Column(name = "lastname")
    @JsonProperty("lastName")
    String lastName;

    @Column(name = "phone1")
    @JsonProperty("phone1")
    String phone1;

    @ManyToOne(optional = false, fetch = FetchType.LAZY, targetEntity = Customer.class)
    @JoinColumn(name = "customer_id", updatable = false)
    @Fetch(FetchMode.JOIN)
    Customer customer;

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
}
vinS
  • 1,417
  • 5
  • 24
  • 37
  • 1
    No, it doesn't execute that query when executing find(). It most probably execute that query when you serialize the Contact to JSON: you didn't tell Jackson to avoid serializing the contct's customer, so Jackson serializes it, so Hibernate needs to execute a qery to load the state of the customer. – JB Nizet Dec 10 '17 at 08:29
  • can you please add the code that used to find Contact – Ahmad Al-Kurdi Dec 10 '17 at 10:14

1 Answers1

3

I think your issue comes from using @Fetch(FetchMode.join) together with Lazy Loading. If you don't want to load the Customer eagerly then you should remove the @Fetch(FetchMode.join) and only use lazy loading

See more infos regarding this here (https://stackoverflow.com/a/29667050/2637940):

First of all, @Fetch(FetchMode.JOIN) and @ManyToOne(fetch = FetchType.LAZY) are antagonistic, one instructing an EAGER fetching, while the other suggesting a LAZY fetch.