Hibernate - Exemple un-à-plusieurs (annotation)
Dans ce didacticiel, il réutilisera toute l'infrastructure du précédent "http://www.example.com/hibernate/hibernate-one-to-many-relationship-example/[Hibernate un à plusieurs exemple de relation - mappage XML]" tutoriel, améliorez-le pour prendre en charge l'annotation Hibernate / JPA.
Structure du projet
Passez en revue la nouvelle structure de projet de ce didacticiel.
Note
Depuis Hibernate 3.6, les codes d'annotation sont fusionnés dans le module principal d'Hibernate, ainsi, le fichierprevious pom.xml peut être réutilisé.
1. Relation de table «un à plusieurs»
Voir à nouveau la relation précédente à plusieurs tables.
2. Classe de modèle Hibernate
Mettez à jour les classes de modèle précédentes -Stock.java
etStockDailyRecord.java
, et définissez le code d'annotation à l'intérieur.
Fichier: Stock.java
package com.example.stock; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; @Entity @Table(name = "stock", catalog = "exampledb", uniqueConstraints = { @UniqueConstraint(columnNames = "STOCK_NAME"), @UniqueConstraint(columnNames = "STOCK_CODE") }) public class Stock implements java.io.Serializable { private Integer stockId; private String stockCode; private String stockName; private SetstockDailyRecords = new HashSet ( 0); public Stock() { } public Stock(String stockCode, String stockName) { this.stockCode = stockCode; this.stockName = stockName; } public Stock(String stockCode, String stockName, Set stockDailyRecords) { this.stockCode = stockCode; this.stockName = stockName; this.stockDailyRecords = stockDailyRecords; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "STOCK_ID", unique = true, nullable = false) public Integer getStockId() { return this.stockId; } public void setStockId(Integer stockId) { this.stockId = stockId; } @Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10) public String getStockCode() { return this.stockCode; } public void setStockCode(String stockCode) { this.stockCode = stockCode; } @Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20) public String getStockName() { return this.stockName; } public void setStockName(String stockName) { this.stockName = stockName; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "stock") public Set getStockDailyRecords() { return this.stockDailyRecords; } public void setStockDailyRecords(Set stockDailyRecords) { this.stockDailyRecords = stockDailyRecords; } }
Fichier: StockDailyRecord.java
package com.example.stock; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.UniqueConstraint; @Entity @Table(name = "stock_daily_record", catalog = "exampledb", uniqueConstraints = @UniqueConstraint(columnNames = "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; public StockDailyRecord() { } public StockDailyRecord(Stock stock, Date date) { this.stock = stock; this.date = date; } public StockDailyRecord(Stock stock, Float priceOpen, Float priceClose, Float priceChange, Long volume, Date date) { this.stock = stock; this.priceOpen = priceOpen; this.priceClose = priceClose; this.priceChange = priceChange; this.volume = volume; this.date = date; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "RECORD_ID", unique = true, nullable = false) public Integer getRecordId() { return this.recordId; } public void setRecordId(Integer recordId) { this.recordId = recordId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "STOCK_ID", nullable = false) public Stock getStock() { return this.stock; } public void setStock(Stock stock) { this.stock = stock; } @Column(name = "PRICE_OPEN", precision = 6) public Float getPriceOpen() { return this.priceOpen; } public void setPriceOpen(Float priceOpen) { this.priceOpen = priceOpen; } @Column(name = "PRICE_CLOSE", precision = 6) public Float getPriceClose() { return this.priceClose; } public void setPriceClose(Float priceClose) { this.priceClose = priceClose; } @Column(name = "PRICE_CHANGE", precision = 6) public Float getPriceChange() { return this.priceChange; } public void setPriceChange(Float priceChange) { this.priceChange = priceChange; } @Column(name = "VOLUME") public Long getVolume() { return this.volume; } public void setVolume(Long volume) { this.volume = volume; } @Temporal(TemporalType.DATE) @Column(name = "DATE", unique = true, nullable = false, length = 10) public Date getDate() { return this.date; } public void setDate(Date date) { this.date = date; } }
3. Hibernate Configuration File
Place les classes annotéesStock.java
etStockDailyRecord.java
danshibernate.cfg.xml
comme ceci:
Fichier: hibernate.cfg.xml
com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/exampledb root password org.hibernate.dialect.MySQLDialect true
4. 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 (Annotation)"); 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"); } }
Sortie
Hibernate one to many (Annotation) Hibernate: insert into exampledb.stock (STOCK_CODE, STOCK_NAME) values (?, ?) Hibernate: insert into exampledb.stock_daily_record (DATE, PRICE_CHANGE, PRICE_CLOSE, PRICE_OPEN, STOCK_ID, VOLUME) values (?, ?, ?, ?, ?, ?) Done
Téléchargez-le -Hibernate-one-to-many-annotation.zip (9 Ko)