Suppose I have Two objects: A pencil case and a pen in a pencil case can contain a large number of pens. Imagine a database with two tables: Code:
<?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns="http://www.hibernate.org/xsd/hibernate-mapping"> <class name="ru.modelsxml.Pinal" table="Pinal"> <id name="id" column="id"> <generator class="identity"/> </id> <property name="name" column="name"/> <bag name="ruchka" table="ruchka" inverse="true" cascade="all-delete-orphan"> <key column="name_ruchka" not-null="true"/> <one-to-many class="ru.modelsxml.Ruchka"/> </bag> </class> </hibernate-mapping> Код: <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns="http://www.hibernate.org/xsd/hibernate-mapping"> <class name="ru.modelsxml.Ruchka" table="ruchka"> <id name="id" column="id"> <generator class="identity"/> </id> <property name="name_ruchka" column="name_ruchka"/> <many-to-one name="pinal" column="pinal_id" class="ru.modelsxml.Pinal"/> </class> </hibernate-mapping>
and here I immediately create a pencil box object that contains several pens and through hibernate I try to add it to the database. As a result, 1 pencil case was added and pens were added, but in the pens table the pens do not have id cases to which they belong. question: what parameter do I need to specify so that the pens correctly enter id canisters with which they are added? or is it really possible to add cases in the database first, then get id cases to add these id to the model of pens and then add pens to the database?
import java.util.List; public class Pinal { private String name; private List<Ruchki> ruchkis; public List<Ruchki> getRuchkis() { return ruchkis; } public void setRuchkis(List<Ruchki> ruchkis) { this.ruchkis = ruchkis; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class Ruchki { private String name; private Pinal pinal; public String getName() { return name; } public void setName(String name) { this.name = name; } public Pinal getPinal() { return pinal; } public void setPinal(Pinal pinal) { this.pinal = pinal; } }
penal = new Penal(); ruchka = new Ruchka();
penal = new Penal(); ruchka = new Ruchka();
1)ruchka.setPenal(penal);
2)penal.getRuchkis().add(ruchka);
3)em.persist(penal);
those. it is necessary to establish connections in both directions (nn1 and 2) - Sergeybag
, thekey column
should haveruchka_name
, and notpinal_id
? - Sergey