Sponsered Links
Categories
Sponsered Links

JPA Hello World Example

 

This is a simple Hello World Example of standalone java application using Java Persistence API (JPA). The Application consists of an entity class, a main class and you need to create a persistence.xml file in the META-INF folder.

Entity class

package com.prg;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Greeting implements Serializable {
@Id @GeneratedValue private int id;
@Basic private String message;
@Basic private String language;

public Greeting() {}
public Greeting(String message, String language) {
this.message = message;
this.language = language;
}

public String toString() {
return "Greeting id=" + id + ", message=" + message + ", language=" + language;
}
}


Main class

package com.prg;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class HelloWorld {
private EntityManagerFactory emf;
private EntityManager em;
private String PERSISTENCE_UNIT_NAME = "hello-world";

public static void main(String[] args) {
HelloWorld hello = new HelloWorld();
hello.initEntityManager();
hello.create();
hello.read();
hello.closeEntityManager();
}

private void initEntityManager() {
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = emf.createEntityManager();
}

private void closeEntityManager() {
em.close();
emf.close();
}

private void create() {
em.getTransaction().begin();
Greeting g_en = new Greeting("hello world", "en");
Greeting g_es = new Greeting("hola, mundo", "es");
Greeting[] greetings = new Greeting[]{g_en, g_es};
for(Greeting g : greetings) {
em.persist(g);
}
em.getTransaction().commit();
}

private void read() {
Greeting g = (Greeting) em.createQuery(
"select greetingg where g.language = :language")
.setParameter("language", "en").getSingleResult();
System.out.println("Query returned: " + g);
}
}

 
 
Sponsered Links
Latest Updates
 
All Content of this site is for learning only. We do not warrant the correctness of its content. The risk from using it lies entirely with the user. While using this site, you agree to have read and accepted our terms of use and privacy policy.
Copyright © 2009 JSPSERVLETTUTORIAL.INFO All Right Reserved