Hibernate - Many-to-Many-Beispiel (Anmerkung)

Ruhezustand - Viele-zu-Viele-Beispiel (Anmerkung)

In diesem Lernprogramm wird die gesamte Infrastruktur des vorherigen Lernprogramms "http://www.example.com/hibernate/hibernate-many-to-many-relationship-example/[Hibernate many to many example - XML ​​Mapping]" wiederverwendet , erweitern Sie es, um die Hibernare / JPA-Annotation zu unterstützen.

Note
Für viele bis viele mit zusätzlichen Spalten in der Verknüpfungstabelle lesen Sie bitte diesetutorial.

Projektstruktur

Überprüfen Sie die neue Projektstruktur dieses Lernprogramms.

many to many project folder

1. "Many-to-many" -Tabellenbeziehung

Siehe die vorherige Beziehung zwischen vielen und vielen Tabellen erneut.

many to many ER diagram

2. Hibernate Model Class

Aktualisieren Sie frühere Modellklassen -Stock.java undCategory.java und definieren Sie darin neuen Anmerkungscode.

Datei: 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.CascadeType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
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 Set categories = new HashSet(0);

    public Stock() {
    }

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

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

    @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;
    }

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "stock_category", catalog = "exampledb", joinColumns = {
            @JoinColumn(name = "STOCK_ID", nullable = false, updatable = false) },
            inverseJoinColumns = { @JoinColumn(name = "CATEGORY_ID",
                    nullable = false, updatable = false) })
    public Set getCategories() {
        return this.categories;
    }

    public void setCategories(Set categories) {
        this.categories = categories;
    }

}

Datei: Category.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.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name = "category", catalog = "exampledb")
public class Category implements java.io.Serializable {

    private Integer categoryId;
    private String name;
    private String desc;
    private Set stocks = new HashSet(0);

    public Category() {
    }

    public Category(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public Category(String name, String desc, Set stocks) {
        this.name = name;
        this.desc = desc;
        this.stocks = stocks;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "CATEGORY_ID", unique = true, nullable = false)
    public Integer getCategoryId() {
        return this.categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }

    @Column(name = "NAME", nullable = false, length = 10)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = "[DESC]", nullable = false)
    public String getDesc() {
        return this.desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "categories")
    public Set getStocks() {
        return this.stocks;
    }

    public void setStocks(Set stocks) {
        this.stocks = stocks;
    }

}

3. Ruhezustand-Konfigurationsdatei

Setzt kommentierte KlassenStock.java undCategory.java inhibernate.cfg.xml wie folgt ein:

Datei: hibernate.cfg.xml






    com.mysql.jdbc.Driver
    jdbc:mysql://localhost:3306/exampledb
    root
    password
    org.hibernate.dialect.MySQLDialect
    true
    
    

4. Starte es

Führen Sie es aus, das Ergebnis ist selbsterklärend.

Datei: App.java

package com.example;

import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import com.example.stock.Category;
import com.example.stock.Stock;
import com.example.util.HibernateUtil;

public class App {
    public static void main(String[] args) {

        System.out.println("Hibernate many to many (Annotation)");
    Session session = HibernateUtil.getSessionFactory().openSession();

    session.beginTransaction();

    Stock stock = new Stock();
        stock.setStockCode("7052");
        stock.setStockName("PADINI");

        Category category1 = new Category("CONSUMER", "CONSUMER COMPANY");
        Category category2 = new Category("INVESTMENT", "INVESTMENT COMPANY");

        Set categories = new HashSet();
        categories.add(category1);
        categories.add(category2);

        stock.setCategories(categories);

        session.save(stock);

    session.getTransaction().commit();
    System.out.println("Done");
    }
}

Ausgabe

Hibernate many to many (Annotation)
Hibernate:
    insert
    into
        exampledb.stock
        (STOCK_CODE, STOCK_NAME)
    values
        (?, ?)
Hibernate:
    insert
    into
        exampledb.category
        (`DESC`, NAME)
    values
        (?, ?)
Hibernate:
    insert
    into
        exampledb.category
        (`DESC`, NAME)
    values
        (?, ?)
Hibernate:
    insert
    into
        exampledb.stock_category
        (STOCK_ID, CATEGORY_ID)
    values
        (?, ?)
Hibernate:
    insert
    into
        exampledb.stock_category
        (STOCK_ID, CATEGORY_ID)
    values
        (?, ?)
Done

Laden Sie es herunter -Hibernate-many-to-many-annotation.zip (9KB)