1:n
relationship, I want to 1:5
, how do I do this? >
The relationship is this:
@ManyToOne
private Task task;
1:n
relationship, I want to 1:5
, how do I do this? >
The relationship is this:
@ManyToOne
private Task task;
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.