我指定了与HQL的联接,以通过链接表addresses
从users
表中获取与users_addresses
相关的单个字段。这是有效的,但我的问题是Hibernate还加入了另一个链接表users_phoneNumbers
。
public Country getUserCountry(Integer userId) {
return (Country) entityManager.createQuery("SELECT a.country FROM User u JOIN u.address a WHERE u.id = :userId")
.setParameter("userId", userId).getSingleResult();
}
它执行的查询:
Hibernate:
/* SELECT
a.country
FROM
User u
JOIN
u.address a
WHERE
u.id = :userId */ select
address1_.country as col_0_0_
from
users user0_
left outer join
users_phoneNumbers user0_1_
on user0_.id=user0_1_.userId_fk
left outer join
users_addresses user0_2_
on user0_.id=user0_2_.userId_fk
inner join
addresses address1_
on user0_2_.addressId=address1_.id
where
user0_.id=?
我的用户对象有一些与其他表有关系的其他字段,但只是额外加入电话号码。
@Entity
@Table(name = "users")
@Getter
@Setter
@ToString
public class User implements Serializable {
private static final long serialVersionUID = 47483884837236327284854L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotNull
private String name;
@NotNull
private LocalDate birthDate;
private Boolean notifications = TRUE;
@OneToMany(fetch = EAGER, cascade = {ALL}, orphanRemoval = true)
@JoinColumn(name = "userId", referencedColumnName = "id", nullable = false)
private final Set<UserSkill> skills = new HashSet<>();
@Getter(AccessLevel.NONE)
@OneToOne(fetch = EAGER, cascade = ALL)
@JoinTable(name = "users_phoneNumbers", joinColumns = @JoinColumn(name = "userId"), inverseJoinColumns = @JoinColumn(name = "phoneNumberId"))
private PhoneNumber phoneNumber;
@OneToOne(fetch = EAGER, cascade = ALL)
@JoinTable(name = "users_addresses", joinColumns = @JoinColumn(name = "userId"), inverseJoinColumns = @JoinColumn(name = "addressId"))
private Address address;
@ElementCollection(fetch = EAGER)
@Enumerated(EnumType.STRING)
@CollectionTable(name = "users_userInterests", joinColumns = @JoinColumn(name = "userId"))
@Column(name = "userInterest")
private final Set<UserInterest> userInterests = new HashSet<>();
private String profilePhoto;
private LocalDateTime created;
private User() {
}
public User(String name, LocalDate birthDate, Set<UserSkill> skills) {
this.name = name;
this.birthDate = birthDate;
this.skills.addAll(skills);
}
public void addSkills(Collection<UserSkill> skills) {
this.skills.addAll(skills);
}
public void removeSkills(Collection<UserSkill> skills) {
this.skills.removeAll(skills);
}
public String getPhoneNumber() {
if (phoneNumber != null) {
return phoneNumber.getPhoneNumber();
} else {
return null;
}
}
public Boolean isPhoneNumberVerified() {
if (phoneNumber != null) {
return phoneNumber.getIsVerified();
} else {
return false;
}
}
我怀疑它可能与phoneNumber相关的吸气剂有关,但这只是一个想法。
为什么会这样?我怎么能避免它?