I am trying to use JPA and JPQL to query my entity and return the sum of a column (total days) from the table. I thought I had set it up right but I am getting this error:
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'myRepository':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Validation failed for query for method
public abstract java.lang.Float
com.nissan.rca.repository.MyRepository.selectTotals()!
Here is a representation of my entity:
@Entity
@Table(name = "TABLENAME")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class MyEntity implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private MyEntityCompositeKey myEntityCompositeKey;
@Column(name = "raiser_id")
private String raiserID;
@Column(name = "total_days")
private Float totalDays;
and here is my repository in which I make the query assigned to a method:
@Repository
public interface MyRepository extends JpaRepository<MyEntity, ID> {
@Query("SELECT SUM(total_days) FROM MyEntity")
Float selectTotals();
}
I call the selectTotals() method from myRepository object in my rest controller for the api mapping.
@GetMapping("/getForecastTotals")
public Float getForecastTotals() {
return myRepository.selectTotals();
}
I'm unsure as to why it can't be returned as a float.
You cant actually use both of them in the same application. For backwards compatibility. We are expanding our application and want to start using Spring Data JPA, but still keep the old hibernate implementation. Its better you develop your new application as a separate microservice and use spring data jpa ..
Its findById method retrieves an entity by its id. The return value is Optional<T> . Optional<T> is a container object which may or may not contain a non-null value. If a value is present, isPresent returns true and get returns the value.
If a given JPA GROUP BY query returns only two columns where one is unique, it's very suitable to return the result as a Java Map. For this, you can use either the Java Stream functionality or the Hibernate-specific ResultTransformer .
The hibernate application can be created with annotation. There are many annotations that can be used to create hibernate application such as @Entity, @Id, @Table etc. Hibernate Annotations are based on the JPA 2 specification and supports all the features. All the JPA annotations are defined in the javax.
It's not a valid JPQL.
You either should have:
@Query("SELECT SUM(m.totalDays) FROM MyEntity m")
or, make it a native one:
@Query(value = "SELECT SUM(total_days) FROM MyEntity", nativeQuery = true)
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