I've been learning Spring Boot framework recently, according to my research, I can either
- Include Hibernate JPA implementation in maven dependency list, extends
CrudRepository
and add custom methods
or
- Use
EntityManager
from Hibernate to execute custom SQL query
or
- Use annotation
@org.springframework.data.jpa.repository.Query
Questions
Do they cache data I queried?
Do they have the same performance?
Which one is the most elegant way to go with custom SQL queries? If none of them is, is there any other way to deal with custom SQL queries when using Spring framework (not limited to Repository pattern) and Hibernate?
1. Repository approach
@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 approach
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
approach
NOTE: this code snippet below is wrong, but I can't figure out how to do it correctly. So it would be nice if someone can help me to implement native query with named parameters and limit clause (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) {
}
}
Thanks!