I can use the findAll() method to select * from my_table to get all columns and rows.
Spring Data JPA supports find, read, query, count and get.
JPA handles most of the complexity of JDBC-based database access and object-relational mappings. On top of that, Spring Data JPA reduces the amount of boilerplate code required by JPA. That makes the implementation of your persistence layer easier and faster.
Crud Repository doesn't provide methods for implementing pagination and sorting. JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.
As of Spring Data 1.7.1.RELEASE you can do it with two different ways,
public interface UserRepository extends CrudRepository<User, Integer> {
long countByName(String name);
}
@Query
annotation. public interface UserRepository extends CrudRepository<User, Integer> {
@Query("SELECT COUNT(u) FROM User u WHERE u.name=?1")
long aMethodNameOrSomething(String name);
}
or using @Param
annotation also,
public interface UserRepository extends CrudRepository<User, Integer> {
@Query("SELECT COUNT(u) FROM User u WHERE u.name=:name")
long aMethodNameOrSomething(@Param("name") String name);
}
Check also this so answer.
As long as you do not use 1.4 version, you can use explicit annotation:
example:
@Query("select count(e) from Product e where e.area.code = ?1")
long countByAreaCode(String code);
JpaRepository also extends QueryByExampleExecutor. So you don't even need to define custom methods on your interface:
public interface UserRepository extends JpaRepository<User, Long> {
// no need of custom method
}
And then query like:
User probe = new User();
u.setName = "John";
long count = repo.count(Example.of(probe));
Working example
@Repository
public interface TenantRepository extends JpaRepository< Tenant, Long > {
List<Tenant>findByTenantName(String tenantName,Pageable pageRequest);
long countByTenantName(String tenantName);
}
Calling from DAO layer
@Override
public long countByTenantName(String tenantName) {
return repository.countByTenantName(tenantName);
}
This feature has been added in version 1.4 M1
Apparently it is implemented now DATAJPA-231
According to Abel, after the version 1.4 (tested in version 1.4.3.RELEASE) is possible doing this way:
public long countByName(String name);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With