我的环境
Java 8 / Spring Data JPA 2.0.5 / JPA 2.1 / Eclipse Link 2.6.4 / JBoss EAP 7.1
我的情况
我有三个实体(@Entity):文件夹,配置和文档。
我有三个存储库(@Repository):FolderRepository,ConfigurationRepository和DocumentRepository。
我有一项服务(@Service):TestService。
交易性仅在TestService方法中定义。
我的问题
如果我们执行'test'方法,代码将尝试将'Folder'实体保留在数据库中:
我不明白,如果我们分离了实体,为什么会抛出此异常。该实体不应位于持久性上下文中。
我的代码
@Service
public class TestServiceImpl implements TestService
{
@Autowired
private FolderRepository folderRepository;
@Autowired
private ConfigurationRepository configurationRepository;
@Autowired
private DocumentRepository documentRepository;
@PersistenceContext
private EntityManager em;
@Override
@Transactional(readOnly = false)
public void test(String documentCode)
{
List<Configuration> configuration = configurationRepository.findAll();
DateFormat dateFormat = new SimpleDateFormat("yyyyMM");
Date date = new Date();
String folderName = dateFormat.format(date)
Folder folder = new Folder ();
folder.setName (folderName); //Primary key
folder.setDateCreation (date);
// We try to persist 'folder' entity using an EntityManager instance.
// We don't use 'saveAndFlush' because we don't want a merge happens.
// If constraint exception is thrown, we detach the 'folder' entity
try
{
em.persist(folder);
em.flush();
}
catch (PersistenceException e)
{
em.detach(folder);
}
// Why is a SQLIntegrityConstraintViolationException thrown here?
folder = documentRepository.findById (documentCode);
............ more code ............
}
}