Reputation: 31
How do you write custom queries in Spring Data JPA? Is there more convenient method than the following? I did before like this:
public class TestCustomRepositoryImpl implements TestCustomRepository {
@PersistenceContext
private EntityManager entityManager;
@Override
public Double getValue(Long param) {
// Simple SQL query for example.
String queryString = "SELECT column_name1 FROM table_name1 "
+ "WHERE column_name2 = " + param;
Query query = entityManager.createNativeQuery(queryString);
List resultList = query.getResultList();
if (!resultList.isEmpty()) {
Number value = (Number) resultList.get(0);
if (value != null) {
return value.doubleValue();
}
}
return 0.0;
}
}
Then I added custom interface to my JPA repository:
public interface TestRepository extends JpaRepository<TestEntity, Long>, TestCustomRepository {
}
Is there more convenient way? Can I use Spring Data for CRUD and implement TestCustomRepository with MyBatis, for example? How do you implement your custom methods?
Upvotes: 3
Views: 10657
Reputation: 3166
in TestRepository
you can use DTO using SELECT NEW
and pass DTO object:
@Query("SELECT NEW com.app.domain.EntityDTO(table.id, table.col2, table.col3)
FROM Table table")
public List<EntityDTO> findAll();
In the example your DTO must have a constructor with these 3 parameters.
If you want to select properties you can simply use:
@Query("SELECT table.id)
FROM Table table")
public List<Long> findAllIds();
Upvotes: 1
Reputation: 56
You can write the native query in the repository like this:
1)
@Query("SELECT t.column_name1 FROM table_name1 t WHERE t.column_name2 =:param")
List<String> getValue(@Param("param") String param);
OR
2)@Query("SELECT t.column_name1 FROM table_name1 t WHERE t.column_name2 = 'param'", nativeQuery=true)
List<String> getValue();
Or you can use NamedQuery and add the query in the model only.
for eg:
@Entity
@Table(name = "table_name1", schema="db_name")
@NamedQuery(name = "ENTITY.fetchParam",
query = "SELECT t.column_name1 FROM table_name1 t WHERE t.column_name2 =:param "
)
public class Employee {
}
And have same method in the repository like:
@Repository
public interface TestRepository extends JpaRepository<Employee,Long>, TestRepositoryCustom {
List<String> fetchParam(@Param("param") String param);
}
Upvotes: 4