このチュートリアルでは、これまでの ”

Hibernate one-many relationship example – XML mapping

“チュートリアルのインフラストラクチャ全体を再利用し、サポートを強化しますHibernate/JPAアノテーション

プロジェクト構造

このチュートリアルの新しいプロジェクト構造を見直してください。


1対多の注釈フォルダ、title = "1対複数注釈関係フォルダ"、幅= 461、高さ= 429

1. “1対多”テーブルの関係

前の1対多のテーブル関係を再度参照してください。


1対多のテーブル関係、title = "1対多関係"、width = 554、height = 207

2. Hibernateモデルクラス

以前のモデルクラス

Stock.java`と

StockDailyRecord.java`を更新し、内部に注釈コードを定義します。


File:Stock.java

package com.mkyong.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 = "mkyongdb", 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 Set<StockDailyRecord> stockDailyRecords = new HashSet<StockDailyRecord>(
            0);

    public Stock() {
    }

    public Stock(String stockCode, String stockName) {
        this.stockCode = stockCode;
        this.stockName = stockName;
    }

    public Stock(String stockCode, String stockName,
            Set<StockDailyRecord> 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<StockDailyRecord> getStockDailyRecords() {
        return this.stockDailyRecords;
    }

    public void setStockDailyRecords(Set<StockDailyRecord> stockDailyRecords) {
        this.stockDailyRecords = stockDailyRecords;
    }

}


File:StockDailyRecord.java

package com.mkyong.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 = "mkyongdb",
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.ハイバネート設定ファイル


Stock.java`と

StockDailyRecord.java`の注釈付きクラスを `hibernate.cfg.xml`に次のように挿入します:


File:hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
    <property name="hibernate.connection.driver__class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyongdb</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show__sql">true</property>
    <mapping class="com.mkyong.stock.Stock"/>
    <mapping class="com.mkyong.stock.StockDailyRecord"/>
</session-factory>
</hibernate-configuration>

4.それを実行する

これを実行すると、HibernateはSTOCKテーブルに行を挿入し、STOCK

DAILY

RECORDテーブルに行を挿入します。

ファイル:App.java

package com.mkyong;

import java.util.Date;

import org.hibernate.Session;

import com.mkyong.stock.Stock;
import com.mkyong.stock.StockDailyRecord;
import com.mkyong.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");
    }
}


出力

Hibernate one to many (Annotation)
Hibernate:
    insert
    into
        mkyongdb.stock
        (STOCK__CODE, STOCK__NAME)
    values
        (?, ?)
Hibernate:
    insert
    into
        mkyongdb.stock__daily__record
        (DATE, PRICE__CHANGE, PRICE__CLOSE, PRICE__OPEN, STOCK__ID, VOLUME)
    values
        (?, ?, ?, ?, ?, ?)
Done

ダウンロードする –

Hibernate-one-to-many-annotation.zip

(9KB)