![](/img/trans.png)
[英]How to implement Generic JPA Repository in Spring Boot - Which can be autowired into spring services for any entity/class type
[英]How to implement ligh Entity version with Jpa repository?
有一個“完整的實體”類:
@Entity(name = "vacancy_dec_to_words")
public class VacancyDescriptionToWords {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@JoinColumn(name = "vacancy_description_id")
@ManyToOne(cascade = CascadeType.ALL)
private VacancyDescription vacancyDescription;
@JoinColumn(name = "words_id")
@ManyToOne
private Words words;
@Column(name = "qty")
private int qty;
@Column(name = "create_date")
private Date date;
//...getters and setters
在某些方法中,我只需要使用此數據庫中的2列: word_id
和qty
我嘗試以下方式:
預測 https://docs.spring.io/spring-data/jpa/docs/2.1.2.RELEASE/reference/html/#projections
public interface QtyWords {
Long getWords();
Integer getQty();
}
JpaReposytory:
*查詢,我使用測試並且可行,我在JpaRepository
使用他:
@Repository
public interface SmallVDTWRepository extends JpaRepository<VacancyDescriptionToWords, Long> {
@Query(nativeQuery = true,
value = "SELECT sum(qty), words_id FROM vacancy_desc_to_words WHERE vacancy_description_id IN (" +
"SELECT id FROM vacancy_description WHERE vacancy_id IN (" +
"SELECT id FROM vacancy WHERE explorer_id = :exp))" +
"GROUP BY words_id")
List<QtyWords> getDistinctWordsByExplorer(@Param("exp") long exp);
}
但是當我獲得實體列表時,我得到了一些有趣的結果:
List<QtyWords> list = vdtwService.getByExplorerId(72);
我沒有得到任何例外,但我列出的是未知對象。 這個對象包含我需要的數據( qty
和words_id
),但我不能從他那里得到它們。
我可以使用此方法( Projection
)來實現此任務嗎?一般來說,如何在這種情況下正確實現'Light Entity'?
Spring提供了兩種機制,可用於限制要獲取的數據。
通過設置要獲取的確切屬性,預測可以幫助您減少從數據庫中檢索的數據。
@Entity
class Person {
@Id UUID id;
String firstname, lastname;
@OneToOne
Address address;
}
@Entity
static class Address {
@Id UUID id;
String zipCode, city, street;
}
interface NamesOnly {
String getFirstname();
String getLastname();
}
@Repository
interface PersonRepository extends Repository<Person, UUID> {
Collection<NamesOnly> findByLastname(String lastname);
}
注釋EntityGraph
可以通過設置需要獲取的確切相關實體來幫助您減少對數據庫的查詢量。
@Entity
@NamedEntityGraph(name = "GroupInfo.detail", attributeNodes = @NamedAttributeNode("members"))
public class GroupInfo {
@Id UUID id;
@ManyToMany //default fetch mode is lazy.
List<GroupMember> members = new ArrayList<GroupMember>();
}
@Repository
public interface GroupRepository extends CrudRepository<GroupInfo, String> {
@EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD)
GroupInfo getByGroupName(String name); //Despite of GroupInfo.members has FetchType = LAZY, it will be fetched because of using EntityGraph
}
EntityGraph
有兩種類型:
EntityGraphType.LOAD
- 用於指定實體圖,由實體圖的屬性節點指定的屬性被視為FetchType.EAGER
,未指定的屬性將根據其指定的或默認的FetchType
。 EntityGraphType.FETCH
- 用於指定實體圖,由實體圖的屬性節點指定的屬性被視為FetchType.EAGER
,未指定的屬性被視為FetchType.LAZY
。 PS:還記得您可以設置延遲提取類型: @ManyToOne(fetch = FetchType.LAZY)
,JPA將在獲取父提取時不提取子實體。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.