简体   繁体   中英

JPA hibernate executes multiple select query internally

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;
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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