Arun Gupta, Miles to go ...

Arun Gupta is a technology enthusiast, a passionate runner, and a community guy who works for Sun Microsystems.
« Previous day (Jun 19, 2007) | Main | Next day (Jun 21, 2007) »

http://blogs.sun.com/arungupta/date/20070620 Wednesday June 20, 2007

Hello JPA World!

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.

  1. In NetBeans IDE, create a new Web project and name it as "HelloJPA".
  2. Create an Entity class. Right-click the project, select 'New', 'Entity Class ...'. Specify the values as shown below:

    1. Create a new Persistence Unit by selecting 'Create Persistence Unit ...' and entering values as shown below:



      and click on 'Create'.

    and click on 'Finish'.

  3. Expand '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>
  4. Add the following fields to the newly generated 'Company.java':

    private String companyName;
    private float price;
    private float change;
    private float percentChange;
    private String lastUpdated;
  5. Generate getters/setters for each field by selecting the newly added fields, right-click on the selected text, select 'Refactor', 'Encapsulate Fields ...' and choose the getter/setters for each field as shown below:

  6. Add a constructor to '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;
    }
  7. Change the toString method in Company to:

    return "server.Company[id=" + id + ", lastUpdated=" + lastUpdated + "]";
  8. Add a new Servlet by right-click on the Project, select New, 'Servlet ...' as shown below:



    and click on 'Finish'.
  9. Update the generated Servlet template code such that it looks like:

    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();
    }


    Fix the imports by using 'Alt+Shift+F' default keyboard shortcut.
  10. Right-click on the Project, select 'Properties', 'Run' Categories, change the Relative URL to '/Hello'.
  11. And that's it! Hit the Green button to run the project or the default keyboard shortcut of 'F6'. After re-loading the page twice, the following output will be seen in the browser window:


 

Technorati: jpa glassfish netbeans

del.icio.us | furl | simpy | slashdot | technorati | digg |
|
« Previous day (Jun 19, 2007) | Main | Next day (Jun 21, 2007) »

Valid HTML! Valid CSS!

This is a personal weblog, I do not speak for my employer.