Tuesday Feb 09, 2010

TOTD #122: Creating a JPA Persistence Unit using NetBeans 6.8

Taking TOTD #121 forward, this blog explains how to create a JPA Persistence Unit for a MySQL sample database and package it as a library. This JAR file can then be easily included in other web applications.

Lets get started!

  1. Configure GlassFish for using the MySQL sample database (sakila) as described in TOTD #121.
  2. Add the GlassFish instance in NetBeans IDE using "Services" panel.
  3. Create JPA entities using NetBeans IDE.
    1. Create a Java class library:



      Our ultimate goal is to create a reusable JAR file and that's why this project type is chosen.
    2. Specify the name of project as "SakilaPU":


    3. Right-click on the project and select "New", "Entity Classes from Database ..." to initiate the process of entity generation:

    4. Choose the database connection as:



      If not configured, then can be easily done by clicking on "New Database Connection ..." in the list box.
      1. Click on "Add All >>" to generate the mapped JPA entities for all tables and views.
      2. The views do not have primary keys and will need to be appropriately annotated (described later).
      3. Click on "Next >".
    5. Give the package name as:



      and specify the package name as "sakila". Click on "Create Persistence Unit ...".
    6. Change the default PU name from "SakilaPUPU" to "SakilaPU":



      and click on "Finish". Notice that "EclipseLink", the Reference Implementation of JPA 2.0, is used as the persistence library.
    7. Add "@javax.persistence.Id" annotation to the following class/field combination:
      Class Field
      sakila.SalesByFilmCategory category
      sakila.ActorInfo actorId
      sakila.FilmList fid
      sakila.CustomerList id
      sakila.NicerButSlowerFilmList fid
      sakila.StaffList id
      sakila.SalesByStore store

      This is required because none of the "views" are defined with a primary key.
    8. Right-click on the project and select "Clean & Build". This generates "dist/SakilaPU.jar" and the structure looks like:



This JAR file can now be included in any web application. The pre-built JAR file can also be downloaded here.

In order for this PU to be used in an application server (such as GlassFish) that is pre-configured with a JDBC resource, the "persistence.xml" needs to be changed to:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
 <persistence-unit name="SakilaPU" transaction-type="JTA">
 <jta-data-source>jdbc/sakila</jta-data-source>
 <properties/>
 </persistence-unit>
</persistence>

The JDBC resource name is specified using <jta-data-source>.

The key items to note about this pre-built JAR:

  • Persistence Unit Name: "SakilaPU"
  • All classes are in "sakila.\*" package.
  • Each class has a pre-defined "<CLASS-NAME>.findAll" named query that returns all elements from the underlying view/table.

This JAR can be installed to your local Maven repository as:

mvn install:install-file -Dfile=SakilaPU.jar -DgroupId=org.glassfish.samples -DartifactId=sakilapu -Dversion=1.0 -Dpackaging=jar -DgeneratePom=true

and then included in your "pom.xml" as:

 <dependency>
   <groupId>org.glassfish.samples</groupId>
   <artifactId>sakilapu</artifactId>
   <version>1.0</version>
   <scope>compile</scope>
 </dependency>

Even though this blog uses a MySQL sample database, these steps can be easily followed for any other database such as Oracle or JavaDB.

Technorati: totd javaee glassfish v3 jpa eclipselink persistenceunit mysql sakila netbeans

Tuesday Aug 05, 2008

TOTD #40: jQuery Autcomplete widget with MySQL, GlassFish, NetBeans

TOTD #39 explained how to create an Autocomplete widget (server-powered autocompleting of text fields, similar to Google Suggest) using Prototype/Script.aculo.us libraries with NetBeans, GlassFish and MySQL. This Tip Of The Day (TOTD) builds upon that project and shows how same functionality can be achieved using jQuery Library.
  1. Use the NetBeans project created in TOTD #39. Right-clicking on the project, select "New", "JSP...", enter the name as "index2" and click on "Finish".
  2. Download jquery JavaScript library from here (1.2.6 (minified) as of this writing) and copy into the "javascripts" folder of your NetBeans project.
  3. Copy contents from "index.jsp" into "index2.jsp".
  4. Borrowing the code from AjaxCompleter Tutorial, replace <script> tags in "index2.jsp" with the following code fragment:

            <script src="javascripts/jquery-1.2.6.min.js" type="text/javascript"></script>
            <script type="text/javascript">
                function autocomplete(autocomplete) {
                    if (autocomplete.length == 0) {
                        $('#autocomplete_choices').hide();
                    } else {
                        $.post("/Autocomplete/StatesServlet", { autocomplete_parameter: "" + autocomplete + ""},
                            function(data) {
                                if (data.length > 0) {
                                    $('#autocomplete_choices').show();
                                    $('#autocomplete_choices').html(data);
                                }
                            });
                    }
                }
            </script>

