4
How do I insert the Product object into the database that is composed of an Ingredient object that already exists in the database, without duplicating the Ingredient object in the database. If I remove Scade and place the ID (Primary key auto increment) of the object in the Ingredient, it is an error. Wouldn’t the correct Hibernate not save the object? Does at the time of insertion it belittles the ID for being auto increment?
Error:
Exception in thread "main" org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation : entity.ProdutoIngrediente.ingrediente -> entity.Ingrediente
Classes:
@Entity
@Table(name = "produto_ingrediente")
public class ProdutoIngrediente implements java.io.Serializable {
......
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_ingrediente", nullable = false)
public Ingrediente getIngrediente() {
return this.ingrediente;
}
public void setIngrediente(Ingrediente ingrediente) {
this.ingrediente = ingrediente;
}
}
@Entity
@Table(name = "produto", catalog = "grupotenkite2")
public class Produto implements java.io.Serializable {
...
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id_produto", unique = true, nullable = false)
public Integer getIdProduto() {
return this.idProduto;
}
}
Project error. If there is an attribute that cannot be duplicated it should be the key and not create an auto-increment.
– user4552
Post the ids of your entities, the modeling of relationships as well as your data scheme. From what I understood the table
produto_ingrediente
is a Many-to-Many relationship table (probably with extra attributes, which justifies the decision to have a separate entity).– Anthony Accioly
If this is the case, model the entity with a composite key and relationships using
@PrimaryKeyJoinColumn
s (and reflect this in the bank by creating a Composite PK, which avoids duplicated ingredients for the same product). You can persist the entity without problems. Example - In English. Think about theaddEmployee(Employee employee, boolean teamLead)
such as, for exampleadicionarIngrediente(Ingrediente ingrediente, BigDecimal quantidade)
;– Anthony Accioly
@Anthonyaccioly take a look at the entity and relationship diagram I put together, please. What you recommend me. the intention is to let a product have one more ingredient.. In my program, I first insert all the ingredients of the system and then add the product and make the connection through the 'product' table'
– diegosoaresub