由于注释@ManyToOne
,我使用关联表在两个实体之间建立了一个简单的Hibernate @JoinTable
映射。
这是我的映射:
@Entity
public class Customer {
private Long id;
private Address address;
@Id
@GeneratedValue
public Long getId() {
return id;
}
@ManyToOne
@JoinTable(
name = "customer_address_association",
joinColumns = @JoinColumn(name = "customer_id"),
inverseJoinColumns = @JoinColumn(name = "address_id")
)
public Address getAddress() {
return address;
}
public void setId(Long id) {
this.id = id;
}
public void setAddress(Address address) {
this.address = address;
}
}
和
@Entity
public class Address {
private Long id;
private String street;
@Id
@GeneratedValue
public Long getId() {
return id;
}
public String getStreet() {
return street;
}
public void setId(Long id) {
this.id = id;
}
public void setStreet(String street) {
this.street = street;
}
}
当我查询“客户”实体时,总是会得到一个额外的左联接到联接表。例如,诸如SELECT c.id from Customer c
之类的HQL查询生成以下SQL查询:select customer0_.id as col_0_0_ from customer customer0_ left outer join customer_address_association customer0_1_ on customer0_.id=customer0_1_.customer_id
。
完整的源代码可以在这里找到:https://github.com/ndionisi/hibernate-extra-left-join
我用Hibernate 5.1、5.2和5.3复制它。有什么方法可以防止Hibernate生成对customer_address_association
表的左联接?它会影响大型表的性能。