Wednesday June 20, 2007
After much discussion, I was able to finally create a simple "Hello JPA World" example that uses Java Persistence API (JPA) to store and retrieve data from JavaDB from a Servlet deployed on GlassFish V2 b50 using NetBeans IDE 5.5.1. This blog describes the steps, in detail, on how to create this sample.
HelloJPA".New', 'Entity
Class ...'. Specify the values as shown below:
Create Persistence Unit ...'
and entering values as shown below:
Create'.and click on 'Finish'.
Configuration Files', open 'persistence.xml', click 'Add Class
...', select 'server.Company' and click on 'OK'. The 'persistence.xml'
will look like:<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
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_1_0.xsd">
<persistence-unit name="HelloJPAPU" transaction-type="RESOURCE_LOCAL">
<provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
<non-jta-data-source>jdbc/sample</non-jta-data-source>
<class>server.Company</class>
<properties>
<property name="toplink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
</persistence>Company.java':private String companyName;
private float price;
private float change;
private float percentChange;
private String lastUpdated;Refactor',
'Encapsulate Fields ...' and choose the getter/setters for each field as
shown below:
Company' class as follows:public Company(String companyName, float price, float change,
float percentChange, String lastUpdated) {
this.companyName = companyName;
this.price = price;
this.change = change;
this.percentChange = percentChange;
this.lastUpdated = lastUpdated;
}return "server.Company[id=" + id + ", lastUpdated=" + lastUpdated +
"]";Servlet
...' as shown below:
Finish'.protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
beginHTML(out);
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("HelloJPAPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
out.println("<h1>Hello JPA World!</h1>");
Company c = new Company("AAA Co", (float)10.0, (float)2.0, (float)10.0,
new Date().toString());
em.persist(c); // persisting to the source
em.getTransaction().commit(); // now committed
List list = em.createQuery(
"select c from Company c where
c.companyName = :companyName")
.setParameter("companyName",
c.getCompanyName()).getResultList();
out.println("<b>Total Companies: " + list.size() + "</b><br>");
for (int i=0; i<list.size(); i++) {
out.println((Company) list.get(i) +
"<br>");
}
endHTML(out);
}
void beginHTML(PrintWriter out) {
out.println("<html>");
out.println("<head>");
out.println("<title>Hello JPA World!</title>");
out.println("</head>");
out.println("<body>");
}
void endHTML(PrintWriter out) {
out.println("</body>");
out.println("</html>");
out.close();
}Alt+Shift+F' default keyboard shortcut.Properties', 'Run'
Categories, change the Relative URL to '/Hello'.F6'. After re-loading the page twice, the following output
will be seen in the browser window:
Technorati: jpa glassfish netbeans
Posted by Arun Gupta in web2.0 | Comments[23]
|
|
|
|
|
Today's Page Hits: 764
Total # blog entries: 994
| « November 2009 | ||||||
| Sun | Mon | Tue | Wed | Thu | Fri | Sat |
|---|---|---|---|---|---|---|
1 | 2 | 4 | 6 | 7 | ||
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | |||||
| Today | ||||||
Posted by Kris on July 02, 2007 at 03:18 AM PDT #
Posted by Arun on July 02, 2007 at 07:00 AM PDT #
Posted by Kris on July 03, 2007 at 08:02 PM PDT #
Posted by Arun Gupta's Blog on August 30, 2007 at 06:21 AM PDT #
Hi Arun,
At first i like to appriciate for good work. I am new JPA. I want to use it with jsp.I did some work on that but unable to get good result.So can you please provide me some example on JPA. It will be great help since iam searching for it from 4 days but unable to get good resource. Because iam an example guy please provide me an example also.
Thanks
suraj
Posted by suraj on November 10, 2007 at 07:23 AM PST #
Suraj, Several examples of JSP using JPA are available at: http://blogs.sun.com/arungupta/tags/jpa
Let me know if you have a specific question.
Posted by Arun Gupta on November 10, 2007 at 07:35 AM PST #
Posted by Arun Gupta's Blog on January 24, 2008 at 04:46 AM PST #
This is wonderful..thanks ..Arun
I was wondering which approach would be better.
1. First create entity class and then database from those entity class or
2. Create entity class from database.
Is there any good discussion/thread out there which explains the prons and cons of both of these scenarios?
Thanks
Jessica
Posted by Jessica on March 01, 2008 at 08:11 PM PST #
Just wanted to share this....on Netbeans 6.0, when you run this app, it will give you this error
Caused by: Exception [TOPLINK-0] (Oracle TopLink Essentials - 2.0 (Build b58g-fcs (09/07/2007))): oracle.toplink.essentials.exceptions.IntegrityException
Descriptor Exceptions:
---------------------------------------------------------
Exception [TOPLINK-63] (Oracle TopLink Essentials - 2.0 (Build b58g-fcs (09/07/2007))): oracle.toplink.essentials.exceptions.DescriptorException
Exception Description: The instance creation method [server.Company.<Default Constructor>], with no parameters, does not exist, or is not accessible.
Internal Exception: java.lang.NoSuchMethodException: server.Company.<init>()
Descriptor: RelationalDescriptor(server.Company --> [DatabaseTable(COMPANY)])
Adding an empty constructor in Company.java solves the issue.
Thanks
Jessica
Posted by Jessica on March 01, 2008 at 09:25 PM PST #
Running this code after a fresh install of Netbeans 6.1 gave me the error:
java.lang.IllegalArgumentException: Object: server.Company[id=null, lastUpdated=Sat Mar 08 09:43:17 EST 2008] is not a known entity type.
I added a default constructor to server.Company, but I still receive this error.
Posted by Ben on March 08, 2008 at 06:43 AM PST #
Restarted server and it works. Go figure.
Posted by Ben on March 08, 2008 at 06:46 AM PST #
Hi Arun,
I am new to EJB3 and Iam doing a project on EJB3 this semester. your article helped me to understand basics. thanks for this.
I would like to request you if you can provide me any details for using mysql instead of javaderby for EJB3 using glassfish on Netbeans.
My Problem is Iam unable to understnad about database part. Do I need to add it to connection resource in server console or i can go through some database setting on netbeans ide.
Plz clear me..
thanks a lot in advance
regards
abishek kumar.
Posted by Abishek Kumar on March 18, 2008 at 04:38 PM PDT #
Thanks a lot for this tutorial! It's really clear.
I'm using Eclipse, MySQL 5.0, GlassFish V2 instead of NetBeans and Derby.
To connect to MySQL I define a MySQL JDBC Ressource and call it jdbc/mysql_resource. I had to use this in persistence.xml ( had to define a non-jta-data-source called jdbc/mysql_resource as well as classes )
Posted by Tony on March 24, 2008 at 04:06 PM PDT #
Just forgot I define the MySQL JDBC Resource in the glassfish administration console.
Posted by Tony on March 24, 2008 at 04:08 PM PDT #
I'm curious about the "non-jta-datasource" tag in your persistence.xml that has the same value ("jdbc/sample") you entered in your gui tool. Does this "data-source" property exist in some external xml? How is "jdbc/sample" used?
Posted by Joe Kingston on April 10, 2008 at 01:08 PM PDT #
[TopLink Info]: 2008.03.06 09:46:25.640--ServerSession(3668766)--TopLink, version: Oracle TopLink Essentials - 2.0 (Build b58g-fcs (09/07/2007))
Exception Description: Cannot acquire data source [data_source].
Internal Exception: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial)
Posted by anonymus on April 30, 2008 at 12:16 AM PDT #
can any1 figureout wat the prob is...am using jpa wid toplinks
Posted by anonymus on April 30, 2008 at 12:18 AM PDT #
Just forgot I define the MySQL JDBC Resource in the glassfish administration console.
Posted by laptop batteries on November 27, 2008 at 04:58 PM PST #
It worked for me with NetBeans 6.1 as well. Nice example.
But I cannot understand lines about how to query the DB using entity manager as given below in Hello.java servlet class
***********************************
Company c = new Company("AAA Co", (float)10.0, (float)2.0, (float)10.0, new Date().toString());
em.persist(c); // persisting to the source
em.getTransaction().commit(); // now committed
List list = em.createQuery(
"select c from Company c where c.companyName = :companyName")
.setParameter("companyName", c.getCompanyName()).getResultList();
******************************
A Good explantion would have helped beginners like me.
Some reference also might help.
Thanks and Wishes
Posted by Harish Vembu on January 06, 2009 at 11:15 AM PST #
Harish, Glad you liked the article. Please google on JPQL and you'll find tons of reference on how to use the query language that can be used with DB entity manager.
Posted by Arun Gupta on January 06, 2009 at 11:45 AM PST #
Instead of creating EntityManger as:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("HelloJPAPU");
EntityManager em = emf.createEntityManager();
it can be injected as:
@PersistenceContext(unitName="HelloJPAPU")
EntityManager em;
Posted by Arun Gupta on February 05, 2009 at 03:35 PM PST #
To connect to MySQL I define a MySQL JDBC Ressource and call it jdbc/mysql_resource. I had to use this in persistence.xml ( had to define a non-jta-data-source called jdbc/mysql_resource as well as classes )
Posted by New Funny Pictures on March 08, 2009 at 02:28 PM PDT #
<strong>very good work</strong>
Posted by jj on March 19, 2009 at 05:38 PM PDT #