我有两个实体:地址和客户。它们之间存在一对一的双向关系。
@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;
...
}
然后,我执行以下代码来选择根据Id查找客户。
entityManager.find(Customer.class, 1L);
我发现会生成两个查询语句,这很令人困惑。我认为只需要第一个查询就足以获取客户和地址实体。
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=?
有人遇到这个问题吗?如果代码有误,请指出来。
@JoinColumn(name = "foreign_key_in_customer")
吗?还有,为什么要使用new Address();
? - Naman Gala