The Source for Java Technology Collaboration
User: Password:



Arun Gupta

Arun Gupta's Blog

Hello JPA World

Posted by arungupta on June 20, 2007 at 05:54 AM | Comments (4)

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


Bookmark blog post: del.icio.us del.icio.us Digg Digg DZone DZone Furl Furl Reddit Reddit
Comments
Comments are listed in date ascending order (oldest first) | Post Comment


  • That looks pretty reasonable, although starting with the database tables first was easier for me.

    I have one question. I've been working with the Hibernate JPA support and we've found it important to add the equals() and hashCode() methods to our entity classes. Is that something that you should do as well?

    Regards,

    -james.

    Posted by: jstansel on June 20, 2007 at 12:12 PM

  • Hi James,

    Netbeans will automatically add the equals and hashCode methods for you when you create an Entity using the steps above

    Posted by: lancea on June 21, 2007 at 05:44 AM

  • With Hibernate and JPA and Netbeans one of the things that I found is that you may want to change some of the things Netbeans gives you for free.

    For instance, Hibernate has a bad bunch of bugs to do with bags, so if you have two @OneToMany relationships in a class it will spit the dummy over the Collection.

    Bizarrely, changing the Collection to a Set or a List solves that problem (strictly speaking Hibernates 'bag' can contain more than one instance of the same thing, whereas a Set only ever has one instance of the same thing, so be careful)

    Posted by: rickcarson on June 21, 2007 at 04:59 PM

  • I think may you would like to try following project:
    https://dcoat.dev.java.net/
    It's simpler to auto-generate the more perfect source code.
    And more esay to use.

    Posted by: lihy70 on June 22, 2007 at 03:54 AM



Only logged in users may post comments. Login Here.


Powered by
Movable Type 3.01D
 Feed java.net RSS Feeds