我一直在學習春天引導框架近日,據我的研究,我可以帶有ORM,EntityManager,@Query的Spring Data Repository,處理自定義SQL查詢的最優雅的方法是什麼?
- 包括在Maven的依賴列表Hibernate的JPA實現,擴展
CrudRepository
並添加自定義方法
或
- 使用
EntityManager
從Hibernate來執行自定義的SQL查詢
或
- 使用註釋
@org.springframework.data.jpa.repository.Query
問題
他們是否緩存我查詢的數據?
它們是否具有相同的性能?
哪一個是最適合自定義SQL查詢的方法?如果它們都不是,那麼在使用Spring框架(不限於存儲庫模式)和Hibernate時,是否有其他方式來處理自定義SQL查詢?
1.存儲庫的方法
@Entity
@Table(name = Collection.TABLE_NAME)
public class Collection {
public final static String TABLE_NAME = "collection";
...
}
public interface CollectionRepository extends CrudRepository<Collection, Integer> {
}
public class CollectionRepositoryImpl {
@Autowired
private CollectionRepository collectionRepository;
public List<Collection> findCollectionsForSeason(int season, int count) {
List<Collection> results = new ArrayList<>();
for (Collection c : collectionRepository.findAll()) {
if (c.getSeason() == season) {
results.add(c);
}
}
return results;
}
}
2. EntityManager的方法
public class xxx {
private EntityManager em;
...
public List<Collection> findCollectionsForSeason(int season, int count) {
String sqlString = String.format("SELECT * FROM `collection` WHERE `season`=%d LIMIT %d", season, count);
return this.em.createNativeQuery(sqlString).getResultList();
}
}
3. @Query
方法
注意:下面的這段代碼是錯誤的,但我無法弄清楚如何正確地做到這一點。所以如果有人可以幫助我使用命名參數和限制子句(mysql)實現本機查詢,那將會很好。
public interface CollectionRepository extends CrudRepository<Collection, Integer> {
@Query(value = "SELECT * FROM `collection` WHERE `season`=%d LIMIT %d", nativeQuery = true)
List<Collection> findCollectionsForSeason(int season, int count) {
}
}
謝謝!