Charlie's super short JPA example
I will try to expand on this later, but for now I do not have time and wanted to get something on this subject recorded, so here is an ultra short example of using JPA with JEE5 outside of a container.
I used the Oracle Toplink JPA Implementation - they also have some tutorials there, but like many others they get into too much other crap, building a web app, etc.
1. Setup a database and make sure you can access it with the correct perms over the network (I used MySQL and ConnectorJ).
I also used a simple "user" table for my testing, columns: id, name, fullName, password, email.
2. Setup a project in your IDE, use Java 5 and include the TopLink JPA jar and your JDBC driver as dependencies.
3. Create an entity to use with the example, in this case a User bean.
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class User implements Serializable {
@Id
private int id;
private String email;
private String fullname;
private String password;
private String name;
private static final long serialVersionUID = 1L;
public User() {
super();
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFullname() {
return this.fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
4. Borrow the standalone EntityManagerFactory setup code from the JPA tutorial to create JPAResourceBean in your own project.
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
* This is an Application Scoped bean that holds the JPA
* EntityManagerFactory. By making this bean Applciation scoped the
* EntityManagerFactory resource will be created only once for the application
* and cached here.
*
*@author Gordon Yorke
*/
public class JPAResourceBean {
protected EntityManagerFactory emf;
/*
* Lazily acquire the EntityManagerFactory and cache it.
*/
public EntityManagerFactory getEMF (){
if (emf == null){
emf = Persistence.createEntityManagerFactory("default", new java.util.HashMap());
}
return emf;
}
}
5. Setup your META-INF/persistence.xml resource with the correct properties for your database.
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0"> <persistence-unit name="default" transaction-type="RESOURCE_LOCAL"> <provider>oracle.toplink.essentials.PersistenceProvider</provider> <class>com.totsp.datatest.User</class> <properties> <property name="toplink.logging.level" value="FINEST"/> <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="toplink.jdbc.url" value="jdbc:mysql://192.168.0.10:3306/totsp"/> <property name="toplink.jdbc.user" value="totsp"/> <property name="toplink.jdbc.password" value="password"/> </properties> </persistence-unit> </persistence></pre>
6. Create a testing class that will persist the entity and run it.
import javax.persistence.EntityManagerFactory;
import oracle.toplink.essentials.ejb.cmp3.EntityManager;
public class Driver
{
public static void main(String[] args)
{
EntityManagerFactory emf = new JPAResourceBean().getEMF();
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
User user = new User();
user.setEmail("email");
user.setFullname("fullname");
user.setPassword("password");
user.setName("name");
entityManager.persist(user);
entityManager.getTransaction().commit();
}
}
7. Voila! Look at the database, it should have a user in it. (And keep in mind this is supposed to be a super-short learning example, from here you need to read more about JPA in order to learn how to use it in a production environment - this example is not production-worthy.)








Comments
Charlie, Excellent starting
Charlie,
Excellent starting point stuff. I was having problems in choosing the provider, and the persistence provider you've given in your persistence.xml worked for me..
Keep up the good work.
Cheers,
BK
usually i put a
usually i put a joinTransaction() after beginning it, why you did not use it?
:)
Not using JTA
Because my super short example is certainly not using JTA. I don't want to "join" in this case, I want to manually begin and commit.
Clear and simple
Thk! Pefectly clear and simple to have a quick taste of it.
Great tutorial
Great tutorial. As you said, too many gets into too much other crap, like servers, spring integration etc. That way you don't learn the true basics. This one cuts right to the bone, wish there were more tutorials like this.
Error
Thanks for such a nice example
But i am getting an error " column id cannot be resolved".
I did created a sequence in database. I am new to JPA . Could you please let me know how and where will we get the id and will it inserted in the databse.
I glossed over the database
I glossed over the database details in this post, semi-intentionally. The DB does need an "id" column, yes. I should have noted that in step 1 there. I will update it.
Hibernate Arrrrg
Great example. Just like so many I've found. Why can I not find an example showing how to read an object FROM the DB instead of writing one !!!! It is so frustraiting. I don't want one showing how to read an object based on it's ID I want one based on the value of some/all fields. Why is there no such example ?? I would have thought this is the type of thing that people would want to see before anything else !!!
hello my friend i will help u
hello my friend i will help u NOW.
to read all from a db:
package persistiendo;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
public class Hospital {
private List persons;
public static EntityManager em;
public Hospital(EntityManager em) {
Hospital.em=em;
persons=new ArrayList();
persons=em.createQuery("SELECT p FROM person p").getResultList();
// person is obviously an Entity, this way u "load" all //instances of Person into persons Array
using the example above u can
I'm working with eclipse,
I'm working with eclipse, followed your steps. when I run the damn thing, it keeps returning this:
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named default: The following providers:
oracle.toplink.essentials.PersistenceProvider
oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider
Returned null to createEntityManagerFactory.
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:154)
at com.totsp.datatest.JPAResourceBean.getEMF(JPAResourceBean.java:19)
at com.totsp.datatest.Driver.main(Driver.java:11)
WTF?
Exception in thread "main"
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named default: The following providers:
oracle.toplink.essentials.PersistenceProvider
oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider
Returned null to createEntityManagerFactory.
hey!! EntityManager named default: ==> default you must replace DEFAULT with your EntityManagerFactory's name!!!!!!! the XML's name created by jpa !! persistence.xml==> there u have a name, u must use it. Persistence Unit Name