1

From my understanding, an ElementCollection has no primary key, is embedded with the class, and cannot be queried. This sounds pretty hefty, but it allows me the comfort of writing an enum class which also helps with internationalization (using the enum key for lookup in my ResourceBundle).

Example: We have a user on a media site and he can choose in which format he downloads the files

@Entity
@Table(name = "user")
public class User {    
    /* snip other fields */

    @Enumerated
    @ElementCollection(
            targetClass = DownloadFilePreference.class,
            fetch = FetchType.EAGER
    )
    @CollectionTable(name = "download_file_preference",
        joinColumns = @JoinColumn(name = "user_id")
    )
    @Column(name = "name")
    private Set<DownloadFilePreference> downloadFilePreferences = new HashSet<>();
}

public enum DownloadFilePreference {
    MP3, WAV, AIF, OGG;
}

This seems pretty great to me, and I suppose it comes down to "it depends on your use case", but I also know that I'm quite frankly only an initiate when it comes to Database design. Some best practices suggest to never have a class without a primary key- even in this case? It also doesn't seem very extensible- should I use this and gamble on the chance I will never need to query on the FilePreferences?

3
  • When you use an element collection, you are telling JPA that the collected elements are part of the parent and not entities in and of themselves. That means you can't query them separately - JPA will always load all of them for a given parent. Also, eager fetch on collections can be problematic. Oct 3, 2016 at 15:03
  • @JoshuaDavis You can use @ElementCollection(fetch = FetchType.LAZY) to disable eager fetching of the element collection. Aug 9, 2021 at 14:17
  • @DarioSeidl Yep. That works well! Aug 10, 2021 at 15:25

1 Answer 1

2

I had a simple case with I first solved with an enum that was stored inside a ElementCollection. It would suffice in your situation because you would most likely just query the whole collection and then you can do your operations on the Set. If you want on the other hand to have your choices to be more extensible you should create another Entity for DownloadFilePreferences.

ome best practices suggest to never have a class without a primary key

Just because you didn't declare a primary it doesn't mean that your JPA implementation doesn't create an id on the mapping table.

1
  • Many JPA implementations will put all of the columns of the object in the collection into the primary key, so it behaves like a Set. Oct 3, 2016 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.