Cascade Merge not working fine

时间:2015-06-15 15:07:24

标签: java spring hibernate jpa

I have created this code:

Sale sale = new Sale();
sale = saleService.create(sale);

Company company = new Company("companyName");

Vendor vendor = new Vendor("name", company);

sale.setVendor(vendor);

try {
        sale = saleService.update(sale);
    } catch (EntityNotFoundException ex) {
        System.err.println("");
    }

Product product = new Product("name", company);
sale.setProduct(product);

try {
        sale = saleService.update(sale);
    } catch (EntityNotFoundException ex) {
        System.err.println("");
    }

Also, sale is in cascade with vendor:

@ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, 
 targetEntity = Vendor.class)
private Vendor vendor;

and Vendor and Product with Company:

@ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, 
 targetEntity = Company.class)
private Company company;

The saleService has this code:

@Transactional
public Sale create(Sale entity) {
    Sale created = entity;
    saleRepository.saveAndFlush(created);
    return created;
}

@Transactional(rollbackFor = EntityNotFoundException.class)
public Calibration update(Calibration entity) throws EntityNotFoundException {

   if (!calibrationRepository.exists(entity.getId())) {
        throw new EntityNotFoundException();
    }


    return calibrationRepository.saveAndFlush(entity);
}

It's also annoted as @Service. The repository is an Interface that implements JpaRepository<Sale, Long>.

I'm getting an Error saying that the name property of Company is duplicated, and it must not be. It's clear to me that the code is trying to created another company in database. How to just merge or use the already created one?

Thanks!

0 个答案:

没有答案