Spring Data- how to tell spring what entities to retrieve

杀马特。学长 韩版系。学妹 提交于 2020-01-30 11:22:08

问题


If i have several entites, lets say :

@Entity
class Book{
String name;
Author author; 
}

@Entity
class Author{
String name;
City hometown;
}

@Entity
class City{
String cityName;
}

If i want to retrieve all the books, if i use classic JPA Repository and Spring Data and just do a findAll(), it will get me all the books with all the Authors with all their home towns. I know i can use @JsonIgnore, but i think that only prevents whats being returned, not whats being looked up in the database. And also i have methods that DO want to return both books and authors, so @JsonIgnore -ing does not work for me. Is there anything like this ? To tell Spring Data what to look up and what to return ? Any links or guides or methods i don't know of, would be appreciated.


回答1:


Spring Data has the concept of 'projections' which allow you to return different representations of the same Entity.

Official Documentation:

Spring Data query methods usually return one or multiple instances of the aggregate root managed by the repository. However, it might sometimes be desirable to create projections based on certain attributes of those types. Spring Data allows modeling dedicated return types, to more selectively retrieve partial views of the managed aggregates.

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

Where a Projection is a 'closed' projection (a projection interface whose accessor methods all match properties of the target aggregate) then the documentation notes that additionally:

Spring Data can optimize the query execution [to select only the relevant fields], because we know about all the attributes that are needed to back the projection proxy

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections.interfaces.closed

Spring Data also allows for Projections to be specified dynamically at runtime. See further:

https://github.com/spring-projects/spring-data-commons/blob/master/src/main/asciidoc/repository-projections.adoc#dynamic-projections




回答2:


  • First mark your relations as LAZY
  • Then specify what data needs to be fetched on a per-query basis.

See for example: https://vladmihalcea.com/eager-fetching-is-a-code-smell/



来源:https://stackoverflow.com/questions/56130098/spring-data-how-to-tell-spring-what-entities-to-retrieve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!