-1
我在休眠目睹怪異的行爲,我有很多很多的關係,我有表如下圖所示冬眠多對多映射不插入一行到從服務層連接表
Attribute -- Attribute_Category -- Category
當我嘗試運行我的DAO層測試,hibernate在所有三個表中插入行,包括連接表ATTRIBUTE_CATEGORY。
@Test
@Rollback(false)
public void testAddAttribute(){
try {
AttributeDO attributeDO = getAttributeDO();
List<AttributeDO> attributeDOs = new ArrayList<AttributeDO>();
CategoryDO categoryDO = getAttributeDO().getCategoryDOs().get(0);
attributeDOs.add(attributeDO);
categoryDO.setAttributeDOs(attributeDOs);
attributeDAOImpl.addAttribute(attributeDO);
System.out.println("attribute id - " + attributeDO.getAttributeId());
} catch (DataException cExp) {
cExp.printStackTrace();
Assert.fail();
}
}
但是當我嘗試在服務層做同樣的事情,只有映射表插入,但沒有連接表。
我的服務實現代碼
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void addAttribute(AttributeBO attributeBO) throws CrafartServiceException {
AttributeDO attributeDO = mapper.mapAttributeBOToDO(attributeBO, new AttributeDO());
CategoryDO categoryDO = mapper.mapCategoryBOToDO(attributeBO.getCategoryBO(), new CategoryDO(), new SeoDO());
List<CategoryDO> categoryDOs = new ArrayList<>();
categoryDOs.add(categoryDO);
attributeDO.setCategoryDOs(categoryDOs);
// creating bi directional relation ship between attribute --> category table. (category --> attribute cause unidirectional relation)
List<AttributeDO> attributeDOs = new ArrayList<>();
attributeDOs.add(attributeDO);
categoryDO.setAttributeDOs(attributeDOs);
try {
attributeDAOImpl.addAttribute(attributeDO);
attributeBO.setAttributeId(attributeDO.getAttributeId());
} catch (DataException cExp) {
throw new ServiceException("Service error - error while adding attribute", cExp);
}
}
我不看道測試和服務實現之間的區別,我的全部映射博做對象,我做標識合併如下圖所示
@Entity
@Table(name = "ATTRIBUTE")
public class AttributeDO implements Cloneable, Serializable {
/**
* serial id
*/
private static final long serialVersionUID = -8629832877426207073L;
@Id
@Column(name = "attribute_id")
@SequenceGenerator(name = "seq_attribute", sequenceName = "seq_attribute", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_attribute")
private long attributeId;
@ManyToMany(mappedBy = "attributeDOs", cascade=CascadeType.MERGE)
private List<CategoryDO> categoryDOs;
我類別實體
@Entity
@Table(name = "CATEGORY")
public class CategoryDO implements Serializable, Cloneable {
/**
*
*/
private static final long serialVersionUID = -870423497459160593L;
@Id
@Column(name = "category_id")
@SequenceGenerator(name = "seq_category", sequenceName = "seq_category", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_category")
private long categoryId;
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(name = "ATTRIBUTE_CATEGORY", joinColumns = { @JoinColumn(name = "SUB_CATEGORY_ID") }, inverseJoinColumns = { @JoinColumn(name = "ATTRIBUTE_ID") })
private List<AttributeDO> attributeDOs;
需要幫助解決該W奇怪的問題