Simple JPA Application with Hibernate

Posted: February 14, 2012 in Java Posts
Tags: , , , , , , ,
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,

1 CREATE TABLE `Department` (
2 `departmentId` int(10) NOT NULL,
3 `departmentName` varchar(10) default NULL,
4 PRIMARY KEY  (`departmentId`))
2. Persistence.xml:

This persistence.xml file is act like configuration file for JPA.

01 <?xml version="1.0" encoding="UTF-8"?>
02
04
05 <persistence-unit name="JPASamplePU" transaction-type="RESOURCE_LOCAL">
06
07 <provider>org.hibernate.ejb.HibernatePersistence</provider>
08
09 <class>com.bsj.entities.Department</class>
10
11 <properties>
12
13 <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
14
15 <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/jpadb"/>
16
17 <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
18
19 <property name="hibernate.hbm2ddl.auto" value="update"/>
20
21 <property name="hibernate.connection.username" value="root"/>
22
23 <property name="hibernate.connection.password" value="root"/>
24
25 </properties>
26
27 </persistence-unit>
28
29 </persistence>

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;
02
03 import java.io.Serializable;
04
05 import javax.persistence.Basic;
06
07 import javax.persistence.Column;
08
09 import javax.persistence.Entity;
10
11 import javax.persistence.Id;
12
13 import javax.persistence.NamedQueries;
14
15 import javax.persistence.NamedQuery;
16
17 import javax.persistence.Table;
18
19 @Entity//Represent the class entity class
20
21 @Table(name = "department")//Represents the table name
22
23 @NamedQueries(
24
25 {
26
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")
28
29 })
30
31 public class Department implements Serializable
32
33 {
34
35 private static final long serialVersionUID = 1L;
36
37 @Id
38
39 @Basic(optional = false)
40
41 @Column(name = "departmentId")
42
43 private Integer departmentId;
44
45 @Column(name = "departmentName")
46
47 private String departmentName;
48
49 public Department()
50
51 {
52
53 }
54
55 public Department(Integer departmentId)
56
57 {
58
59 this.departmentId = departmentId;
60
61 }
62
63 public Department(Integer departmentId, String DepartmentName)
64
65 {
66
67 this.departmentId = departmentId;
68
69 this.departmentName = departmentName;
70
71 }
72
73 //Getter setter method of variables
74
75 }
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;
002
003 import java.util.List;
004
005 import javax.persistence.EntityManager;
006
007 import javax.persistence.EntityManagerFactory;
008
009 import javax.persistence.Query;
010
011 public class DepartmentManager
012
013 {
014
015 private EntityManager em;
016
017 public DepartmentManager(EntityManagerFactory emf)
018
019 {
020
021 em = emf.createEntityManager();
022
023 }
024
025 /**
026
027 * Method used to create department.
028
029 * @param department
030
031 */
032
033 public void createDepartment(Department department)
034
035 {
036
037 //Begin Transaction
038
039 System.out.println("Creation : ");
040
041 em.getTransaction().begin();
042
043 em.persist(department); //Persist entity in persistence context.
044
045 //Commit Transaction
046
047 em.getTransaction().commit();
048
049 System.out.println("Department Created SuccessFully");
050
051 }
052
053 /**
054
055 * Method used to search department Name by id.
056
057 * @param id
058
059 * @return
060
061 */
062
063 public Department searchById(Integer id)
064
065 {
066
067 //Method used to find data
068
069 return em.find(Department.class, id);
070
071 }
072
073 public void updateUser(Department department)
074
075 {
076
077 System.out.println("Update : ");
078
079 em.getTransaction().begin();
080
081 em.merge(department);
082
083 em.getTransaction().commit();
084
085 System.out.println("Update successfully.");
086
087 }
088
089 public void removeUser(Department department)
090
091 {
092
093 em.getTransaction().begin();
094
095 em.remove(department);
096
097 em.getTransaction().commit();
098
099 System.out.println("Remove department successfully");
100
101 }
102
103 public List getAll()
104
105 {
106
107 Query query = em.createQuery("select a from Department a");
108
109 List list = query.getResultList();
110
111 return list;
112
113 }
114
115 public void close()
116
117 {
118
119 em.close();
120
121 }
122
123 }
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;
002
003 import com.bsj.entities.Department;
004
005 import com.bsj.entities.DepartmentManager;
006
007 import java.util.Iterator;
008
009 import java.util.List;
010
011 import javax.persistence.EntityManagerFactory;
012
013 import javax.persistence.Persistence;
014
015 public class TestJPA
016
017 {
018
019 private DepartmentManager departmentManager;
020
021 private EntityManagerFactory emf;
022
023 /**
024
025 * Method to setup basic thing need for implementation like entiny manager
026
027 * factory,entity manager etc.
028
029 * @throws Exception
030
031 */
032
033 protected void setUp() throws Exception
034
035 {
036
037 /**
038
039 * Create the entity manager factory with the help of persistence.
040
041 * @Param NameofPersistence unit form Persistence.xml
042
043 */
044
045 emf = Persistence.createEntityManagerFactory("JPASamplePU");
046
047 /**
048
049 * create Departmanager
050
051 * @Param Entity Manager Factory
052
053 */
054
055 departmentManager = new DepartmentManager(emf);
056
057 }
058
059 /**
060
061 * Method to close entity manager and entity manager factory.
062
063 * (i.e) Remove from the persistence context
064
065 * @throws Exception
066
067 */
068
069 protected void close() throws Exception
070
071 {
072
073 departmentManager.close();
074
075 emf.close();
076
077 }
078
079 /**
080
081 * Method for test the application.
082
083 */
084
085 public void test()
086
087 {
088
089 /**
090
091 * Create the Entity by using constructor of Entity.
092
093 */
094
095 Department department = new Department(10, "Chemical");
096
097 departmentManager.createDepartment(department);
098
099 System.out.println("Before Update :");
100
101 Department searchDepartment = departmentManager.searchById(50);
102
103 System.out.println("Department Name of Id 50 : " + searchDepartment.getDepartmentName());
104
105 searchDepartment.setDepartmentName("EEE");
106
107 departmentManager.updateUser(department);
108
109 department = departmentManager.searchById(50);
110
111 System.out.println("After update.");
112
113 System.out.println("Department Name of Id 50 : " + searchDepartment.getDepartmentName());
114
115 List list = departmentManager.getAll();
116
117 System.out.println("Number of Departments: " + list.size());
118
119 System.out.println("List of Departments : ");
120
121 Iterator iterator = list.iterator();
122
123 while (iterator.hasNext())
124
125 {
126
127 Department department3 = (Department) iterator.next();
128
129 System.out.println("Id : " + department3.getDepartmentId());
130
131 System.out.println("Name : " + department3.getDepartmentName());
132
133 }
134
135 }
136
137 public static void main(String args[])
138
139 {
140
141 System.out.println("Inside TestJPA main");
142
143 TestJPA testJPA = new TestJPA();
144
145 try
146
147 {
148
149 testJPA.setUp();
150
151 testJPA.test();
152
153 testJPA.close();
154
155 }
156
157 catch (Exception e)
158
159 {
160
161 e.printStackTrace();
162
163 }
164
165 System.out.println("End of TestJPA main");
166
167 }
168
169 }