And here are couple of output screenshots:





Please leave suggestions on other TOTD (Tip Of The Day) that you'd like to see. A complete archive of all tips is available here.

Technorati: totd mysql jpa persistenceunit netbeans glassfish jquery autocomplete

Thursday Jul 24, 2008

TOTD #38: Creating a MySQL Persistence Unit using NetBeans IDE


This TOTD (Tip Of The Day) shows how to create a Persistence Unit (PU) for a MySQL database using NetBeans IDE. This PU can then be used in any of Java EE artifacts (JSP, Servlet, EJB, ...) for database interaction.
  1. In NetBeans IDE, create a new project
    1. Create a new NetBeans Web project and enter the values ("Autocomplete") as shown:



      and click on "Next".
    2. Choose GlassFish v2 as the deployment server and then click on "Finish".
  2. Set up the database
    1. Start the database as:

      ~ >sudo mysqld_safe --user root
      Password:<YOUR PASSWORD>
      Starting mysqld daemon with databases from /usr/local/mysql/data

    2. Create a user, create the database and grant the privileges to newly created user as:

      mysql> CREATE USER duke IDENTIFIED by 'duke';
      Query OK, 0 rows affected (0.00 sec)

      mysql> create database states;
      Query OK, 1 row affected (0.00 sec)

      mysql> GRANT ALL on states.\* TO duke;
      Query OK, 0 rows affected (0.00 sec)
    3. In NetBeans IDE, Services panel, right-click on Databases and click on "New Connection..." and enter the values as shown:



      and click on "OK" and again on "OK".
    4. Right-click on the newly created database and select "Execute Command ..." as shown:


    5. Create the database table as:

      CREATE TABLE STATES (
            id INT,
            abbrev VARCHAR(2),
            name VARCHAR(50),
            PRIMARY KEY (id)
      );

      and click on the green button to run the query as shown here:


    6. Following the same instructions, populate the table using the following SQL:

      INSERT INTO STATES VALUES (1, "AL", "Alabama");
      INSERT INTO STATES VALUES (2, "AK", "Alaska");
      INSERT INTO STATES VALUES (3, "AZ", "Arizona");
      INSERT INTO STATES VALUES (4, "AR", "Arkansas");
      INSERT INTO STATES VALUES (5, "CA", "California");
      INSERT INTO STATES VALUES (6, "CO", "Colorado");
      INSERT INTO STATES VALUES (7, "CT", "Connecticut");
      INSERT INTO STATES VALUES (8, "DE", "Delaware");
      INSERT INTO STATES VALUES (9, "GL", "Florida");
      INSERT INTO STATES VALUES (10, "GA", "Georgia");
      INSERT INTO STATES VALUES (11, "HI", "Hawaii");
      INSERT INTO STATES VALUES (12, "ID", "Idaho");
      INSERT INTO STATES VALUES (13, "IL", "Illinois");
      INSERT INTO STATES VALUES (14, "IN", "Indiana");
      INSERT INTO STATES VALUES (15, "IA", "Iowa");
      INSERT INTO STATES VALUES (16, "KS", "Kansas");
      INSERT INTO STATES VALUES (17, "KY", "Kentucky");
      INSERT INTO STATES VALUES (18, "LA", "Louisiana");
      INSERT INTO STATES VALUES (19, "ME", "Maine");
      INSERT INTO STATES VALUES (20, "MD", "Maryland");
      INSERT INTO STATES VALUES (21, "MA", "Massachussetts");
      INSERT INTO STATES VALUES (22, "MI", "Michigan");
      INSERT INTO STATES VALUES (23, "MN", "Minnesota");
      INSERT INTO STATES VALUES (24, "MS", "Mississippi");
      INSERT INTO STATES VALUES (25, "MO", "Missouri");
      INSERT INTO STATES VALUES (26, "MT", "Montana");
      INSERT INTO STATES VALUES (27, "NE", "Nebraska");
      INSERT INTO STATES VALUES (28, "NV", "Nevada");
      INSERT INTO STATES VALUES (29, "NH", "New Hampshire");
      INSERT INTO STATES VALUES (30, "NJ", "New Jersey");
      INSERT INTO STATES VALUES (31, "NM", "New Mexico");
      INSERT INTO STATES VALUES (32, "NY", "New York");
      INSERT INTO STATES VALUES (33, "NC", "North Carolina");
      INSERT INTO STATES VALUES (34, "ND", "North Dakota");
      INSERT INTO STATES VALUES (35, "OH", "Ohio");
      INSERT INTO STATES VALUES (36, "OK", "Oklahoma");
      INSERT INTO STATES VALUES (37, "OR", "Orgeon");
      INSERT INTO STATES VALUES (38, "PA", "Pennsylvania");
      INSERT INTO STATES VALUES (39, "RI", "Rhode Island");
      INSERT INTO STATES VALUES (40, "SC", "South Carolina");
      INSERT INTO STATES VALUES (41, "SD", "South Dakota");
      INSERT INTO STATES VALUES (42, "TN", "Tennessee");
      INSERT INTO STATES VALUES (43, "TX", "Texas");
      INSERT INTO STATES VALUES (44, "UT", "Utah");
      INSERT INTO STATES VALUES (45, "VT", "Vermont");
      INSERT INTO STATES VALUES (46, "VA", "Virginia");
      INSERT INTO STATES VALUES (47, "WA", "Washington");
      INSERT INTO STATES VALUES (48, "WV", "West Virignia");
      INSERT INTO STATES VALUES (49, "WI", "Wisconsin");
      INSERT INTO STATES VALUES (50, "WY", "Wyoming");
  3. Create and configure the persistence unit
    1. Right-click on the newly created project and select "New", "Entity Classes from Database ..." as shown:


    2. In DataSource, select "New Data Source..." and enter the JNDI name "jndi/states" as shown:


    3. Select "STATES" table in "Available Tables:" and click on "Add >" and then "Next >".
    4. Click on "Create Persistence Unit ...", take all the defaults and click on "Create".
    5. Enter the package name as "server" and click on "Finish".
    6. Expand "Configuration File", open "persistence.xml". Unselect "Include All Entity Classes" check box, click on "Add Class...", select "server.States" and click on OK. The updated view looks like:

    7. Select the XML view and replace <properties/> with

          <properties>
              <property name="toplink.jdbc.user" value="duke"/>
              <property name="toplink.jdbc.password" value="duke"/>
          </properties>

      The username and password values must match the ones specified during database creation. The updated "persistence.xml" looks 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="AutocompletePU" transaction-type="JTA">
          <jta-data-source>jndi/states</jta-data-source>
          <class>server.States</class>
          <exclude-unlisted-classes>true</exclude-unlisted-classes>
          <properties>
            <property name="toplink.jdbc.user" value="duke"/>
            <property name="toplink.jdbc.password" value="duke"/>
          </properties>
        </persistence-unit>
      </persistence>
  4. Create a Servlet to perform the database operations
    1. Right-click on the project, select "New", "Servlet".
    2. Enter the class name as "StatesServlet" and package as "server" and click on "Finish".
    3. Add the following fragment in the beginning of the class:

          EntityManager em;

          @Override
          public void init() throws ServletException {
              EntityManagerFactory emf = Persistence.createEntityManagerFactory("AutocompletePU");
              em = emf.createEntityManager();
          }

      Alternatively, you can use resource injection to populate the EntityManager. Use the following fragment, instead of the above, to achieve that:

          @PersistenceContext(unitName="AutocompletePU")
          EntityManager em;
    4. Replace the commented code in "processRequest" with the following fragment:

                  String abbrev = request.getParameter("abbrev");

                  List<States> list = em.createNamedQuery("States.findByAbbrev").
                          setParameter("abbrev", abbrev).
                          getResultList();

                  if (list.size() > 0) {
                      States s = list.get(0);
                      out.println("Found " + s.getName() + " with abbrev \\"" + abbrev + "\\"");
                  } else {
                      out.println("No matching state found with \\"" + abbrev + "\\"");
                  }

      and fix the imports by right-clicking in editor pane and selecting "Fix Imports".
    5. Right-click on the project and select "Undeploy and Deploy".
Now let's try it!

Invoking "curl http://localhost:8080/Autocomplete/StatesServlet?abbrev=CA" shows the following output on command prompt:

Found California with abbrev "CA"

Alternatively, you can enter this URL in browser as well to see the output as:



Invoking "http://localhost:8080/Autocomplete/StatesServlet?abbrev=CB" shows the output:



Even though MySQL is used as the database in this case, any other database can be easily used for creating this portable PU.

Please leave suggestions on other TOTD (Tip Of The Day) that you'd like to see. A complete archive of all tips is available here.

Technorati: totd mysql jpa persistenceunit netbeans glassfish
Technorati: totd mysql jpa persistenceunit netbeans glassfish jquery autocomplete
About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
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