Introduction:
Now I am the newbie to JPA.I learn some thing about JPA. So I wanna share that with you all. So only I am here to do the same. This article deals with how to develop the simple JPA application using hibernate vendor support. Let’s get into that.
Prerequisites:
- JDK 1.5 and above
- Your favourite IDE.
- HibernateJPA Library.
- Mysqljdbc.jar
After create the Project we have to add above required libraries and jars into our library folder.
Steps:
- Table Creation.
- Creation of Persistence.xml
- Creation of Entity class
- Creation of Entity Manager class
- Creation of Test class.
1. Table Creation:
Create table named “Department”, which contains two columns “departmentId” and “departmentName” by executing the following script,
3 |
`departmentName` varchar(10) default NULL, |
2. Persistence.xml:
This persistence.xml file is act like configuration file for JPA.
01 |
<?xml version="1.0" encoding="UTF-8"?> |
05 |
<persistence-unit name="JPASamplePU" transaction-type="RESOURCE_LOCAL"> |
07 |
<provider>org.hibernate.ejb.HibernatePersistence</provider> |
09 |
<class>com.bsj.entities.Department</class> |
13 |
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/> |
17 |
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/> |
19 |
<property name="hibernate.hbm2ddl.auto" value="update"/> |
21 |
<property name="hibernate.connection.username" value="root"/> |
23 |
<property name="hibernate.connection.password" value="root"/> |
Persistence-unit: used to represent the persistence unit.
Transaction-type: type of transaction
There are two type of transactions are avail.
Resource-local: Transactions have to be managed by developer locally.
JTA: Transactions are managed by application server.
Class: Represent the entity.
hbm2ddl.auto: used to perform the action in the database when the SessionFactory is created.
All the others are basic things.
3. Creation of Entity Class:
Entity class is used to represent the table in class format.
01 |
package com.bsj.entities; |
03 |
import java.io.Serializable; |
05 |
import javax.persistence.Basic; |
07 |
import javax.persistence.Column; |
09 |
import javax.persistence.Entity; |
11 |
import javax.persistence.Id; |
13 |
import javax.persistence.NamedQueries; |
15 |
import javax.persistence.NamedQuery; |
17 |
import javax.persistence.Table; |
19 |
@Entity//Represent the class entity class |
21 |
@Table(name = "department")//Represents the table name |
27 |
@NamedQuery(name = "Department.findAll", query = "SELECT d FROM Department d"), @NamedQuery(name = "Department.findByDepartmentId", query = "SELECT d FROM Department d WHERE d.departmentId = :departmentId"), @NamedQuery(name = "Department.findByDepartmentName", query = "SELECT d FROM Department d WHERE d.departmentName = :departmentName") |
31 |
public class Department implements Serializable |
35 |
private static final long serialVersionUID = 1L; |
39 |
@Basic(optional = false) |
41 |
@Column(name = "departmentId") |
43 |
private Integer departmentId; |
45 |
@Column(name = "departmentName") |
47 |
private String departmentName; |
55 |
public Department(Integer departmentId) |
59 |
this.departmentId = departmentId; |
63 |
public Department(Integer departmentId, String DepartmentName) |
67 |
this.departmentId = departmentId; |
69 |
this.departmentName = departmentName; |
73 |
//Getter setter method of variables |
Annotation used in Entity Class:
@Entity – used to represent the class as Entity class. By using this annotation only we can make simple POJO class as Entity class.
@Table – used Represent the table name which the entity class points out.
@Id – Used to represent the primary key field.Only one primary key is allowed in the entity class.
@Column – used to represent the column details such as name, nullable etc.
QueryAPI:
There are two types of query is avail.
1. Static (Named) Queries: defined statically with the help of annotation (or XML) before the entity class.
A name of the Query is usually given to the query definition so that other components in the same persistent unit can refer the query by the name.
2. Dynamic queries: are nothing but whose query strings are provided at run-time
4.Creation of Entity Manager Class:
The constructor has the Entity Manager Factory as argument and it allows us to create the Entity Manager.
The Entity Manager class is transaction scoped bean so we have to begin transaction before each action and commit transaction after each operation.
001 |
package com.bsj.entities; |
003 |
import java.util.List; |
005 |
import javax.persistence.EntityManager; |
007 |
import javax.persistence.EntityManagerFactory; |
009 |
import javax.persistence.Query; |
011 |
public class DepartmentManager |
015 |
private EntityManager em; |
017 |
public DepartmentManager(EntityManagerFactory emf) |
021 |
em = emf.createEntityManager(); |
027 |
* Method used to create department. |
033 |
public void createDepartment(Department department) |
039 |
System.out.println("Creation : "); |
041 |
em.getTransaction().begin(); |
043 |
em.persist(department); //Persist entity in persistence context. |
047 |
em.getTransaction().commit(); |
049 |
System.out.println("Department Created SuccessFully"); |
055 |
* Method used to search department Name by id. |
063 |
public Department searchById(Integer id) |
067 |
//Method used to find data |
069 |
return em.find(Department.class, id); |
073 |
public void updateUser(Department department) |
077 |
System.out.println("Update : "); |
079 |
em.getTransaction().begin(); |
081 |
em.merge(department); |
083 |
em.getTransaction().commit(); |
085 |
System.out.println("Update successfully."); |
089 |
public void removeUser(Department department) |
093 |
em.getTransaction().begin(); |
095 |
em.remove(department); |
097 |
em.getTransaction().commit(); |
099 |
System.out.println("Remove department successfully"); |
107 |
Query query = em.createQuery("select a from Department a"); |
109 |
List list = query.getResultList(); |
Methods used in Entity Manager:
Persist(entityObject)-Used to persist entity in the persistence context.
Find (Entityclass,value) – Find the datas regarding the input passed as argument.
merge(entityobject) : Update the database regarding to the passing details.
5.Creation of Test class:
We can get the entity manager factory by the createEntityManagerFactory method of the class Persistence,
createEntityManagerFactory(persistence unit name);
This method has the persistence unit name as argument.
Call the entity manager methods by using the reference of entity manager.
001 |
package com.bsj.tester; |
003 |
import com.bsj.entities.Department; |
005 |
import com.bsj.entities.DepartmentManager; |
007 |
import java.util.Iterator; |
009 |
import java.util.List; |
011 |
import javax.persistence.EntityManagerFactory; |
013 |
import javax.persistence.Persistence; |
019 |
private DepartmentManager departmentManager; |
021 |
private EntityManagerFactory emf; |
025 |
* Method to setup basic thing need for implementation like entiny manager |
027 |
* factory,entity manager etc. |
033 |
protected void setUp() throws Exception |
039 |
* Create the entity manager factory with the help of persistence. |
041 |
* @Param NameofPersistence unit form Persistence.xml |
045 |
emf = Persistence.createEntityManagerFactory("JPASamplePU"); |
049 |
* create Departmanager |
051 |
* @Param Entity Manager Factory |
055 |
departmentManager = new DepartmentManager(emf); |
061 |
* Method to close entity manager and entity manager factory. |
063 |
* (i.e) Remove from the persistence context |
069 |
protected void close() throws Exception |
073 |
departmentManager.close(); |
081 |
* Method for test the application. |
091 |
* Create the Entity by using constructor of Entity. |
095 |
Department department = new Department(10, "Chemical"); |
097 |
departmentManager.createDepartment(department); |
099 |
System.out.println("Before Update :"); |
101 |
Department searchDepartment = departmentManager.searchById(50); |
103 |
System.out.println("Department Name of Id 50 : " + searchDepartment.getDepartmentName()); |
105 |
searchDepartment.setDepartmentName("EEE"); |
107 |
departmentManager.updateUser(department); |
109 |
department = departmentManager.searchById(50); |
111 |
System.out.println("After update."); |
113 |
System.out.println("Department Name of Id 50 : " + searchDepartment.getDepartmentName()); |
115 |
List list = departmentManager.getAll(); |
117 |
System.out.println("Number of Departments: " + list.size()); |
119 |
System.out.println("List of Departments : "); |
121 |
Iterator iterator = list.iterator(); |
123 |
while (iterator.hasNext()) |
127 |
Department department3 = (Department) iterator.next(); |
129 |
System.out.println("Id : " + department3.getDepartmentId()); |
131 |
System.out.println("Name : " + department3.getDepartmentName()); |
137 |
public static void main(String args[]) |
141 |
System.out.println("Inside TestJPA main"); |
143 |
TestJPA testJPA = new TestJPA(); |
165 |
System.out.println("End of TestJPA main"); |
Thats all folks.If you found this article was helpful to you,don’t forget to leave your valuable comments here.Happy coding…
0.000000
0.000000
I’m curious to find out what blog system you’re working with? I’m having some small security problems with my latest website and I’d like to find something more safe. Do you have any solutions?
I wanted to create you one tiny word so as to say thanks a lot the moment again for those marvelous views you have discussed on this website. This has been simply remarkably generous of people like you to give openly just what many people would have offered for an e-book in making some cash for their own end, specifically seeing that you might well have tried it in the event you desired. These inspiring ideas in addition worked to provide a good way to recognize that other people online have a similar eagerness just as my very own to figure out whole lot more in regard to this issue. I know there are several more enjoyable opportunities up front for many who go through your site.
Good post admin! i bookmarked your web blog. i’ll glance forward when you will have an e-mail variety adding.
Great post, I think people should learn a lot from this web site its rattling user friendly. So much excellent information on here
.
oh my god amazing put up admin will verify your web site often
I was searching for this great sharing admin a lot thanks and have great running a blog bye
I went over this website and I think you have a lot of superb information, saved to favorites (:.
I always was interested in this subject and still am, thankyou for putting up.
I’m really impressed along with your writing abilities as smartly as with the format to your blog. Is that this a paid topic or did you modify it yourself? Either way keep up the nice quality writing, it is rare to peer a great blog like this one nowadays.
As soon as I noticed this web site I went on reddit to share some of the love with them.
Hello admin great post considerably thanks beloved this website truly a lot
Good post. I learn something far more challenging on distinct blogs everyday.
With havin so much written content do you ever run into any problems of plagorism or copyright infringement? My website has a lot of exclusive content I’ve either written myself or outsourced but it looks like a lot of it is popping it up all over the web without my authorization. Do you know any solutions to help stop content from being ripped off? I’d really appreciate it.
I like this blog very much, Its a really nice berth to read and get information. “Slang is a language that rolls up its sleeves, spits on its hands and goes to work.” by Carl Sandburg.
Cause that’s required valuable affiliate business rules to get you started on participating in circumstances appropriate for your incredible web-based business concern. Inernet marketing
Enjoyed reading this, very good stuff, thanks .
You have remarked very interesting details! ps nice site.
I really like your writing style, superb info , thankyou for posting : D.
Hmm it appears like your blog ate my first comment (it was super long) so I guess I’ll just sum it up what I submitted and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog blogger but I’m still new to the whole thing. Do you have any suggestions for beginner blog writers? I’d certainly appreciate it.
Outstanding post, I think website owners should acquire a lot from this website its real user genial . “My father always told me, ‘Find a job you love and you’ll never have to work a day in your life.’” by Jim Fox.
I really appreciate this post. I’ve been looking all over for this! Thank goodness I found it on Bing. You’ve made my day! Thank you again!
Excellent read, I just passed this onto a colleague who was doing a little research on that. And he just bought me lunch as I found it for him smile Thus let me rephrase that: Thanks for lunch! “They may forget what you said, but they will never forget how you made them feel.” by Carl W. Buechner.
My brother recommended I may like this web site. He was once entirely right. This post actually made my day. You cann’t imagine simply how much time I had spent for this info! Thank you!