在JPA或Hibernate中,枚举是否可以实现多对多关系?

时间:2016-10-05 09:57:51

标签: hibernate jpa enums many-to-many

我的问题基本上是标题,下面的文字描述了我尝试使其发挥作用。那么,我正在努力实现这一目标,还是应该创建一个Category类,并在枚举和实体之间进行转换?

ArticleCategory有多对多的关系,但Category是一个枚举,会造成麻烦。 JPA很好地创建表,但是当我查询类别时,抛出了这个异常:

JpaSystemException:没有实体的默认构造函数:Category。

我有一个构造函数,但枚举的构造函数只能是私有的,而JPA规范声明实体的默认构造函数应该是public或protected。

类别枚举:

@Entity
public enum Category {

    HOME_NEWS("home news"),
    FOREIGN_NEWS("foreign news"),
    POLITICS("politics"),
    BUSINESS("business"),
    BREAKING("breaking"), // and updates
    SCIENCE("science"),
    OPINION("opinion"),
    SPORTS("sports"),
    ENVIRONMENT("environment"),
    TECHNOLOGY("technology"),
    TRAVEL("travel"),
    FASHION("fashion"),
    LIFESTYLE("lifestyle"),
    HEALTH("health"),
    ARTS("arts"),
    FOOD("food"),
    CULTURE("culture"),
    GLAMOUR("glamour"),
    PHOTOGRAPHY("photography"),
    NOT_DEFINED("not defined");

    @Id
    @GeneratedValue
    private long id;
    @Column(unique = true)
    private String name;

    Category() {
    }

    Category(String name) {
        this.name = name;
    }

    private static Map<String, Category> nameToValueMap = new HashMap<>();

    static {
        for (Category category : EnumSet.allOf(Category.class)) {
            nameToValueMap.put(category.name(), category);
        }
    }

    public static Category forName(String name) {
        return nameToValueMap.get(name);
    }

    public String toString() {
        return this.name;
    }

}

部分文章类:

@Entity
public class Article implements Comparable<Article> {

    @ElementCollection
    @JoinTable(name = "article_category",
            joinColumns = {@JoinColumn(name = "article_id")},
            inverseJoinColumns = {@JoinColumn(name = "category_id")})
    private Set<Category> categories = new HashSet<>(0);
}

0 个答案:

没有答案