【发布时间】:2012-02-03 01:21:29
【问题描述】:
我对 Hibernate 还很陌生,需要一些有关 hibernate 映射的帮助。
我有 4 个不同的类,我想将它们映射到一个表中,其中主键由来自 2 个不同类的属性组成。同时,我只想将每个类中选定的属性映射到本地数据库中。我希望避免使用 JPA 注释,而是在 hbm.xml 文件中定义映射样式。我该怎么做?
举个例子:
public class Tenant implements Serializable {
private final static long serialVersionUID = 1L;
protected List<Rack> rack;
protected String type;
//getters setters
}
public class Rack implements Serializable {
private final static long serialVersionUID = 1L;
protected List<Circuit> circuit;
protected String rackLabel;
protected Boolean excludes;
//getters setters
}
public class Circuit implements Serializable {
private final static long serialVersionUID = 1L;
protected List<CircuitReadings> circuitReadings;
protected String circuitNo;
protected Boolean excludes;
//getters setters
}
public class CircuitReadings
implements Serializable {
private final static long serialVersionUID = 1L;
protected String date;
protected String kva;
protected String current;
protected String kwh;
//getters setters
}
最终的表格应包含以下内容:
type | rackLabel | circuitNo | date | kva | current | energy
上面的“circuitNo”和“date”应该构成复合主键。
有人可以给我举个例子来说明我应该如何映射它吗?谢谢!
【问题讨论】:
-
为什么要在一个表中添加所有四个类?从它们的外观来看,所有类之间都有多对一的关系。将它们全部添加到一个表中会产生一个非常非规范化的表。这在关系数据库中通常是一件坏事。
-
这是因为我不想将所有属性都存储到数据库中,而只想要选定的属性。我想要的属性在上面的表格描述中突出显示。我的解决方案是创建一个单独的方法,循环遍历“租户”对象及其子类,并将我想要存储到数据库中的值合并到一个单独的类中,例如A类。然后为 ClassA 创建一个 hbm 文件。我知道这样做并不理想,因此,我正在寻找更优化的解决方案。
标签: java hibernate jakarta-ee mapping hibernate-mapping