0

I have a row in my DB enter image description here

And java function

@Select("<script>\n" +
            "SELECT TARIFF FROM MY_TABLE WHERE ROW_ID = #{id}\n" +
       "</script>\n")
List<String> findTariffById(@Param("id") String id);

If I add @ResultType(String.class), i get list with 1 element: "classic;premium;my-conversation"

But i need to get list with 3 element:

"classic"

"premium"

"my-conversation"

If i have POJO class Tariff

@Data
public class Tariff{

    private List<String> name;

}

Than i can change my function to

@Select("<script>\n" +
            "SELECT TARIFF FROM MY_TABLE WHERE ROW_ID = #{id}\n" +
       "</script>\n")
@Results({
    @Result(property = "name", column = "TARIFF", typeHandler = StringArrayListTypeHandler.class)}
)
Tariff findTariffById(@Param("id") String id);

And be happy..

But, I need to get List<String>

Can I get List<String> without creating POJO?

P.S. StringArrayListTypeHandler parse String to List

2 Answers2

0

You can go from your first result, and split it into array list. in my code excerpt the starting list is empty but as commented you should use the list of size one that is initialized from DB. So you manually split the string with the separator ";".

        List<String> returnedListOfSizeOne = new ArrayList<>(); //.add("classic;premium;my-conversation")
        List<String> properlySplitString = new ArrayList<>();
        for(String string: returnedListOfSizeOne){
            Collections.addAll(properlySplitString,string.split(";"));
        }
Akin Okegbile
  • 1,108
  • 19
  • 36
0

You can avoid creating a POJO and still have logic in mapper by using default methods from java 8+:

interface MyMapper {
  @Select("<script>\n" +
            "SELECT TARIFF FROM MY_TABLE WHERE ROW_ID = #{id}\n" +
       "</script>\n")
  String findTariffStringById(@Param("id") String id);

  default List<String> findTariffById(String id) {
     String tariffString = findTarrifStringById(id)
     return Arrays.asList(tariffString.split(";"));
  }
}

Otherwise you can't map one row returned in JDBC resultset to multiple objects in result obtained from the mapper. Either do it java or alternatively do it in DB. For postgres for example like this, here is for mysql.