我有几个表按照每个子类的方式映射。Hibernate Table Per Subclass和NonUniqueObjectException
在层次结构的顶部是EmployeeTransaction,其中包含一个复合主键类:
public class EmployeeTransaction implements Serializable {
private TransactionCompositeId id;
@Id
public TransactionCompositeId getId() { // etc }}
}
public static class TransactionCompositeId implements Serializable {
public String employeeId;
public Long transactionId;
// getters/setters
}
所以,子类我的人物之一是HiringTransaction:
@PrimaryKeyJoinColumns(//etc)
public class HiringTransaction extends EmployeeTransaction implements Serializable {
// etc
}
现在,有些情况下需要自行创建EmployeeTransaction,然后再与其中一个子类关联。
下面是单元测试,这是导致NonUniqueObjectException一些代码:
@Test
@Rollback(false)
public void testSave()
{
final TransactionCompositeId id = new TransactionCompositeId("777777777",553942L);
EmployeeTransaction pt = new EmployeeTransaction(); pt.setId(id);
pt.setLastUpdate(date);
pt.setLastUpdatedBy(user);
pt.setCreatedBy(user);
pt.setCreationDate(date);
// various setters
employeeTransactionDAO.save(pt);
//EmployeeTransaction pt1 = employeeTransactionDAO.get(id);
TransactionCompositeId newId = new TransactionCompositeId("777777777",553942L);
HiringTransaction eth = new HiringTransaction();
BeanUtils.copyProperties(pt, eth);
//HiringTransaction eth = (HiringTransaction) pt;
//HiringTransaction eth = new HiringTransaction(pt);
eth.setId(newId);
// various setters/getters
dao.save(eth);
HiringTransaction tempEth = dao.get(id);
assertNotNull("HiringTransaction should not be null", tempEth);
dao.remove(id);
ptDAO.remove(id);
tempEth = dao.get(id);
EmployeeTransaction tempPt = ptDAO.get(id);
assertNotNull("EmployeeTransaction should not be null", tempEth);
assertNotNull("HiringTransaction should not be null", tempPt);
}
我怀疑的是,我不能把这两项活动的单一的UnitOfWork内。但是,我不知道如何解决NonUniqueObjectException。由于映射是每个子类的表,所以id肯定是相同的。
注:DAO的简单通用的DAO调用session.save(),Session.merge()来等
我有一个问题,为每个类和复合主键的表创建一个HBM文件。你能帮我创建映射文件吗? http://stackoverflow.com/questions/36955085/how-to-define-hibernate-mapping-file-with-table-per-subclass-and-composite-id – Razavi 2016-05-01 05:10:43
我不使用HBM文件,只有注释。 – Jason 2016-05-02 12:03:19