我正在使用Spring数据处理Spring项目。我有以下型号:
Location.java
@Entity
@Table(name = "location")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Location {
@Id
@GeneratedValue
private int id;
private String latitude;
private String longitude;
private String date;
@ManyToOne
@JoinColumn(name ="user")
@JsonBackReference
private User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
...
...
}
User.java
@Entity
@Table(name = "users")
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
@Id
@GeneratedValue
private int uid;
private String first_name;
private String last_name;
private String email;
private String password;
private boolean enabled;
private String avatar;
@Enumerated(EnumType.STRING)
@Column(name = "user_role")
private Role role;
@OneToMany(mappedBy="user")
@JsonManagedReference
private List<Location> locations;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
}
数据库
CREATE TABLE location (
id integer NOT NULL,
"user" integer,
...
CONSTRAINT location_pkey PRIMARY KEY (id),
CONSTRAINT location_user_fkey FOREIGN KEY ("user")
REFERENCES users (uid) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
CREATE TABLE users
(
uid integer NOT NULL,
...
CONSTRAINT users_pkey PRIMARY KEY (uid)
)
目标使用CrudRepository,我想获取所有位置的列表WITH WITH WITH WITHOUT corresponsing users!
public interface LocationRepository extends CrudRepository<Location, Integer> {
List<Location> findAll();
@Query("SELECT l FROM Location l")
List<Location> findLast();
}
据我所知,上面的查询将获得没有相应用户的所有位置,但以下
@Query("SELECT l FROM Location l JOIN l.user u")
将获得具有相应用户的所有位置
问题:两个查询都会获得具有相应用户的所有地点!
我在这里做错了什么?感谢
答案 0 :(得分:2)
问题在于您将Location
映射到始终检索User
(反之亦然)。如果您不想要此行为,可以使用FetchType.LAZY
标记以懒惰方式获取User
:
@ManyToOne(fetch=FetchType.LAZY, optional=false)
@JoinColumn(name ="user")
@JsonBackReference
private User user;
这样,User user
中的Location
只会在通过getter访问时检索,如果它在有效会话中。