Hibernate Ders 07 – @ManytoMany Association

Merhaba Arkadaslar,

Bu dersimizde , Book ve Author iliskisinden yola cikarak, many-to-many yani coktan-cok’a iliski ile ilgili basit bir ornek yapmaya caliscagiz.
Bır yazar dusunelim, bir cok kitabi olabilecegi gibi, bir kitap icin birden fazla yazar olabilir.Buradaki iliskimiz many to many ‘ dir.

Hemen yeni bir package acalim.. hibernate7_many2many_association.
ilk sinifimizi olusturalim… Book

public Class Author {
    private int bookid;
    private String title;
    private int pages;
    private Calendar publicationDate;

    // ....

    // Getters , Setters
}

getter/setter metotlarini olusturup , gerekli notasyonlari verelim.. @Entity, @Id ve    @GeneratedValue(strategy= GenerationType.AUTO) notasyonunu verdik. Burada dikkate ederseniz bir Calendar turunde degisken kullandik ve bizden bir notasyon bekliyor.
Olusturdugumuz

public Calendar getPublicationDate() {
    return publicationDate;
}

metodunun uzerine gelirsek, A temporal attribute must be marked with @Temporal annotaton uyarisi verdigini goruruz.
@Temporal(javax.persistence.TemporalType.DATE) notasyonu isimizi gorecektir.

Simdilik Book sinifimiz ile isimiz bitti, ikinci sinifimiz olan Author sinifimizi olusturalim…

    private int author_id;
    private String name;
    private String surname;

    // ....

    // Getters , Setters

Getter/Setter metotlarini olusturup, gerekli notasyonlarimizi yapiyoruz 🙂

Author sinifimizda yeni bir degisken tanimliyoruz;

 private Set<Book> books = new HashSet<>();

Generic Book turunde bir set(kume) tanimliyoruz.. Getter/Setter metodunu eklemeyi unutmayalim 🙂

    @ManyToMany
    public Set<Book> getBooks() {
        return books;
    }

Ayni islemi  Book sinifimiz icin uyguluyalim.

private Set<Author> authors = new HashSet<>();

Burada da Generic Author turunde bir set (kume) tanimliyoruz. Getter/Setter metodunu ekliyoruz.

    @ManyToMany
    public Set<Author> getAuthors() {
        return authors;
    }

Simdi sirada yaptiklarimizi test etmeye.. Bunun icin daha once yaptigimiz test siniflarimizdan birini alip kopyaliyorum, tabi refactor ile adini degistiriyorum BookAuthorTest yapiyoruz.. Temel sablonumuz ayni oldugu icin, bastan yazmamiza gerek yok..

    config.addAnnotatedClass(Author.class);
    config.addAnnotatedClass(Book.class);

kisminda ,tabi bir onceki ornekten kalma siniflar degil hali hazirda kullanacagimiz Author.class ve Book.class isimlerini vermeyi unutmayalim 🙂

    session.beginTransaction();
    session.getTransaction().commit();

arasini temizledikten sonra test sinifimiz hazir.

BookAuthorTest.java

package hibernate7_many2many_association;

import java.util.Calendar;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

/**
 *
 * @author Levent
 */
public class BookAuthorTest {

    public static void main(String[] args) {

        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Author.class);
        config.addAnnotatedClass(Book.class);
        config.configure("hibernate.cfg.xml");

        new SchemaExport(config).create(true, true);

        SessionFactory factory = config.buildSessionFactory();
        Session session = factory.getCurrentSession();
        session.beginTransaction();

        Calendar publicationDate = Calendar.getInstance();
        Calendar publicationDate2 = Calendar.getInstance();
        Calendar publicationDate3 = Calendar.getInstance();

        publicationDate.set(1990, Calendar.JANUARY, 1);
        Book book1 = new Book();
        book1.setPages(500);
        book1.setTitle("BookTitle1");
        book1.setPublicationDate(publicationDate);

        publicationDate2.set(2000, Calendar.NOVEMBER, 10);
        Book book2 = new Book();
        book2.setPages(1000);
        book2.setTitle("BookTitle2");
        book2.setPublicationDate(publicationDate2);

        publicationDate3.set(2011, Calendar.NOVEMBER, 1);
        Book book3 = new Book();
        book3.setPages(800);
        book3.setTitle("BookTitle3");
        book3.setPublicationDate(publicationDate3);

        Author author1 = new Author();
        author1.setName("Author1");
        author1.setSurname("Surname1");

        Author author2 = new Author();
        author2.setName("Author2");
        author2.setSurname("Surname2");

        book1.getAuthors().add(author1);
        book2.getAuthors().add(author2);
        book3.getAuthors().add(author1);
        book3.getAuthors().add(author2);

        session.save(book1);
        session.save(book2);
        session.save(book3);

        session.save(author1);
        session.save(author2);

        session.getTransaction().commit();

    }
}

Book.java

package hibernate7_many2many_association;

import java.io.Serializable;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Temporal;

/**
 *
 * @author Levent
 */
@Entity
public class Book implements Serializable {

    private int bookid;
    private String title;
    private int pages;
    private Calendar publicationDate;
    private Set authors = new HashSet();

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getBookid() {
        return bookid;
    }

    public void setBookid(int bookid) {
        this.bookid = bookid;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    @Temporal(javax.persistence.TemporalType.DATE)
    public Calendar getPublicationDate() {
        return publicationDate;
    }

    public void setPublicationDate(Calendar publicationDate) {
        this.publicationDate = publicationDate;
    }

    @ManyToMany
    @JoinTable(name = "Book_Author_Table",
    joinColumns = {
        @JoinColumn(name = "bookid")},
    inverseJoinColumns = {
        @JoinColumn(name = "author_id")})
    public Set getAuthors() {
        return authors;
    }

    public void setAuthors(Set authors) {
        this.authors = authors;
    }
}

Author.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernate7_many2many_association;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;

/**
 *
 * @author Levent
 */
@Entity
public class Author implements Serializable {

    private int author_id;
    private String name;
    private String surname;
    private Set books = new HashSet();

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getAuthor_id() {
        return author_id;
    }

    public void setAuthor_id(int author_id) {
        this.author_id = author_id;
    }

    public String getName() {
        return name;
    }

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

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    @ManyToMany
    @JoinTable(name = "Book_Author_Table",
    joinColumns = {
        @JoinColumn(name = "author_id")},
    inverseJoinColumns = {
        @JoinColumn(name = "bookid")})
    public Set getBooks() {
        return books;
    }

    public void setBooks(Set books) {
        this.books = books;
    }
}

Iki sinifimizda da , JoinTable notasyonunu kullandik, ve ortak bir isim verdik. Book_Author_Table.

Test edip sonuclari gorelim 🙂

author tablomuz

book tablomuz

birlestirdigimiz book_author_table  tablomuz.

Bu ornegimizde book1=1 book2=2 book3=3  ve author1=4 author1=5 numarali id olarak otomatik olustu.

book1.getAuthors().add(author1); 1----->4
book2.getAuthors().add(author2); 2----->5
book3.getAuthors().add(author1); 3----->4
book3.getAuthors().add(author2); 3----->5

Gordugunuz gibi book3 un 2 tane yazari var, ve author1 in yazari oldugu 2 kitap var.(manytomany)

Kaynak kodlar:HibernateTutorial_v7

Herkese Bol Javali Gunler dilerim.
Be an oracle man , import java.*;
Levent Erguder
injavawetrust

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published.