Im have repository:
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findAllByPriceBetween(BigDecimal from, BigDecimal to, PageRequest pageRequest);
}
In liquibase im just create table:
--liquibase formatted sql
--changeset <sniklz>:<create-products-table>
CREATE TABLE IF NOT EXISTS products
(
id bigint auto_increment,
title varchar(255) not null,
price decimal not null,
CONSTRAINT product_pl PRIMARY KEY (id)
);
--rollback DROP TABLE products;
then im try to test my repository:
@DataJpaTest
@Testcontainers
@AutoConfigureTestDatabase (replace = AutoConfigureTestDatabase.Replace.NONE)
class ProductRepositoryTest {
@Container
static MySQLContainer<?> database = new MySQLContainer<>("mysql:8")
.withDatabaseName("springboot")
.withPassword("springboot")
.withUsername("springboot");
@DynamicPropertySource
static void setDataSourceProperties(DynamicPropertyRegistry propertyRegistry) {
propertyRegistry.add("spring.datasource.url", database::getJdbcUrl);
propertyRegistry.add("spring.datasource.username", database::getUsername);
propertyRegistry.add("spring.datasource.password", database::getPassword);
}
@Autowired
private ProductRepository productRepository;
@Test
@Sql("/scripts/init_four_products.sql")
void shouldReturnProductPriceGreaterThan1200() {
List<Sort.Order> order = new ArrayList<>();
order.add(new Sort.Order(Sort.Direction.DESC, "price"));
Sort sort = Sort.by(order);
PageRequest pageRequest = PageRequest.of(0, 10, sort);
List<Product> acutal = productRepository.findAllByPriceBetween(BigDecimal.valueOf(1200),
BigDecimal.valueOf(Integer.MAX_VALUE), pageRequest);
Assertions.assertEquals(1, acutal.size());
Assertions.assertEquals("iPhone XI", acutal.get(0).getTitle());
}
}
in /scripts/init_four_products.sql im just create som products:
INSERT INTO products (title, price) VALUES ("iPhone 8", 700);
INSERT INTO products (title, price) VALUES ("iPhone 9 ", 800);
INSERT INTO products (title, price) VALUES ("iPhone X", 1000);
INSERT INTO products (title, price) VALUES ("iPhone XI", 1200);
But have error:
org.springframework.dao.InvalidDataAccessApiUsageException: At least 3 parameter(s) provided but only 2 parameter(s) present in query.; nested exception is java.lang.IllegalArgumentException: At least 3 parameter(s) provided but only 2 parameter(s) present in query.
did not find any useful information at google
CodePudding user response:
According to Spring documentation:
The infrastructure recognizes certain specific types like
Pageable
andSort
, to apply pagination and sorting to your queries dynamically.
With that being said, you should replace PageRequest
with Pageable
in the ProductRepository
method:
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findAllByPriceBetween(BigDecimal from, BigDecimal to, Pageable pageable);
}
Pageable
should be instantiated as follows:
Pageable pageable = PageRequest.of(0, 10, sort);