Hibernate - Exemple un-à-plusieurs (mappage XML)
Une relation un-à-plusieurs se produit lorsqu'une entité est liée à plusieurs occurrences dans une autre entité.
Dans ce didacticiel, nous vous montrons comment travailler avec une relation de table un-à-plusieurs dans Hibernate, via un fichier de mappage XML (hbm).
Outils et technologies utilisés dans ces didacticiels:
-
Hibernate 3.6.3.Final
-
MySQL 5.1.15
-
Maven 3.0.3
-
Eclipse 3.6
Structure du projet
Structure du projet de ce tutoriel.

Dépendance du projet
Récupérezhibernate.jar depuis le référentiel JBoss, Maven s'occupera de toutes les dépendances liées pour vous
Fichier: pom.xml
JBoss repository http://repository.jboss.org/nexus/content/groups/public/ mysql mysql-connector-java 5.1.15 org.hibernate hibernate-core 3.6.3.Final javassist javassist 3.12.1.GA
1. Exemple «un à plusieurs»
Il s'agit d'une conception de table de relationsone-to-many, une table STOCK a de nombreuses occurrences table STOCK_DAILY_RECORD.

Voir les scripts de table MySQL
DROP TABLE IF EXISTS `stock`; CREATE TABLE `stock` ( `STOCK_ID` int(10) unsigned NOT NULL AUTO_INCREMENT, `STOCK_CODE` varchar(10) NOT NULL, `STOCK_NAME` varchar(20) NOT NULL, PRIMARY KEY (`STOCK_ID`) USING BTREE, UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`), UNIQUE KEY `UNI_STOCK_ID` (`STOCK_CODE`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `exampledb`.`stock_daily_record`; CREATE TABLE `exampledb`.`stock_daily_record` ( `RECORD_ID` int(10) unsigned NOT NULL AUTO_INCREMENT, `PRICE_OPEN` float(6,2) DEFAULT NULL, `PRICE_CLOSE` float(6,2) DEFAULT NULL, `PRICE_CHANGE` float(6,2) DEFAULT NULL, `VOLUME` bigint(20) unsigned DEFAULT NULL, `DATE` date NOT NULL, `STOCK_ID` int(10) unsigned NOT NULL, PRIMARY KEY (`RECORD_ID`) USING BTREE, UNIQUE KEY `UNI_STOCK_DAILY_DATE` (`DATE`), KEY `FK_STOCK_TRANSACTION_STOCK_ID` (`STOCK_ID`), CONSTRAINT `FK_STOCK_TRANSACTION_STOCK_ID` FOREIGN KEY (`STOCK_ID`) REFERENCES `stock` (`STOCK_ID`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8;
2. Classe de modèle Hibernate
Créez deux classes de modèle -Stock.java etStockDailyRecord.java, pour représenter les tables ci-dessus.
Fichier: Stock.java
package com.example.stock;
import java.util.HashSet;
import java.util.Set;
public class Stock implements java.io.Serializable {
private Integer stockId;
private String stockCode;
private String stockName;
private Set stockDailyRecords =
new HashSet(0);
//getter, setter and constructor
}
Fichier: StockDailyRecord.java
package com.example.stock;
import java.util.Date;
public class StockDailyRecord implements java.io.Serializable {
private Integer recordId;
private Stock stock;
private Float priceOpen;
private Float priceClose;
private Float priceChange;
private Long volume;
private Date date;
//getter, setter and constructor
}
3. Hibernate XML Mapping
Maintenant, créez deux fichiers de mappage Hibernate (hbm) -Stock.hbm.xml etStockDailyRecord.hbm.xml.
Fichier: Stock.hbm.xml
Fichier: StockDailyRecord.hbm.xml
4. Hibernate Configuration File
PlaceStock.hbm.xml etStockDailyRecord.hbm.xml dans votre fichier de configuration Hibernate, ainsi que les détails de connexion MySQL.
Fichier: hibernate.cfg.xml
com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/exampledb root password org.hibernate.dialect.MySQLDialect true true
5. Exécuter
Exécutez-le, Hibernate insérera une ligne dans la table STOCK et une ligne dans la table STOCK_DAILY_RECORD.
Fichier: App.java
package com.example;
import java.util.Date;
import org.hibernate.Session;
import com.example.stock.Stock;
import com.example.stock.StockDailyRecord;
import com.example.util.HibernateUtil;
public class App {
public static void main(String[] args) {
System.out.println("Hibernate one to many (XML Mapping)");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Stock stock = new Stock();
stock.setStockCode("7052");
stock.setStockName("PADINI");
session.save(stock);
StockDailyRecord stockDailyRecords = new StockDailyRecord();
stockDailyRecords.setPriceOpen(new Float("1.2"));
stockDailyRecords.setPriceClose(new Float("1.1"));
stockDailyRecords.setPriceChange(new Float("10.0"));
stockDailyRecords.setVolume(3000000L);
stockDailyRecords.setDate(new Date());
stockDailyRecords.setStock(stock);
stock.getStockDailyRecords().add(stockDailyRecords);
session.save(stockDailyRecords);
session.getTransaction().commit();
System.out.println("Done");
}
}
Production …
Hibernate one to many (XML Mapping)
Hibernate:
insert
into
exampledb.stock
(STOCK_CODE, STOCK_NAME)
values
(?, ?)
Hibernate:
insert
into
exampledb.stock_daily_record
(STOCK_ID, PRICE_OPEN, PRICE_CLOSE, PRICE_CHANGE, VOLUME, DATE)
values
(?, ?, ?, ?, ?, ?)
Hibernate Annotation
Pour l'annotation un-à-plusieurs dans Hibernate, veuillez vous référer à ceexample.
Téléchargez-le -Hibernate-one-to-many-xml-mapping.zip (10 Ko)