EJB - Relations d'entité

EJB 3.0 offre la possibilité de définir des relations / mappages d'entités de base de données comme des relations un-à-un, un-à-plusieurs, plusieurs-à-un et plusieurs-à-plusieurs.

Voici les annotations pertinentes -

  • One-to-One- Les objets ont une relation un à un. Par exemple, un passager peut voyager en utilisant un seul billet à la fois.

  • One-to-Many- Les objets ont une relation un-à-plusieurs. Par exemple, un père peut avoir plusieurs enfants.

  • Many-to-One- Les objets ont une relation plusieurs-à-un. Par exemple, plusieurs enfants ayant une mère célibataire.

  • Many-to-Many- Les objets ont une relation plusieurs-à-plusieurs. Par exemple, un livre peut avoir plusieurs auteurs et un auteur peut écrire plusieurs livres.

Nous allons démontrer l'utilisation de la cartographie ManyToMany ici. Pour représenter la relation ManyToMany, trois tableaux suivants sont requis -

  • Book - Table de livre, ayant des registres de livres.

  • Author - Table d'auteur, ayant les enregistrements de l'auteur.

  • Book_Author - Table des auteurs de livres, ayant un lien avec la table des livres et des auteurs susmentionnée.

Créer des tableaux

Créer une table book author, book_author dans la base de données par défaut postgres.

CREATE TABLE book (
   book_id     integer,   
   name   varchar(50)      
);

CREATE TABLE author (
   author_id   integer,
   name   varchar(50)      
);

CREATE TABLE book_author (
   book_id     integer,
   author_id   integer 
);

Créer des classes d'entités

@Entity
@Table(name="author")
public class Author implements Serializable{
   private int id;
   private String name;
   ...   
}

@Entity
@Table(name="book")
public class Book implements Serializable{
   private int id;
   private String title;
   private Set<Author> authors;
   ...   
}

Utilisez l'annotation ManyToMany dans Book Entity.

@Entity
public class Book implements Serializable{
   ...
   @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}
      , fetch = FetchType.EAGER)
   @JoinTable(table = @Table(name = "book_author"),
      joinColumns = {@JoinColumn(name = "book_id")},
      inverseJoinColumns = {@JoinColumn(name = "author_id")})
   public Set<Author> getAuthors() {
      return authors;
   }
   ...
}

Exemple d'application

Créons une application EJB de test pour tester les objets de relations d'entité dans EJB 3.0.

Étape La description
1

Créez un projet avec un nom EjbComponent sous un package com.tutorialspoint.entity comme expliqué dans le chapitre EJB - Créer une application . Veuillez utiliser le projet créé dans le chapitre EJB - Persistance en tant que tel pour ce chapitre afin de comprendre les objets incorporés dans les concepts d'EJB.

2

Créez Author.java sous le package com.tutorialspoint.entity comme expliqué dans le chapitre EJB - Créer une application . Gardez le reste des fichiers inchangé.

3

Créez Book.java sous le package com.tutorialspoint.entity . Utilisez EJB - Chapitre Persistence comme référence. Gardez le reste des fichiers inchangé.

4

Nettoyez et créez l'application pour vous assurer que la logique métier fonctionne conformément aux exigences.

5

Enfin, déployez l'application sous forme de fichier jar sur JBoss Application Server. Le serveur d'applications JBoss démarrera automatiquement s'il n'est pas encore démarré.

6

Créez maintenant le client EJB, une application basée sur la console de la même manière que celle expliquée dans le chapitre EJB - Créer une application sous la rubriqueCreate Client to access EJB.

EJBComponent (module EJB)

Auteur.java

package com.tutorialspoint.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="author")
public class Author implements Serializable{
    
   private int id;
   private String name;

   public Author() {}

   public Author(int id, String name) {
      this.id = id;
      this.name = name;
   }
   
   @Id  
   @GeneratedValue(strategy= GenerationType.IDENTITY)
   @Column(name="author_id")
   public int getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

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

   public String toString() {
      return id + "," + name;
   }    
}

Book.java

package com.tutorialspoint.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

@Entity
@Table(name="book")
public class Book implements Serializable{

   private int id;
   private String name;
   private Set<Author> authors;

   public Book() {        
   }

   @Id  
   @GeneratedValue(strategy= GenerationType.IDENTITY)
   @Column(name="book_id")
   public int getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

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

   public void setAuthors(Set<Author> authors) {
      this.authors = authors;
   }    
   
   @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}
      , fetch = FetchType.EAGER)
   @JoinTable(table = @Table(name = "book_author"),
      joinColumns = {@JoinColumn(name = "book_id")},
      inverseJoinColumns = {@JoinColumn(name = "author_id")})
   public Set<Author> getAuthors() {
      return authors;
   }
}

LibraryPersistentBeanRemote.java

package com.tutorialspoint.stateless;

import com.tutorialspoint.entity.Book;
import java.util.List;
import javax.ejb.Remote;

@Remote
public interface LibraryPersistentBeanRemote {

   void addBook(Book bookName);

   List<Book> getBooks();
    
}

LibraryPersistentBean.java

package com.tutorialspoint.stateless;

