我已经定义了用户和位置之间的多对多关系,并且运行良好;当我必须使用组合键的一部分来执行数据检索时,所有问题都已经开始。
业务用户模型定义如下:
@Table(name = "BusinessUser")
public class User {
private String userId;
private String userAuthId;
private Set<UserLocation> userLocations;
@Id
public String getUserId () {
return userId;
}
public void setUserId ( String userId ) {
this.userId = userId;
}
public User () {
userLocations = new HashSet<>();
}
@JsonManagedReference
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<UserLocation> getUserLocations () {
return userLocations;
}
public void setUserLocations ( Set<UserLocation> userLocations ) {
this.userLocations = userLocations;
}
}
位置实体的定义如下:
public class Location {
private String locationId;
private String googlePlacesId;
private Set<UserLocation> userLocations;
@Id
public String getLocationId () {
return locationId;
}
public void setLocationId ( String locationId ) {
this.locationId = locationId;
}
public Location () {
userLocations = new HashSet<>();
}
@JsonManagedReference
@OneToMany(mappedBy = "location")
public Set<UserLocation> getUserLocations () {
return userLocations;
}
public void setUserLocations ( Set<UserLocation> userLocations ) {
this.userLocations = userLocations;
}
}
和UserLocation表如下:
@Entity
@Table(name="user_location")
@IdClass(UserLocation.UserLocationId.class)
public class UserLocation implements Serializable {
private User user;
private Location location;
private Date createdDate;
@Id
@ManyToOne
@JsonBackReference
@JoinColumn(name = "userId")
public User getUser () {
return user;
}
public void setUser ( User user ) {
this.user = user;
}
@Id
@ManyToOne
@JsonBackReference
@JoinColumn(name = "locationId")
public Location getLocation () {
return location;
}
public void setLocation ( Location location ) {
this.location = location;
}
public Date getCreatedDate () {
return createdDate;
}
public void setCreatedDate ( Date createdDate ) {
this.createdDate = createdDate;
}
这样做是为了确保用户和位置之间的映射一致。但是现在出现了问题。我有一个用户ID,在此基础上,我需要从UserLocation表中检索所有LocationId。获得所有位置ID后,便可以检索所有位置对象。
我的UserLocation JPAR存储库已创建如下:
@Repository
public interface UserLocationRepository extends JpaRepository<UserLocation,Long> {
List<UserLocation> findByUser ( User user);
}
这是定义这种关系的最佳方法。 如何只给定userID来检索Location的值 我可以看到一个IdClass错误,该错误已为其定义了ID类并添加了相同的类。 一旦这样做,我会看到一个持久ID错误。有线索吗?