Reputation: 86845
@Entity
public class Language {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(length = 2)
private String code; //EN, DE, US
public Language(String code) {
this.code = code;
}
}
@Entity
public class ProductText {
@OneToOne(Cascade.ALL)
private Language lang;
}
ProductText text = new ProductText();
text.setLang(new Language("en")); //what if "en" exists?
dao.save(text);
Now, when I persist the ProductText
, everytime a new Language
object would be generated.
Can I prevent this, and in case a language table entry with code = 'en'
exists this existing entity should be linked instead.
My initial goal is to not having to repeat the countryCodeString "EN" multiple times in my product-text table, but just reference the id. But does this really make sense? Should I rather just use the plain String
without an extra table? (I later want to query a list of productTexts where lang = 'de'
).
Is the only change executing a select like dao.findByLang("en")
before?
Or is there also some hibernate feature that would support this without explicit executing a query myself?
Upvotes: 0
Views: 74
Reputation: 7393
If there is only three different possible values for the language, you can also use an enum like this :
public enum Language {
EN("EN"),
DE("DE"),
US("US");
private String code; //EN, DE, US
public Language(String code) {
this.code = code;
}
// Getter...
}
@Entity
public class ProductText {
@Enumerated(EnumType.STRING)
// Or @Enumerated(EnumType.ORDINAL)
private Language lang;
}
EnumType.STRING
will store the enum in the database as a String, while EnumType.ORDINAL
will store it as an int. Int is maybe a little more efficient, but the mapping could change if you insert a new value in your enum. String is more flexible since it will use the names of your enum members.
In both case, you don't have to manage a separate entity and hibernate will not create an additional table, and it's more type-safe than using a plain string.
Upvotes: 1
Reputation: 8127
If the only value in Language is a 2 or 3 letter string, why not just have the string as a member? This will be quicker and more efficient.
Upvotes: 0
Reputation: 18163
Do you process the value "en" further or do you display it directly? If only used for displaying purposes, I would just store the string, but if you want to reduce redundancy by using foreign key IDs you have to create an Entity
containing the language string en
which can be persisted via entity manager and which you have to obtain out of the entity manager before persisting to reuse it.
Upvotes: 1