FetchMode在Spring Data JPA中是如何工作的
2022-08-31 09:41:57
在我的项目中,我确实有三个模型对象(帖子末尾的模型和存储库片段)之间的关系。
当我调用它时,它确实触发了三个选择查询:PlaceRepository.findById
(“sql”)
SELECT * FROM place p where id = arg
SELECT * FROM user u where u.id = place.user.id
SELECT * FROM city c LEFT OUTER JOIN state s on c.woj_id = s.id where c.id = place.city.id
这是相当不寻常的行为(对我来说)。据我所知,在阅读Hibernate文档后,它应该始终使用JOIN查询。在类中更改为 (使用附加 SELECT 的查询)时,查询没有区别,更改为 (使用 JOIN 进行查询)时,类的查询相同。FetchType.LAZY
FetchType.EAGER
Place
City
FetchType.LAZY
FetchType.EAGER
当我使用灭火时,有两个选择:CityRepository.findById
SELECT * FROM city c where id = arg
SELECT * FROM state s where id = city.state.id
我的目标是在所有情况下都有一个 sam 行为(要么总是 JOIN,要么 SELECT,但 JOIN 是首选)。
模型定义:
地方:
@Entity
@Table(name = "place")
public class Place extends Identified {
@Fetch(FetchMode.JOIN)
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_user_author")
private User author;
@Fetch(FetchMode.JOIN)
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "area_city_id")
private City city;
//getters and setters
}
城市:
@Entity
@Table(name = "area_city")
public class City extends Identified {
@Fetch(FetchMode.JOIN)
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "area_woj_id")
private State state;
//getters and setters
}
存储 库:
PlaceRepository
public interface PlaceRepository extends JpaRepository<Place, Long>, PlaceRepositoryCustom {
Place findById(int id);
}
用户存储库:
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findAll();
User findById(int id);
}
城市存储库:
public interface CityRepository extends JpaRepository<City, Long>, CityRepositoryCustom {
City findById(int id);
}