Foreign keys on Insert with Struts2 / Hibernate
I'm new user of Struts 2 w/ hibernate. I have 2 tables : "Client" and "Coordonnees" (french word) In my table "Client", I have a FK named "coordonnees_id", that references field "id" from table "Coordonnees" I created an insert form like this :
File add.jsp
<s:form method="post" action="create">
<s:textfield cssClass="" label="Nom" name="client.nom" />
<s:textfield cssClass="" label="Prénom" name="client.prenom" />
....
<s:textfield cssClass="" label="Email" name="coordonnees.email" />
<s:textfield cssClass="" label="Adresse" name="coordonnees.adresse" />
<s:submit value="Insert" />
</s:form>
File ClientAction.java
private Client 开发者_Python百科client;
private ClientManager clientManager;
private Coordonnees coordonnees;
private CoordonneesManager coordonneesManager;
public String create() {
client = getClient();
coordonnees = getCoordonnees();
try {
clientManager.insert(client);
coordonneesManager.insert(coordonnees);
return SUCCESS;
} catch (Exception e) {
e.printStackTrace();
return ERROR;
}
}
File CoordonneesManager.java
public boolean insert(Coordonnees coordonnees) {
session = MyHibernateUtil.currentSession();
tx = session.beginTransaction();
try {
session.save(coordonnees);
log.info("Enregistrement de : " + getClass());
return true;
} catch (Exception e) {
log.error(e);
return false;
} finally {
tx.commit();
MyHibernateUtil.closeSession();
}
}
In my Client.hbm.xml file :
<many-to-one class="model.Coordonnees" fetch="select" name="coordonnees">
<column name="coordoonnees_id"/>
</many-to-one>
Here is my problem : When I submit my form, I would like to insert data into table Client (of course ...), into table "Coordonnees" (it works fine), and I would like to get the "id" I just created from table Coordonnees and insert it into my table Client (field "coordonnees_id" => my FK).
Is there an easy option in struts2 to do that ? Of course I can perform a select query on my last insert in table Coordonnees, get the id and update my table Client ... But it's not the point, I would like Struts to do this for me (if it's possible of course).
Thank you all for your help :)
I believe that persisting these two objects should happen in the same transaction. You should first persists the parent i.e. the coordonnees
then flash it to get the primary key and then set the relation in the child object. Afterwards persist the child.
精彩评论