gpt4 book ai didi

java - Spring Data,获取行ManyToOne/OneToMany关系?

转载 作者:行者123 更新时间:2023-12-02 05:54:19 24 4
gpt4 key购买 nike

我正在使用 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,我想获取包含或不包含相应用户的所有位置的列表!

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")

将获取相应用户的所有位置

问题:两个查询都获取具有相应用户的所有位置!

我在这里做错了什么?谢谢

最佳答案

问题在于您将 Location 映射为始终检索 User(反之亦然)。如果您不希望出现此行为,可以使用 FetchType.LAZY 标记以惰性方式获取 User :

@ManyToOne(fetch=FetchType.LAZY, optional=false)
@JoinColumn(name ="user")
@JsonBackReference
private User user;

这样,只有在通过 getter 访问并且位于有效 session 内时,才会检索 Location 中的 User user

关于java - Spring Data,获取行ManyToOne/OneToMany关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23246286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com