Thats all folks.If you found this article was helpful to you,don’t forget to leave your valuable comments here.Happy coding…

About these ads
Comments
  1. A/C Repair says:

    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?

  2. Esmeralda Calta says:

    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.

  3. göz yanılmaları says:

    Good post admin! i bookmarked your web blog. i’ll glance forward when you will have an e-mail variety adding.

  4. Broadjam scam says:

    Great post, I think people should learn a lot from this web site its rattling user friendly. So much excellent information on here :D.

  5. oyun oyna says:

    oh my god amazing put up admin will verify your web site often

  6. sextube says:

    I was searching for this great sharing admin a lot thanks and have great running a blog bye

  7. e-tupakka suomesta says:

    I went over this website and I think you have a lot of superb information, saved to favorites (:.

  8. licensing music rights says:

    I always was interested in this subject and still am, thankyou for putting up.

  9. certified nursing assistant exam says:

    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.

  10. teething ring says:

    As soon as I noticed this web site I went on reddit to share some of the love with them.

  11. film izle says:

    Hello admin great post considerably thanks beloved this website truly a lot

  12. rofl photos says:

    Good post. I learn something far more challenging on distinct blogs everyday.

  13. breast cancer leeds says:

    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.

  14. web cam sex says:

    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.

  15. auto approved blog says:

    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

  16. attorney los angeles says:

    Enjoyed reading this, very good stuff, thanks .

  17. Galina Perng says:

    You have remarked very interesting details! ps nice site.

  18. hybrid cars says:

    I really like your writing style, superb info , thankyou for posting : D.

  19. cancer quilts patterns says:

    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.

  20. us mail privacy act says:

    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.

  21. four micro onde says:

    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!

  22. surfing tips says:

    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.

  23. accelerated nursing programs says:

    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!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s