How to limit a relationship 1 to many JPA?

Asked

Viewed 288 times

2

I’m using JPA with Spring Framework on a project, I would like to limit a relationship 1:n, want to do 1:5, how do I do that?

This is the relationship:

@ManyToOne
private Task task;

1 answer

1


Unfortunately, you can’t do it that way. But as 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 that case you would only have the Repository for your product entity. The persistence of the Item entity is all in charge of JPA, you just need to add the items in the product and save it. For example:

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

And in the same way to remove the items.

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.