0

I am trying to use named jdbctemplate.update to fire a delete query but somehow this query is not working.

This is my code

Order looks something like this

public class Order {
  private Long cuId;
  private String supplierType;
  private String customerType;
  private String orderType;
}

final List<Order> ordersStuckInNewStatus; //defined like this


//main code starts here

List<String> cuIds=
      ordersStuckInNewStatus.stream()
          .map(Order::getCuId)
          .map(id -> String.format("'%s'", id))
          .collect(Collectors.toList());
         
 syso(cuIds)      //Output:- ['193111000000000451']


  SqlParameterSource parameters = new MapSqlParameterSource("cuIds", cuIds);      
  
syso(parameters )      //Output:- MapSqlParameterSource {cuIds=['193111000000000451']}


  int deleteCount = 0;
  String sql = "DELETE FROM OLCM.REJECTED_EVENT where entity_id IN (:cuIds)";
  deleteCount = namedJdbcTemplate.update(sql, parameters);
  
  log.info("Delete Count:[{}]", deleteCount);
  

This is how many logs gets printed . No compilation error

Query:["DELETE FROM OLCM.REJECTED_EVENT where entity_id IN (?)"], Params:[('193111000000000451')]
Delete Count:[0]

Even though the correct query gets fired but somehow the reords did not get deleted. The records do exists in db.

Note:

  • entity_id is varchar

  • Instead of List<String> cuid if i use the below code it works

    List<Long> cuIds=ordersStuckInNewStatus.stream().map(Order::getCuId).collect(Collectors.toList());

Any reason why this is not working for List<String> but works for List<Long>

Abhishek
  • 650
  • 1
  • 8
  • 31
  • `IN (?)` looks odd; why not `= ?`? It would do exactly the same and looks less ambiguous (as `IN` implies you are passing tuples). – Thom A Dec 13 '22 at 16:46
  • @Larnu because there can be multile cuids/tuples – Abhishek Dec 13 '22 at 16:47
  • 1
    But `?` is a *scalar* value, it can't contain a tuple. If you want to pass *multiple* values you'll need to use a table type parameter or pass a delimited list and *split* that value into a rowset (and `JOIN` to or use an `EXISTS` against that). – Thom A Dec 13 '22 at 16:52
  • but say if i pass like tis it will work right DELETE FROM OLCM.REJECTED_EVENT where entity_id IN ('123','456'). I want this to work – Abhishek Dec 13 '22 at 16:54
  • Why are you surrounding the id value with extra `'` characters? If you watch the query in SQL Profiler or Extended Events you should be seeing this batch getting submitted: `DELETE FROM REJECTED_EVENT where entity_id IN ('''193111000000000451''')`. If `entity_id` is a `bigint` column then the batch should be throwing the error message `Error converting data type varchar to bigint` but if it's a `char`/`varchar` column it's just not going to match any values due to the extra `'` characters wrapping the id. – AlwaysLearning Dec 15 '22 at 11:59

0 Answers0