I am developing a system in layers (packages), to exercise the concepts of class and I came across a doubt I would like to create a product class, it 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 class content would have to persist all related classes in the Supplier and category case besides 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;
}
Oops: 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 is the category of that my object will receive as a 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);
}
In the meantime there is an error in which I can not persist a list, but then how can I represent a product that has several suppliers
List 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) at sistemavendas.rn.RN.ProductoRN.insert (ProductoRN.java:20) at system sales.Product.Test.main (TestProduct.java:22) Thank you for your attention