I have a relationship between the three model objects in my project (fragments of the model and the repository at the end of the post.
When I call PlaceRepository.findById , it launches three queries:
("SQL")
SELECT * FROM place p where id = argSELECT * FROM user u where u.id = place.user.idSELECT * FROM city c LEFT OUTER JOIN state s on c.woj_id = s.id where c.id = place.city.id
This is a rather unusual behavior (for me). As far as I can tell from reading the Hibernate documentation, it should always use JOIN requests. There is no difference in queries when FetchType.LAZY changed to FetchType.EAGER in the Place class (query with optional SELECT), the same for the City class when FetchType.LAZY changed to FetchType.EAGER (query with JOIN).
When I use CityRepository.findById fire suppression, two choose:
SELECT * FROM city c where id = argSELECT * FROM state s where id = city.state.id
My goal is to have sam behavior in all situations (either always JOIN, or SELECT, JOIN is preferable).
Model Definitions:
A place:
@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;
City:
@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;
Storage:
PlaceRepository
public interface PlaceRepository extends JpaRepository<Place, Long>, PlaceRepositoryCustom { Place findById(int id); }
UserRepository:
public interface UserRepository extends JpaRepository<User, Long> { List<User> findAll(); User findById(int id); }
CityRepository:
public interface CityRepository extends JpaRepository<City, Long>, CityRepositoryCustom { City findById(int id); }
java spring spring-data-jpa hibernate jpa
SirKometa Apr 13 '15 at 9:48 2015-04-13 09:48
source share