java org.h2.jdbc.JdbcSQLException:方法只允许用于查询

pkmbmrz7  于 2023-01-01  发布在  Java
关注(0)|答案(4)|浏览(152)

我已经使用下面的代码在我的数据库上运行了一个查询。

@Repository
public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, PurchaseOrderID> {

    @Query(value ="update PURCHASE_ORDER   set status='REJECTED'   where id=?1", nativeQuery = true)
    void RejectPO(Long id);
}

然后在服务中调用这个方法

@Service
public class SalesService {

    @Autowired
    PurchaseOrderRepository purchaseOrderRepository;
public void RejectPurchaseOrder(Long of) {

        purchaseOrderRepository.RejectPO(of);
    }
}

但我面对一个错误:

org.h2.jdbc.JdbcSQLException: Method is only allowed for a query. Use execute or executeUpdate instead of executeQuery; SQL statement:
update PURCHASE_ORDER   set status='REJECTED'   where id=? [90002-191]

问题是,我从来没有调用过executeQuery,我只是要求使用jpa运行它。那么我该如何修复它呢?

hc8w905p

hc8w905p1#

为了让JPA真正运行修改数据库状态的定制@Query,必须使用@Modifying注解该方法,以告知JPA使用executeUpdate等。
代替

@Query(value ="update PURCHASE_ORDER   set status='REJECTED'   where id=?1", nativeQuery = true)
void RejectPO(Long id);

试试看

@Modifying
@Query(value ="update PURCHASE_ORDER   set status='REJECTED'   where id=?1", nativeQuery = true)
void RejectPO(Long id);

详情请访问http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.modifying-queries。

t30tvxxf

t30tvxxf2#

问题出在这一行:

// Used only when select statement is used .
 @Query(value ="update PURCHASE_ORDER   set status='REJECTED'   where id=?1", nativeQuery = true)
    void RejectPO(Long id);

您试图对模式执行update操作,但只使用了@Query注解。
当一个查询方法只使用@Query注解时,Spring内部调用executeQuery(),它不用于modify Schema中的值。executeQuery()只负责执行select查询。
再添加一个注解,使您的@Query能够更新:

@Modifying  // add this annotation
 @Query(value ="update PURCHASE_ORDER   set status='REJECTED'   where id=?1", nativeQuery = true)
    void RejectPO(Long id);
qxsslcnc

qxsslcnc3#

您收到org.h2.jdbc.JdbcSQLException消息是因为您没有将@Modifying注解应用于存储库方法void RejectPO(Long id);

@Modifying
@Query(value ="update PURCHASE_ORDER   set status='REJECTED' where id=?1", nativeQuery = true)
void RejectPO(Long id);
1dkrff03

1dkrff034#

问题似乎就在这里

@Repository
public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, PurchaseOrderID> {

    @Query(value ="update PURCHASE_ORDER   set status='REJECTED'   where id=?1", nativeQuery = true)
    void RejectPO(Long id);
}

我在界面上添加了@Transactional & @Modifying,就像这样,它工作了

@Transactional
 @Repository
 public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, PurchaseOrderID> {
    @Modifying
    @Query(value ="update PURCHASE_ORDER   set status='REJECTED'   where id=?1", nativeQuery = true)
    void RejectPO(Long id);
}

希望能有所帮助

相关问题