0
I am developing a layered system(packages),to exercise the concepts of class and came across a question I would like to create a product class,the same has attributes that are references of other classes :
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private float preco;
private String nome;
private int qtd;
@ManyToMany
private List<Fornecedor> fornecedor;
@ManyToOne
private Categoria categoria;
In my layer where it is similar to DAO following the content of the class would have to persist all related classes in the case Supplier and category beyond the product class that is the one we want to create.
public Produto inserir(Produto produto,List<Fornecedor> listaFornecedores ,Categoria categoria) {
listaFornecedores=new ArrayList<>();
Conexao con = new Conexao();
EntityManager em = con.getEntidade();
em.getTransaction().begin();
em.persist(listaFornecedores);
em.persist(categoria);
em.persist(produto);
em.getTransaction().commit();
em.close();
return produto;
}
Ops : The parameters are to reference the objects that are already instantiated in order to highlight is that object (value) that I want to put in my product or the category of that my object I will receive as parameter and my product will have that category Test class :
public static void main(String[] args) {
Categoria cat = new Categoria("Viajem", "nao to afim de escrever hehe");
Fornecedor fornecedor = new Fornecedor( "Alimentos", 122354,"[email protected]" );
List<Fornecedor> listaFornecedores =new ArrayList<>();
listaFornecedores.add(fornecedor);
Produto produto = new Produto(50,"Talco",3 ,listaFornecedores,cat);
ProdutoRN produtoRN=new ProdutoRN();
produtoRN.inserir(produto, listaFornecedores, cat);
}
However there is an error in which I cannot persist a list,but then how can I represent a product that has several suppliers
List of suppliers ERROR
Exception in thread "main" java.lang.Illegalargumentexception: Unknown Entity: java.util.Arraylist at org.hibernate.Internal.SessionImpl.firePersist(Sessionimpl.java:786) at org.hibernate.Internal.SessionImpl.persist(Sessionimpl.java:767) sistemavendas.rn.Produtorn.insert(Produtorn.java:20) sistemavendas.TesteProduto.main(Testeproduto.java:22) Thanks for your attention
If the answer below solved your problem and there was no doubt left, mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.
– Victor Stafusa