Hibernate - Exemple Plusieurs-à-Plusieurs (Annotation)

Hibernate - Exemple plusieurs-à-plusieurs (annotation)

Dans ce tutoriel, il réutilisera toute l'infrastructure du précédent tutoriel «http://www.example.com/hibernate/hibernate-many-to-many-relationship-example/[Hibernate many to many - XML ​​mapping]». , améliorez-le pour prendre en charge l'annotation Hibernare / JPA.

Note
Pour plusieurs à plusieurs avec des colonnes supplémentaires dans la table de jointure, veuillez vous référer à cetutorial.

Structure du projet

Passez en revue la nouvelle structure de projet de ce didacticiel.

many to many project folder

1. Relation de table «plusieurs à plusieurs»

Voir à nouveau la relation plusieurs à plusieurs précédente.

many to many ER diagram

2. Classe de modèle Hibernate

Mettez à jour les classes de modèle précédentes -Stock.java etCategory.java, et définissez un nouveau 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.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;
    }

}

Fichier: 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. Hibernate Configuration File

Place les classes annotéesStock.java etCategory.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, le résultat est explicite.

Fichier: 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");
    }
}

Sortie

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

Téléchargez-le -Hibernate-many-to-many-annotation.zip (9 Ko)