MrFisherman
MrFisherman

Reputation: 738

How to set unique rows when persist in JPA?

My question is: is there any way to set unique row for rows created by "new" keyword? I mean like this:

Product product = Product.builder()
            .eancode("EAN-1234")
            .externalId("123123")
            .producerPartNumber("123123")
            .name("VERY GOOD LAPTOP")
            .vendor(new Vendor("LENOVO", "www.lenovo.com"))
            .priceDetails(new PriceDetails(
                    new BigDecimal("19.99"),
                    new BigDecimal("20.00"),
                    new BigDecimal("21.00"),
                    Currency.PLN))
            .build();

I want Vendor entity to be unique because now I've got something like this (when I multiply run this code):

id name    url
1  LENOVO  lenovo.com
2  LENOVO  lenovo.com

I just want it to check it first if that name exist yet. Should I use @EmbeddedId in some way?

Edit: look now

@Override
    public Long save(Product item) {
        EntityManager em = getEntityManager();
        em.getTransaction().begin();
        
        //that line throws PersistentObjectException: detached entity passed to persis
        em.persist(item); //cascade is set as PERSIST so why isn't it work
        
        em.getTransaction().commit();
        em.close();
        return item.getId();
    }

Upvotes: 0

Views: 44

Answers (1)

Oleksii Valuiskyi
Oleksii Valuiskyi

Reputation: 2841

You need a VendorRepository contains a method like this Optional<Vendor> getVendorByNameAndUrl(String name, String url).

Then

VendorRepository vendorRepo;

@Transactional
public void saveProduct() {    
    Product product = Product.builder()
            .eancode("EAN-1234")
            .externalId("123123")
            .producerPartNumber("123123")
            .name("VERY GOOD LAPTOP")
            .vendor(findVendorOrCreateNew("LENOVO", "www.lenovo.com"))
            .priceDetails(new PriceDetails(
                    new BigDecimal("19.99"),
                    new BigDecimal("20.00"),
                    new BigDecimal("21.00"),
                    Currency.PLN))
            .build();

     // ...
}

Vendor findVendorOrCreateNew(String name, String url) {
    return vendorRepo.getVendorByNameAndUrl(name, url)
        .orElse(new Vendor(name, url));
}

Upvotes: 1

Related Questions