Given that you said Type
is probably predefined, it seems more reasonable to model it as enum
, and making use of ElementCollection
(I have to admit that I haven't tried to use them both in combination, I believe it should work though :P )
public enum Type {
SPORT, CLOTHES, TECH
}
public class Shop {
@Id
private Long id;
@ElementCollection
@CollectionTable(
name="SHOP_TYPE",
joinColumns=@JoinColumn(name="SHOP_ID")
)
@Column(name="TYPE")
// mapping for enum by usertype or other way, depending on JPA version you are using
private List<Type> types;
}
Of course, you can model SHOP_TYPE
as an entity (e.g. ShopType
) if you want more complicated operations on it, but what described above looks to me a more reasonable domain model.
Even you do not want the Type
to be predefined (i.e. you can create whatever type in your application), it is still more reasonable to model it as a ManyToMany
relationship:
public class Type {
@Id
@Column(name="TYPE_ID")
private Long id
@Column(name="TYPE_NAME")
private String name;
}
public class Shop {
@Id
@Column(name="SHOP_ID")
private Long id;
@ManyToMany
@JoinTable(
name="SHOP_TYPE",
joinColumns=@JoinColumn(name="SHOP_ID"),
inverseJoinColumns=@JoinColumn(name="TYPE_ID"))
private List<Type> types;
}
Just one thing to note: It does not look right to have a Type
entity which contains a String as type name, and refer to Shop
(as some of the answer suggested). Type
should be an entity of itself, and, for example, different shops having CLOTHES
type should refer to same CLOTHES
entity (unless you view types as some kind of arbitrary tag)