Is Java's ElementCollection Considered a Bad Practice?
Posted
by
SoulBeaver
on Programmers
See other posts from Programmers
or by SoulBeaver
Published on 2013-11-05T11:07:21Z
Indexed on
2013/11/05
16:11 UTC
Read the original article
Hit count: 325
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?
© Programmers or respective owner