Custom queries with CrudRepository

走远了吗. 提交于 2019-12-02 23:48:46
Daris

Your first problem is in your JPQL:

@Query("UPDATE customer c SET c.firstName = :firstName WHERE c.id = :id")

type to

@Query("UPDATE Customer c SET c.firstName = :firstName WHERE c.id = :id")

That is because JPQL wants the query's table name to match your Entity Class name.

Another problem could be that you are missing the @Modifying annotation:

@Modifying
@Query("UPDATE customer c SET c.firstName = :firstName WHERE c.id = :id")
  Integer setNewFirstNameForId(@Param("firstName") String firstName, @Param("id") long id);   
}

Every time you want modify by query, you should add the @Modifying anotation because Spring needs to know about it.

Also take in account that when you're creating custom queries you must use the Entity structure and not the final database structure. For example you can have a composed private key. Then you Entity would have an attribute which would be the entity with the attributes that conform the private key. Example:

@Entity(name = "itemPrice")
public class ItemPriceEntity {

    @EmbeddedId
    private ItemPriceComposedPK composedPK;

    // Rest of the fields
    ...

    // Getters and setters
    ...
}

@Embeddable
public class ItemPriceComposedPK implements Serializable {

   @Column
   private String id;

   @Column
   private int iteration;

   // Getters and setters
   ...
}

If you want to use the field iteration, then you must code something like: i.composedPK.iteration. Example:

@Modifying
@Query("select i from itemPrice i where i.composedPK.iteration = :it")
public List<ItemPriceEntity> searchByIteration(@Param("it") String it);

Of course CrudRepository offers a better way to make this query without using custom queries but, as an example, is ok.

Regards!

In query use model/entity name it should work.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!