com/wpollock/jpademo/Main.java
/* Simple Java SE JPA demo, using EclipseLink and embedded JavaDB
*
* @author Wayne Pollock, Tampa Florida USA
*/
package com.wpollock.jpademo;
import jakarta.persistence.*; // The JPA classes
import java.util.List;
public class Main {
public static void main ( String [] args ) {
// With Java EE, you get an Entity Manager reference a different way.
// Here, "MyDB" is the name of a JPA "persistence unit" (or PU),
// defined in the file META-INF/persistence.xml. That file maps this
// PU to a database, and includes all necessary connection information.
// Note that file can be changed without recompiling your Java code.
// In this case, the PU refers to an embedded JavaDB database, which
// is automatically created if it doesn't exist. Additionally, when
// connecting, all existing tables are dropped and recreated. This
// makes it easy to run the demo over and over.
EntityManagerFactory emf =
Persistence.createEntityManagerFactory( "MyDB" );
EntityManager em = emf.createEntityManager();
// Create a new Book entity:
Book b = new Book();
b.setTitle( "Underwater Basket-Weaving for Dummies" );
b.setDescription( "Learn to weave reed baskets "
+ "while holding your breath!" );
b.setIsbn( "0-123-45678-9" );
b.setPrice( 29.95F ); // In U.S. Dollars
b.setAuthor( "Piffl, Hymie" );
// Now add it to the database:
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist( b );
tx.commit();
// Add another book:
b = new Book();
b.setTitle( "Brain Surgery: Self-Taught" );
b.setDescription( "Become a brain surgeon in your spare time!" );
b.setIsbn( "0-987-65432-1" );
b.setPrice( 29.95F ); // In U.S. Dollars
b.setAuthor( "Piffl, Hymie" ); // Best-selling author!
// Now add it to the database:
tx = em.getTransaction();
tx.begin();
em.persist( b );
tx.commit();
// Sample JPA query: fetch all Books in the database:
Query getAllBooks = em.createQuery("SELECT b FROM Book b");
@SuppressWarnings("unchecked")
List<Book> books = getAllBooks.getResultList();
// Do something with the results:
System.out.println( "Titles of books in our collection:" );
for (Book book : books) {
System.out.println( "ID: " + book.getId()
+ ", Title: " + book.getTitle() );
}
System.out.println( "\nNumber of books: " + books.size() );
// Close the database connection:
em.close();
emf.close();
}
}