JPA + Hibernate将java.util.Set中的java.util.Set映射到另一个Entity java.util.Map

时间:2017-10-28 17:33:34

标签: java hibernate jpa

我的项目中出现了JPA + Hibernate映射问题(我是hibernate和jpa的新手,所以请耐心等待:)。

以下是我的实体:

@Entity
@Table(name = "yeasts")
public class Yeast {

...
private Set<BeerRecipe> recipes;
...

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "recipe_yeasts"
        ,joinColumns = @JoinColumn(name = "yst_id", referencedColumnName = "yst_id")
        ,inverseJoinColumns = @JoinColumn(name = "brp_id", referencedColumnName = "brp_id"))
public Set<BeerRecipe> getRecipes() {
    return recipes;
}

public void setRecipes(Set<BeerRecipe> recipes) {
    this.recipes = recipes;
}
}

和第二个:

@Entity
@Table(name = "beer_recipes")
public class BeerRecipe {

...
private Map<Yeast,Double> yeasts;
...
@ManyToMany(cascade = CascadeType.ALL)
@ElementCollection
@JoinTable(name = "recipe_yeasts"
        ,inverseJoinColumns = @JoinColumn(name = "yst_id", referencedColumnName = "yst_id")
        ,joinColumns = @JoinColumn(name = "brp_id", referencedColumnName = "brp_id"))
public Map<Yeast, Double> getYeasts() {
    return yeasts;
}

public void setYeasts(Map<Yeast, Double> yeasts) {
    this.yeasts = yeasts;
}

...
}

我被困在这里,因为我无法找到问题的解决方案。我需要我的BeerRecipe对象来存储Map&lt;酵母双动和GT; (双倍表示啤酒配方中使用的酵母量),和酵母对象存储Set&lt; BeerRecipe&gt;(多对多的关系 - X啤酒食谱使用相同的酵母和X酵母在同一食谱中使用)

现在我得到一个例外:

Use of @OneToMany or @ManyToMany targeting an unmapped class: 
my.project.db_model.BeerRecipe.yeasts[java.lang.Double]

1 个答案:

答案 0 :(得分:0)

示例解决方案:

@Entity
@Table(name = "yeasts")
public class Yeast {

    @Id
    private int yst_id;

    @OneToMany(cascade=CascadeType.ALL, mappedBy="yeasts")
    private Set<BeerRecipe> recipes;

    ...
}

@Entity
@Table(name = "beer_recipes")
public class BeerRecipe {

    @Id
    private int brd_id;

    @ElementCollection
    @CollectionTable(name = "recipe_yeasts", joinColumns = @JoinColumn(name = "brd_id"))
    @MapKeyJoinColumn(name = "yst_id", referencedColumnName = "yst_id") //refers to Yeast
    @Column(name = "amount") //refers to Double
    private Map<Yeast, Double> yeasts;

    ...
}

通过这种方法,您可以保持beer_recipes和酵母之间的双向关系。地图代表之间的recipe_yeasts连接表。