Search code examples
javaspring-bootannotationsmapping

My table is not mapped when using modifying and query annotations?


I am using @Modifying and @Query annotations to execute my sql statement directly, but I am getting an error, telling me that my table in not mapped, so I dont know what I am doing wrong, Here is my code :

@Repository
public interface TypesContratDaoJPA extends CrudRepository<Type, Long> {

    @Query("select type_id from declaration_type where declaration_id=:declaration")
    List<Integer> getListTypes(@Param("declaration") int declaration);

    @Modifying
    @Query("insert into declaration_type values(:declaration,:type)")
    void addTypeToContrat(@Param("declaration") int declaration, @Param("type") int type);

    @Modifying
    @Query("delete from declaration_type where declaration_id=:declaration and type_id=:type")
void deleteTypeFromContrat(@Param("declaration") int declaration, @Param("type") int type);

}

I get this error :

Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: declaration_type is not mapped [delete from declaration_type where declaration_id=:declaration and type_id=:type]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:133)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:670)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)

...
... 
... 
...

Any help would be much appreciated.


Solution

  • It looks like you want to execute a native query instead of a JPQL one.

    In order to mark the queries as native you should add nativeQuery = true as a property on he @Query annotation. For example your first query should look like this:

    @Query("select type_id from declaration_type where declaration_id=:declaration", nativeQuery = true)
        List<Integer> getListTypes(@Param("declaration") int declaration);
    

    If you don't add nativeQuery = true in the query annotation, the query is considered a JPQL query.
    So, in order to make your first query work, you will have to have a class named declaration_type that is annotated with the @Entity and has fields that are named declaration_id and type_id. You should checkout some JPQL tutorial (or the documentation) in order to learn more about these type of queries.