springjpaspring-data-jpaspring-data

Spring data @Query insert, DBC style parameters (?) are not supported for JPA queries


I am trying to make a custom insert query in my interface that exnteds JpaRepository

public interface CustomerCouponDAO extends JpaRepository<CustomerCoupons, Integer>{

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

}

but when I get the exception:

Caused by: java.lang.IllegalArgumentException: JDBC style parameters (?) are not supported for JPA queries.

any ideas on how to make that insert query?


Solution

  • Use PersistentContext. Interface:

    @Repository
    public interface CustomerCouponDAOExtend {
    
        public void insert(Integer custid, Integer coup);
    
    }
    

    Implementation:

    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);
        }
    
    }
    

    Also you can use persist, but in this case your necessary add CustomerCoupons custCoupons = em.find(CustomerCoupons.class, coup); to avoid problems if the row is already in DB. Extend your own interface:

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

    UPDATE: Observe the naming convention that Spring finds implementation: if extend repository has name CustomerCouponDAOExtend then the implementation should be called CustomerCouponDAOExtendImpl.