Fabian Lurz Fabian Lurz - 22 days ago 5
Java Question

Copying an entity in JPA

I want to copy an entity (in this case a PageEntity) in JPA.

This is my code:

@Override
public PageEntity copyPage(Long pageId, PageEntity pageEntity) {


PageEntity pageToCopy=new PageEntity();
BeanUtils.copyProperties(findOne(pageId),pageToCopy);

//Save new template
TemplateEntity templateCopy = pageToCopy.getTemplate();
templateCopy.setBlocks(null);
templateCopy.setId(null);

TemplateEntity copiedTemplate = templateDao.saveAndFlush(templateCopy);

//Save new page
pageEntity.setTemplate(copiedTemplate);

Long copiedPageId=pageDao.saveAndFlush(pageEntity).getId();

//Save blocks and parameters
List<BlockEntity> blockCopy = pageToCopy.getTemplate().getBlocks();

for(BlockEntity block : blockCopy){
block.setId(null);
block.setTemplateId(copiedTemplate.getId());
for(ParameterEntity parameter : block.getParameters()){
parameter.setId(null);
}
blockDao.saveAndFlush(block);
}

return pageDao.findOne(copiedPageId);

}


The problem is, that I can not alter the id - I always get an exception:

"identifier of an instance of de.smava.dao.entity.TemplateEntity was altered from 1 to null; nested exception is org.hibernate.HibernateException: identifier of an instance of de.smava.dao.entity.TemplateEntity was altered from 1 to null",


I totally get what this means - but still. I need to copy a whole page and create a new Id. How to achieve this?

Answer

Simply detach the entity before the copy:

 yourEntityManager.detach(copiedTemplate);
 //Save new page
 pageEntity.setTemplate(copiedTemplate);