I want to use sql select by method name in spring-data.
The select should be ordered by price.
@Entity
public class Product {
int name;
BigDecimal price;
}
interface ProductRepository extends CrudRepository<Product, Long> {
Product findFirstByNameOrderByPriceAsc(String name);
}
Result:
org.springframework.dao.IncorrectResultSizeDataAccessException: result returns more than one elements; nested exception is javax.persistence.NonUniqueResultException: result returns more than one elements
Why? I exactly used the findFirst()
method for this reason to just get the top result if more than one is found..
Let's start with the JpaRepository – which extends PagingAndSortingRepository and, in turn, the CrudRepository. Each of these defines its own functionality: CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records.
The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm.xml file. It's a good approach to place a query definition just above the method inside the repository rather than inside our domain model as named queries.
Spring Data JPA is an add-onIt provides a framework that works with JPA and provides a complete abstraction over the Data Access Layer. Spring Data JPA brings in the concept of JPA Repositories, a set of Interfaces that defines query methods. The Repository and Entity Bean represent the DAO layer in the application.
The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database. The @Table annotation provides four attributes, allowing you to override the name of the table, its catalog, and its schema, and enforce unique constraints on columns in the table.
Top
and First
keywords are available since spring-data-jpa-1.7.1.RELEASE
. See Spring Data JPA Changelog and Limiting query results
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