Java JPA – Is ElementCollection Considered Bad Practice?

databasedesignjavajpa

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?

Best Answer

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.