Search code examples
javaspringthymeleafrethinkdb

How would I return a list of data from RethinkDB in Java for Spring/thymeleaf


So I have a table (in RethinkDB called videos) and I want to have a function that would return all the data in a list (or something else). Because I want to have a webpage with all the videos that are in my table using thymeleaf (to iterate over the list).

I've been looking at the RethinkDB documentation, and trying out those examples. But the main problem is always to be able to convert the data to a list.

For example:

@GetMapping("/videos")
public String showVideos(Model model) {      
    System.out.println(Videos.getVideos(conn));
    return "videos";
}
public static Table getVideos(Connection conn) {
    Table videos = r.table("videos").run(conn);
    return videos;
}

Results in:

nested exception is java.lang.ClassCastException: class com.rethinkdb.net.Cursor$DefaultCursor cannot be cast to class java.util.List (com.rethinkdb.net.Cursor$DefaultCursor is in unnamed module of loader 'app'; java.util.List is in module java.base of loader 'bootstrap')] with root cause

java.lang.ClassCastException: class com.rethinkdb.net.Cursor$DefaultCursor cannot be cast to class java.util.List (com.rethinkdb.net.Cursor$DefaultCursor is in unnamed module of loader 'app'; java.util.List is in module java.base of loader 'bootstrap')

When using this code:

Cursor cursor = r.table("videos").run(conn);
for (Object doc : cursor) {
     System.out.println(doc);
}

I'm able to see every value. But then again I wouldn't have a clue how to actually put it in a way thymeleaf would be able to iterate over it.

In the RethinkDB Documentation I've also found this:

try(Result<Object> result = r.table("users").run(conn)) {
    for (Object doc : result) {
        processResult(doc);
    }
}

But I can't seem to find where the Result (I think it's a class) comes from.


Solution

  • Solution I found:

    @GetMapping("/videos")
       public String showVideos(Model model) {
           ArrayList<Videos> videosHTML = new ArrayList<Videos>();
           Cursor<Videos> videos = r.table("videos").run(conn, Videos.class);
    
           for(Videos vid : videos) {
               videosHTML.add(vid);
           }
           model.addAttribute("videotitles", videosHTML);
           return "videos";
       }
    
    <tr th:each="vid: ${videotitles}">
            <td th:text="${vid.title}"></td>
            <td th:text="${vid.description}"></td>
            <td th:text="${vid.id}"></td>
            <a th:href="'/video/'+${vid.id}"
                href="/video.html"
                class="buttonLook mediumButton">Watch Video</a>
            <br>
    </tr>