Spring Data:如何在mySQL数据库中存储枚举列表

时间:2017-07-05 08:47:00

标签: java mysql spring enums spring-data

在下面的代码中我有一个字段shopType实际上是enum,在我的场景中,一个商店有多种类型,例如商店ABC有杂货店和药店,所以我想要在我的数据库中将enum列表存储在单独的表中,其中两列显示为shop_id而另一列为shop_type,以便一个商店可以有多种类型我该怎么做?

这是我的代码

ShopDetail.java

@Entity
public class ShopDetail {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String address;

    private Double latitude;

    private Double longitude;

    private float  rating;

    private Time openingTime;

    private Time closingTime;



    @Enumerated(EnumType.STRING)
     private Collection<ShopType> shopType;


    @Column(columnDefinition=" bit(1)default 1")
    private boolean shopEnabled = true;

    //getters and setters
    }

ShopType

public enum ShopType {

    GROCERY,
    PHARAMACY
}

1 个答案:

答案 0 :(得分:2)

这应该有效:

@ElementCollection(targetElement = ShopType.class)
@JoinTable(name = "tblShopTypes", joinColumns = @JoinColumn(name = "id"))
@Column(name = "shopType", nullable = false)
@Enumerated(EnumType.STRING)
Collection<ShopType> shopTypes;

参考:this answer