Spring数据@Query插入,JPA查询不支持DBC样式参数(?)

问题描述 投票:0回答:2

我正在尝试在扩展 JpaRepository 的界面中创建自定义插入查询

public interface CustomerCouponDAO extends JpaRepository<CustomerCoupons, Integer>{

    @Query("INSERT into customer_coupons (customerId, couponId) values (?,?)")
    public void insert(Integer custid, Integer coup);

}

但是当我遇到异常时:

引起:java.lang.IllegalArgumentException:JDBC样式参数 (?) 不支持 JPA 查询。

关于如何进行插入查询有什么想法吗?

spring jpa spring-data-jpa spring-data
2个回答
1
投票

使用

PersistentContext
。 接口:

@Repository
public interface CustomerCouponDAOExtend {

    public void insert(Integer custid, Integer coup);

}

实施:

public class CustomerCouponDAOExtendImpl {

    @PersistenceContext
    private EntityManager em;

    @Transactional
    public void insert(Integer custid, Integer coup) {
        CustomerCoupons custCoupons = new CustomerCoupons();
        custCoupons.setCustid(custid);
        custCoupons.setCoup(coup);
        em.merge(custCoupons);
    }

}

您也可以使用

persist
,但在这种情况下您需要添加
CustomerCoupons custCoupons = em.find(CustomerCoupons.class, coup);
以避免该行已在数据库中出现问题。 扩展您自己的接口:

@Repository
public interface CustomerCouponDAO 
    extends JpaRepository<CustomerCoupons, Integer>,CustomerCouponDAOExtend{
}

更新: 观察 Spring 找到实现的命名约定:如果扩展存储库的名称为

CustomerCouponDAOExtend
,那么该实现应该被称为
CustomerCouponDAOExtendImpl


0
投票

无论如何都来不及回答:在 JPA 中,对于自定义方法,您必须在查询注释中设置参数数量:

public interface CustomerCouponDAO extends JpaRepository<CustomerCoupons, Integer>{

@Query("INSERT into customer_coupons (customerId, couponId) values (?1,?2)")
public void insert(Integer custid, Integer coup);

}

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.