None
None

Reputation: 9247

Convert array of string or integers to comma separated integer or string for sql in condition

  public List<String> getCategory(final String logicalUnitCode, final String logicalUnitIdent, final String keyword) {
        return entityManager
                .createNativeQuery(
                        "select name from " + logicalUnitCode + " where " + keyword + "::text in(" + logicalUnitIdent + "::text)")
                .getResultList();
    }

In some case keyword is int8 and logicalUnitIdent is String of integers for example: ("1,2,3,4,5") , and in some cases keyword is varchar and logicalUnitIdent is string (("test,test1,test2"). I want to use one query for both of this cases. Any suggestion how can i achive that and is it possible? To cast both to text or varchar? Im using postgres

Upvotes: 1

Views: 498

Answers (1)

PraveenKumar Lalasangi
PraveenKumar Lalasangi

Reputation: 3523

before calling getCategory() you create logicalUnitIdent String and pass. But modify the query to "in("+logicalUnitIdent+")"

logicalUnitIdent should be "1,2,3" or "'string1','string2','string3' To convert List of string to single quoted and comma separated string use the below code

In JDK 8 or above use this

List<String> stringList = new ArrayList<String>(Arrays.asList("string1","string2","string3"));
        String list= String.join(",", stringList
                .stream()
                .map(name -> ("'" + name + "'"))
                .collect(Collectors.toList()));

System.out.println(list); // prints 'string1','string2','string3'

Upvotes: 1

Related Questions