How to limit a 1 relationship to many JPA?

2
I'm using JPA with Spring Framework in a project, I'd like to limit a 1:n relationship, I want to 1:5 , how do I do this? >

The relationship is this:

@ManyToOne
private Task task;
    
asked by anonymous 26.10.2016 / 13:17

1 answer

1

Unfortunately, there is no way to do it this way. But since you use java, you can use object-orientation to encapsulate this logic within your entity. For example:

@Entity
public class Item {

    @ManyToOne
    private Produto produto;
}

@Entity
public class Produto {

    @OneToMany(mappedBy = "produto", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Item> itens = new LinkedList<>();

    public List<Item> getItens() {
        return Collections.unmodifiableList(itens);
    }

    public void addItem(Item item) {
        if (itens.size() == 5) {
            throw new IllegalStateException("Não é possível adicionar mais itens!");
        }
        itens.add(item);
    }

    public void removeItem(Item item) {
        itens.remove(item);
    }
}

In this case you would only have the repository for your product entity. The persistence of the Item entity is entirely the responsibility of the JPA, you just need to add the items in the product and save the same. For example:

...
produto.addItem(item);
produtoRepository.save(produto);
...

And likewise to remove the items.

...
produto.removeItem(item);
produtoRepository.save(produto);
...

Of course this way you have to treat the exception to show a more user-friendly message to your user.

    
27.10.2016 / 00:30