import com.tutorialspoint.entity.Book;
import java.util.List;
import javax.ejb.Stateless;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class LibraryPersistentBean implements LibraryPersistentBeanRemote {
    
   public LibraryPersistentBean() {
   }

   @PersistenceContext(unitName="EjbComponentPU")
   private EntityManager entityManager;         

   public void addBook(Book book) {
      entityManager.persist(book);
   }    

   public List<Book> getBooks() {
      return entityManager.createQuery("From Book").getResultList();
   }
}
  • Dès que vous déployez le projet EjbComponent sur JBOSS, notez le journal jboss.

  • JBoss a créé automatiquement une entrée JNDI pour notre bean session - LibraryPersistentBean/remote.

  • Nous utiliserons cette chaîne de recherche pour obtenir un objet métier distant de type - com.tutorialspoint.interceptor.LibraryPersistentBeanRemote

Sortie du journal du serveur d'applications JBoss

...
16:30:01,401 INFO  [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
   LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface
   LibraryPersistentBean/remote-com.tutorialspoint.interceptor.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface
16:30:02,723 INFO  [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryPersistentBean,service=EJB3
16:30:02,723 INFO  [EJBContainer] STARTED EJB: com.tutorialspoint.interceptor.LibraryPersistentBeanRemote ejbName: LibraryPersistentBean
16:30:02,731 INFO  [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:

   LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface
   LibraryPersistentBean/remote-com.tutorialspoint.interceptor.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface
...

EJBTester (client EJB)

jndi.properties

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost
  • Ces propriétés sont utilisées pour initialiser l'objet InitialContext du service de nommage java.

  • L'objet InitialContext sera utilisé pour rechercher un bean session sans état.

EJBTester.java

package com.tutorialspoint.test;
   
import com.tutorialspoint.stateful.LibraryBeanRemote;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import java.util.*;

import javax.naming.InitialContext;
import javax.naming.NamingException;

public class EJBTester {

   BufferedReader brConsoleReader = null; 
   Properties props;
   InitialContext ctx;
   {
      props = new Properties();
      try {
         props.load(new FileInputStream("jndi.properties"));
      } catch (IOException ex) {
         ex.printStackTrace();
      }
      try {
         ctx = new InitialContext(props);            
      } catch (NamingException ex) {
         ex.printStackTrace();
      }
      brConsoleReader = 
      new BufferedReader(new InputStreamReader(System.in));
   }
   
   public static void main(String[] args) {

      EJBTester ejbTester = new EJBTester();

      ejbTester.testEmbeddedObjects();
   }
   
   private void showGUI() {
      System.out.println("**********************");
      System.out.println("Welcome to Book Store");
      System.out.println("**********************");
      System.out.print("Options \n1. Add Book\n2. Exit \nEnter Choice: ");
   }
   
   private void testEmbeddedObjects() {

      try {
         int choice = 1; 

         LibraryPersistentBeanRemote libraryBean = 
         (LibraryPersistentBeanRemote)
         ctx.lookup("LibraryPersistentBean/remote");

         while (choice != 2) {
            String bookName;
            String authorName;
            
            showGUI();
            String strChoice = brConsoleReader.readLine();
            choice = Integer.parseInt(strChoice);
            if (choice == 1) {
               System.out.print("Enter book name: ");
               bookName = brConsoleReader.readLine();
               System.out.print("Enter author name: ");
               authorName = brConsoleReader.readLine();               
               Book book = new Book();
               book.setName(bookName);
               Author author = new Author();
               author.setName(authorName);
               Set<Author> authors = new HashSet<Author>();
               authors.add(author);
               book.setAuthors(authors);

               libraryBean.addBook(book);          
            } else if (choice == 2) {
               break;
            }
         }

         List<Book> booksList = libraryBean.getBooks();

         System.out.println("Book(s) entered so far: " + booksList.size());
         int i = 0;
         for (Book book:booksList) {
            System.out.println((i+1)+". " + book.getName());
            System.out.print("Author: ");
            Author[] authors = (Author[])books.getAuthors().toArray();
            for(int j=0;j<authors.length;j++) {
               System.out.println(authors[j]);
            }
            i++;
         }           
      } catch (Exception e) {
         System.out.println(e.getMessage());
         e.printStackTrace();
      }finally {
         try {
            if(brConsoleReader !=null) {
               brConsoleReader.close();
            }
         } catch (IOException ex) {
            System.out.println(ex.getMessage());
         }
      }
   }
}

EJBTester effectue les tâches suivantes -

  • Chargez les propriétés de jndi.properties et initialisez l'objet InitialContext.

  • Dans la méthode testInterceptedEjb (), la recherche jndi est effectuée avec le nom - "LibraryPersistenceBean / remote" pour obtenir l'objet métier distant (EJB sans état).

  • Ensuite, l'utilisateur voit une interface utilisateur de magasin de bibliothèque et il / elle est invité à entrer un choix.

  • Si l'utilisateur entre 1, le système demande le nom du livre et enregistre le livre à l'aide de la méthode addBook () du bean session sans état. Session Bean stocke le livre dans la base de données.

  • Si l'utilisateur entre 2, le système récupère les livres à l'aide de la méthode getBooks () du bean session sans état et se ferme.

Exécuter le client pour accéder à EJB

Recherchez EJBTester.java dans l'explorateur de projet. Faites un clic droit sur la classe EJBTester et sélectionnezrun file.

Vérifiez la sortie suivante dans la console Netbeans.

run:
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 1
Enter book name: learn html5
Enter Author name: Robert
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 2
Book(s) entered so far: 1
1. learn html5
Author: Robert
BUILD SUCCESSFUL (total time: 21 seconds)