Jiaguo Fang
Jiaguo Fang

Reputation: 333

Hibernate @OneToOne bidirectional causes redundant select query

I have two entities: Address and Customer. They have ont-to-one relationship and bidirectional.

@Entity
public class Address {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToOne(mappedBy = "address", cascade = CascadeType.ALL)
    private Customer customer;

    ...
}

@Entity
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToOne(cascade = CascadeType.ALL)
    private Address address;

    ...
}

Then I execute the following code to select Customer by Id.

entityManager.find(Customer.class, 1L);

I find two queries will be generated. It's so confusing. I think only the first query is enough to get both Customer and Address entities.

select * from Customer customer0_ left outer join Address address1_ on customer0_.address_id=address1_.id where customer0_.id=?
select * from Customer customer0_ left outer join Address address1_ on customer0_.address_id=address1_.id where customer0_.address_id=?

Does anyone meet this problem? Can you point me out if there is some mistake in the code?

Upvotes: 4

Views: 609

Answers (1)

Tobias Liefke
Tobias Liefke

Reputation: 9022

You need to define at least one of your OneToOne as fetch = FetchType.LAZY. The default is FetchType.EAGER - thats why he tries to load Address.customer in the second statement.

And I wouldn't use cascade = CascadeType.ALL for both directions - that can lead to problems as well. Usually only the owning side of the link will use CascadeType.ALL.

Upvotes: 1

Related Questions