Home > Blockchain >  How would I display both first name and Surname on my html spring boot jdbc
How would I display both first name and Surname on my html spring boot jdbc

Time:02-17

I am using a select statement in my jdbcTemplate. I am trying to select firstname and surname and display them on the html page however I am getting errors.The error code I am getting on the HTml page is "Incorrect column count: expected 1, actual 2"

    public List<String> getAllUserNames() {
    List<String> usernameList = new ArrayList<>();
    usernameList.addAll(jdbcTemplate.queryForList("SELECT FirstName,Surname from paitents",String.class));
    return usernameList;
}

Html file

<tr th:each="user : ${users}">
    <a href="#" th:text="${user}   ${user.Surname}" ></a> <br>
<!--    <td th:text="${user}"> </td> <br>-->

</tr>
</body>

CodePudding user response:

You are constructing a String List and then trying to insert a complex object type into the list. You have two solutions here; first one is to use a complex type and use that list. An example might be as follows:

public List<User> findAllUsers() {
   String sql = "SELECT FirstName,Surname from paitents";
   return jdbcTemplate.query(sql,
                (rs, rowNum) ->
                        new User(
                                rs.getString("FirstName"),
                                rs.getString("Surname")
                        ));
}

And then in thymeleaf code:

<tr th:each="user : ${users}">
    <a href="#" th:text="${user.FirstName}   ${user.Surname}" ></a> <br>
</tr>

Another solution is a quick fix and you can use a sql trick to do that:

public List<String> getAllUserNames() {
    List<String> usernameList = new ArrayList<>();
    usernameList.addAll(jdbcTemplate.queryForList("SELECT CONCAT(FirstName, ' ', Surname) AS FullName from paitents",String.class));
    return usernameList;
}

You should put this List in a model at your controller method:

model.addAttribute("fullNameList", usernameList);

And then in view layer:

<tr th:each="fullName : ${fullNameList}">
    <a href="#" th:text="${fullName}" ></a> <br>
</tr>
  • Related