Main.java

Download Main.java

 1: /* Simple Java SE JPA demo, using EclipseLink and embedded JavaDB
 2:  *
 3:  * @author Wayne Pollock, Tampa Florida USA
 4:  */
 5: 
 6: package com.wpollock.jpademo;
 7: 
 8: import jakarta.persistence.*;  // The JPA classes
 9: import java.util.List;
10: 
11: public class Main {
12: 
13:    public static void main ( String [] args ) {
14:       // With Java EE, you get an Entity Manager reference a different way.
15:       // Here, "MyDB" is the name of a JPA "persistence unit" (or PU),
16:       // defined in the file META-INF/persistence.xml.  That file maps this
17:       // PU to a database, and includes all necessary connection information.
18:       // Note that file can be changed without recompiling your Java code.
19:       // In this case, the PU refers to an embedded JavaDB database, which
20:       // is automatically created if it doesn't exist.  Additionally, when
21:       // connecting, all existing tables are dropped and recreated.  This
22:       // makes it easy to run the demo over and over.
23:       EntityManagerFactory emf =
24:          Persistence.createEntityManagerFactory( "MyDB" );
25:       EntityManager em = emf.createEntityManager();
26: 
27:       // Create a new Book entity:
28:       Book b = new Book();
29:       b.setTitle( "Underwater Basket-Weaving for Dummies" );
30:       b.setDescription( "Learn to weave reed baskets "
31:          + "while holding your breath!" );
32:       b.setIsbn( "0-123-45678-9" );
33:       b.setPrice( 29.95F );  // In U.S. Dollars
34:       b.setAuthor( "Piffl, Hymie" );
35: 
36:       // Now add it to the database:
37:       EntityTransaction tx = em.getTransaction();
38:       tx.begin();
39:       em.persist( b );
40:       tx.commit();
41: 
42:       // Add another book:
43:       b = new Book();
44:             b.setTitle( "Brain Surgery: Self-Taught" );
45:       b.setDescription( "Become a brain surgeon in your spare time!" );
46:       b.setIsbn( "0-987-65432-1" );
47:       b.setPrice( 29.95F );  // In U.S. Dollars
48:       b.setAuthor( "Piffl, Hymie" );  // Best-selling author!
49: 
50:       // Now add it to the database:
51:       tx = em.getTransaction();
52:       tx.begin();
53:       em.persist( b );
54:       tx.commit();
55: 
56:       // Sample JPA query: fetch all Books in the database:
57:       Query getAllBooks = em.createQuery("SELECT b FROM Book b");
58:       @SuppressWarnings("unchecked")
59:       List<Book> books = getAllBooks.getResultList();
60: 
61:       // Do something with the results:
62:       System.out.println( "Titles of books in our collection:" );
63:       for (Book book : books) {
64:          System.out.println( "ID: " + book.getId()
65:             + ", Title: " + book.getTitle() );
66:       }
67:       System.out.println( "\nNumber of books: " + books.size() );
68: 
69:       // Close the database connection:
70:       em.close();
71:       emf.close();
72:    }
73: }