JpaRepository is creating a wrong query
I have the following query
package gt.com.anibal.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import gt.com.anibal.model.Order;
@Repository
public interface OrderDao extends JpaRepository<Order, Long>{
//@Query("SELECT o FROM Order o")
@Query(value = "SELECT * FROM Order o WHERE o.price = ?1", nativeQuery = true) //native query
public List<Order> findOrder(double price);
}
And this is the error
SELECT
*
FROM
Order o WHERE
o.price = ?
10:13 TRACE 13460 --- [nio-9091-exec-2] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [DOUBLE] - [25.0]
10:13 WARN 13460 --- [nio-9091-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1064, SQLState: 42000
10:13 ERROR 13460 --- [nio-9091-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Order o WHERE o.price = 25.0' at line 1
10:13 ERROR 13460 --- [nio-9091-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Order o WHERE o.price = 25.0' at line 1
If I run the query on MySQL, it works fine
SELECT
*
FROM
test.Order o WHERE
o.price = 25.0
but I think the JpaRepository it's creating a space blank between the from and where, when I use JpaRepository in another Entity, the query it's different in my console
package gt.com.anibal.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import gt.com.anibal.model.Persona;
@Repository
public interface PersonaDao extends JpaRepository<Persona, Long> {
}
Here is the result, I don't see the space blank between from and the next line, I don't know if that is the problem or it is another problem.
select
persona0_.id_persona as id_perso1_3_,
persona0_.apellido as apellido2_3_,
persona0_.email as email3_3_,
persona0_.nombre as nombre4_3_,
persona0_.telefono as telefono5_3_
from
persona persona0_
This is my Entity
package gt.com.anibal.model;
import java.sql.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table( name = "order" )
public class Order {
@Id
@Column(name = "idorder", columnDefinition = "int")
private Long idOrder;
@Column( name = "description")
private String descriptions;
@OneToMany(mappedBy = "order")
private Set<Customer> customer = new HashSet<>();
@Column( name = "date")
private Date date;
@Column( name = "price", precision = 10, scale = 2)
private double price;
public Long getIdOrder() {
return idOrder;
}
public void setIdOrder(Long idOrder) {
this.idOrder = idOrder;
}
public String getDescriptions() {
return descriptions;
}
public void setDescriptions(String descriptions) {
this.descriptions = descriptions;
}
public Set<Customer> getCustomer() {
return customer;
}
public void setCustomer(Set<Customer> customer) {
this.customer = customer;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
and this is my table on MySQL
CREATE TABLE `order` (
`idOrder` int NOT NULL,
`description` varchar(45) NOT NULL,
`idCustomer` varchar(45) NOT NULL,
`date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`price` decimal(10,2) NOT NULL DEFAULT '0.00',
PRIMARY KEY (`idOrder`),
KEY `fk_order_customer_idx` (`idOrder`),
CONSTRAINT `fk_order_customer` FOREIGN KEY (`idOrder`) REFERENCES `customer` (`idCustomer`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
I suggest to use JPA Query Methods for this kind of simple queries.
Your method should be named as follows:
@Repository
public interface OrderDao extends JpaRepository<Order, Long>{
List<Order> findByPrice(double price);
}
This is a more clean code.
If you want to use native queries for further cases, you should replace your "?1" for the name of your method variable name prefixed by a semicolon like this ":price".
what @rortegat suggested is a good way to write simple queries[at least to me]. Now, in your query:
@Query(value = "SELECT * FROM Order o WHERE o.price = ?1", nativeQuery = true)
Here *
means rows/records of all columns but your method is returning List<Order>
which is not compatible.
Instead, change your query like this:
@Query(value = "SELECT o FROM Order o WHERE o.price = ?1", nativeQuery = true
)
Here, SELECT o FROM Order o
this part means you are returning Order instance from your query by your alias o
.