Search code examples
javadatabasehibernatehql

How to retrieve multiple entries from table into one list?


thanks for helping ;)

I'm new to hibernate and wanna try it for my private project.
What i want to do is: I want to have a class like

public class Playlist {
    private long id;
    private String name;
    private long owner_ID;
    private ArrayList<String> urls;
}

Where the list should contain urls to some songs.

At the moment I have one entry in my db for each url. Is there a better way to do that? And to my main question: How can I recieve/save the list?

I can get a "normal" table entry rn but I haven't worked with Hibernate and Lists/ArrayLists in combination jet.

Hope you can help me ;)

If additional information is required feel free to ask.


Solution

  • Since the urls is a basic value (String) you can use @ElementCollection.

    @Entity
    public class Playlist {
        @Id
        private Long id;
        private String name;
        private long owner_ID;
        
        @ElementCollection
        private List<String> urls;
    }
    

    This mapping links two tables:

    • playlist table which has id, name, owner_ID columns
    • playlist_urls table which has playlist_id and urls columns.

    For more information take a look at here.