Byron Kiourtzoglou

About Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Persist object with JPA

With this example we are going to demonstrate how to persist an object using the JPA. The Java Persistence API provides Java developers with an object/relational mapping facility for managing relational data in Java applications.

Here, we are using JPA to persist an object, as shown below:

The PersistObjectWithJPA class

In PersistObjectWithJPA class we create an EntityManagerFactory interface to interact with the entity manager factory for MyPeristenceUnit, that is defined in persistence.xml file. We create an EntityManager, using the createEntityManager() API method. Then, we create a new ProjectManager object. The new object is writen to the database, using the persist(java.lang.Object entity) API method of EntityManager. The getTransaction().begin() and getTransaction().commit() methods are used before and after the EntityManager invokes a method so that a transaction begins and ends.

package com.javacodegeeks.snippets.enterprise;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class PersistObjectWithJPA {
	
	public static void main(String[] args) {
		
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyPersistenceUnit");
		
		EntityManager em = emf.createEntityManager();
		
		em.getTransaction().begin();
		
		Employee employee = new Employee();
		employee.setName("Jack");
		employee.setSurname("Thomson");
		employee.setTitle("QA Engineer");
		employee.setCreated(new Date());
		
		em.persist(employee);
		
		em.getTransaction().commit();
		
		em.close();
	    emf.close();

	}
	
}

Employee Class

The Employee class is an entity class, annotated with the javax.persistence.Entity annotation. It uses the @Id annotation to define its id property, and the @GeneratedValue annotation with strategy set to GenerationType.AUTO so that the id gets auto-generated values.

package com.javacodegeeks.snippets.enterprise;

import java.util.Date;

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

@Entity
public class Employee {
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private Long id;
    private String name;
    private String surname;
    private String title;
    private Date created;
    
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public String getSurname() {
		return surname;
	}
	public void setSurname(String surname) {
		this.surname = surname;
	}
	
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	
	public Date getCreated() {
		return created;
	}
	public void setCreated(Date created) {
		this.created = created;
	}
	
	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", surname=" + surname
				+ ", title=" + title + "]";
	}

}

persistence.xml

<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 http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">
	
	<persistence-unit name="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<properties>
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
			<property name="hibernate.hbm2ddl.auto" value="update" />
			<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
			<property name="hibernate.connection.username" value="jcg" />
			<property name="hibernate.connection.password" value="jcg" />
			<property name="hibernate.connection.url" value="jdbc:mysql://localhost/companydb" />
		</properties>
	</persistence-unit>
	
</persistence>

 
This was an example of how to persist an object using the JPA.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.