【问题标题】:Spring data @Query insert, DBC style parameters (?) are not supported for JPA queriesJPA 查询不支持 Spring 数据 @Query 插入、DBC 样式参数 (?)
【发布时间】:2019-09-08 18:59:36
【问题描述】:

我正在尝试在我的界面中进行自定义插入查询,以扩展 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


【解决方案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

【讨论】:

  • 感谢您的提问,我还发现了这一点:在 JPA 中,从瞬态状态变为托管状态的每个实体都由 EntityManager 自动处理。 EntityManager 检查给定实体是否已经存在,然后决定是否应该插入或更新它。由于这种自动管理,JPA 允许的唯一语句是 SELECT、UPDATE 和 DELETE。
  • 还有一件事,如果你想扩展 JpaRepository,确保实现扩展 JpaRepository 接口的类与 Impl 和 end 的接口同名,例如:CustomerCouponDAO exnteds JpaRepository 实现类:CustomerCouponDAOImpl 实现实现 CustomerCouponDAO 否则将不起作用。来源:docs.spring.io/spring-data/jpa/docs/current/reference/html/…
  • 是的,我的意思是“遵守 Spring 找到实现的命名约定”。我想我应该更清楚地表达自己。
  • 哦,我的错!我偶然发现的另一件事,感谢上帝,我克服了它大声笑:我的 CustomerCouponDAOImpl 类在经过大量测试后给了我“应用程序上下文中一些 bean 的依赖关系形成一个循环”,如果我没记错的话,问题是我正在尝试实现 JpaRepository 接口并有一个自定义方法,该方法要求您相应地命名您的实现类,我不知道为什么,但是一旦我为 JpaRepository (CustomerCouponDAO 扩展了 JpaRepository)创建了一个新接口,没有自定义方法,错误停止。
  • 是的,不需要向你的仓库添加扩展方法,这仅在使用@RepositoryRestResource 注解时需要,而不是@Repository。从CustomerCouponDAO 中删除自定义方法,这应该可以正常工作。记住将两个接口都标记为@Repository。补充了答案。
猜你喜欢
  • 2020-08-04
  • 2019-02-01
  • 2018-10-11
  • 2016-08-19
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
相关资源
最近更新 更多