我是JPA映射的初学者。我有一个简单的实体(基本上是一个2D矩阵),为每个产品组/成本组组合指定一个值。
@Entity
public class CostDistribution {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@NotNull
@OneToOne
private ProductGroup productGroup;
@NotNull
@OneToOne
private CostGroup costGroup;
private Long value;
}
现在,我希望在加载ProductGroup时获得对此矩阵的相关列的只读访问权限(即,加载所有Cost_istribution记录,其中product_group_id等于当前产品组的id)。我无法弄清楚如何做到这一点。这就是我试过的:
@ElementCollection
@CollectionTable(name="cost_distribution", joinColumns=@JoinColumn(name="product_group_id"))
但我得到一个例外:Same physical table name [cost_distribution] references several logical table names: [CostDistribution], [cost_distribution]
我在这里误解了什么?
@Entity
public class ProductGroup {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(length=50)
@NotNull
@Size(max=50)
private String name;
@???
private List<CostDistribution> costDistribution;
}
答案 0 :(得分:0)
正确回答从矩阵加载相关数据:
@OneToMany(mappedBy="productGroup", fetch=FetchType.EAGER)
private List<CostDistribution> costDistribution;
这从连接器表连接到正确的列。例如,在加载id = 1的产品组时:
select productgro0_.id as id1_6_0_, productgro0_.name as name2_6_0_, ..., costdistri1_.value as value2_2_2_,
from product_group productgro0_
left outer join cost_distribution costdistri1_ on productgro0_.id=costdistri1_.product_group_id
left outer join cost_group costgroup2_ on costdistri1_.cost_group_id=costgroup2_.id where productgro0_.id=1