Skip to main content

Elvis, Meet NetBeans

Posted by bleonard on March 28, 2006 at 1:31 PM PST

I was reviewing Cay S. Hortsmann's article, Elvis Meets GlassFish, and I have to say I REALLY like his approach. However, Elvis would be even happier using the NetBeans IDE to create his application (Cay does mention NetBeans' upcoming support for EJB3, but choose not to use it because it's still under development).As a comparison, I'll create the same application using the NetBeans 5.5 Preview.

Getting Started

  • Download and install the NetBeans 5.5 Preview. This will install both NetBeans and if needed, the GlassFish Application Server.

Step 1: Create the Project

This step creates the project infrastructure for you, placing files in the appropriate locations based on Java Blueprints Guidelines. All the necessary Ant scripts for building, packaging and deploying the application are also created for you.

  1. Start the NetBeans 5.5 Preview
  2. Choose File > New Project and create and Enterprise Application (found in the Enterprise Category)
  3. Name the project Quiz and click Finish. You'll end up with the following 3 projects:







    The Quiz project represents our EAR file. Quiz contains 2 sub-projects, Quiz-EJBModule and Quiz-WebModule, representing our jar and war file respectively.

Step 2: Create the Entity Classes

The Quiz application has 3 entity classes, Quiz, Question and Choice as depicted here:




Create the Choice Entity

  1. Right-click the Quiz-EJBModule and choose New > Entity Class.
  2. Set the Class Name to Choice and the Package to elvis.entity. Notice the wizard warns you that a persistence unit is needed to persist entity classes.







    Let's go ahead and create the Persistence Unit at this time.
  3. Click the Create Persistence Unit button and then OK to select the defaults.
  4. Click Finish to create the Choice entity class. Choice.java opens in the editor. Notice it's already properly annotated for us:




  5. Complete Choice.java by adding the text attribute:



    private String text;
  6. You can then easily create a getter and setter for text by moving to a blank line and pressing Ctrl+Space:




Create the Question Entity

  1. Follow the steps above to create the Question entity class in the elvis.entity package.
  2. Add the following attributes:


    private String text;
    private Collection<Choice> choices;
    private String answer;
  3. Press Alt+Shift+F to add the import for java.util.Collection.
  4. When there's a need to create getters and setter for multiple fields, we can more quickly do this using refactoring. Right-click the source and choose Refactor > Encapsulate Fields, which will bring up the Encapsulate Fields wizard:




  5. Click Next to add the getters and setters.
  6. Add the @OneToMany annotation above the getChoices() getter:



Create the Quiz Entity

  1. Create the Quiz entity class in the elvis.entity package.
  2. Add the following attributes:



    private String title;
    private Collection<Question> questions;

       
  3. Press Alt+Shift+F to add the import for java.util.Collection.
  4. Create the getters and setters for title and questions.
  5. Add the @OneToMany annotation before the getQuestions() getter.
  6. Add the following to String method (which will be used by the client):



    public String toString() {
        return getClass().getName()+"[id="+id+",title="+title+",questions="+questions+"]";
    }

See All We've Accomplished Thus Far

Let's see what the GlassFish EJB3 Container does with our entity classes.

  1. Choose Tools > Derby Database > Start Derby Server
  2. Right-click the Quiz project and select Deploy Project. NetBeans packages the ear, starts the application server and deploys the project.
  3. Switch to the Runtime tab and expand the Databases node.
  4. Right-click the jdbc:derby://localhost:1527/sun-appserv-samples;create=true node and select Connect. The Password is App.
  5. Expand the Tables node and you'll see the tables created by the container:




This really demonstrates the power of EJB3. By simply adding an @Entity annotation to 3 plain old Java objects, we are easily able to represent these objects as tables in a relational database.




Step 2: Create the Session Classes

The session classes provide the access or our entity classes. We'll define that access through a Java interface and then provide the implementation for that interface.

  1. Right-click the Quiz-EJBModule and select New > Session Bean
  2. Set the EJB Name to Test and put it in the package elvis.session.
  3. Leave the Session Type as Stateless and select the Remote Interface as well as the Local.
  4. Click Finish. NetBeans has created the TestBean implementation class as well as the local and remote interfaces, again, all properly annotated for us:




  5. Open TestRemote.java and add the following methods to the interface:



    long makeQuiz();
    Object getQuiz(long id);
  6. Save TestRemove.java and switch back to TestBean.java.
  7. Place your cursor on the class declaration and click the light-bulb that appears to implement the interface methods:




  8. The makeQuiz() and getQuiz() methods use an EntityManager to access our entity classes. We associate the EntityManager with a PersistenceContext using an annotation as follows.



    @PersistenceContext() private EntityManager em;


    If you recall, we created the persistence context when we created our first entity class. The persistence context contains the information on how to connect to the database. You'll find the persistence.xml under the Configuration Files node of the Quiz-EJBModule project.
  9. Add the following to the makeQuiz() method:



        Quiz q = new Quiz();
        q.setTitle("A Java Trivia Quiz");
        ArrayList<Question> questions = new ArrayList<Question>();
           
        questions.add(makeQuestion(
             "What trademarked slogan describes Java development? Write once, ...",
             "run anywhere", "debug everywhere", "run many times", "read anywhere"));
        questions.add(makeQuestion(
             "What are the first 4 bytes of every class file (in hexadecimal)?",
             "0xCAFEBABE", "JAVA", "0xFFFE or 0xFEFF", "PK"));
        questions.add(makeQuestion(
             "Which Java keyword is used to define a subclass?",
             "extends", "sub", "super", "implements"));
        questions.add(makeQuestion(
             "What was the original name of the Java programming language?",
             "Oak", "J++", "*7", "!C++"));
        questions.add(makeQuestion(
             "Which Java class describes a point in time?",
             "java.util.Date", "java.util.Time", "java.sql.Time", "java.lang.TimeOfDay"));
        q.setQuestions(questions);
        em.persist(q);
        return q.getId();
  10. Press Alt+Shift+F to fix the imports.
  11. Add the following makeQuestion method:



    private Question makeQuestion(String text, String answer, String... otherChoices) {
        Question q = new Question();
        q.setText(text);
        q.setAnswer(answer);
        ArrayList<Choice> choices = new ArrayList<Choice>();
        Choice c = new Choice();
        c.setText(answer);
        choices.add(c);
        em.persist(c);
        for (String choiceText : otherChoices) {
            c = new Choice();
            c.setText(choiceText);
            em.persist(c);
            choices.add(c);
        }
        q.setChoices(choices);
        em.persist(q);
        return q;
    }
  12. Press Alt+Shift+F to fix the imports.
  13. Add the following to the getQuiz() method:



        Query q = em.createQuery("SELECT x FROM Quiz x WHERE x.id = :id").setParameter("id", id);
        return q.getSingleResult().toString();
  14. Press Alt+Shift+F to fix the imports.

Step 3: Package and Deploy the Application

Well, hopefully we already know by now that one of the beauties of using NetBeans is that all of the file placement, packaging and deployment is handled for you. Simply right-click the Quiz Project and choose Deploy Project.

Step 4: Accessing Session Beans

Cay uses a command-line Java program to access the session beans, so I'll do the same here. In the future I'll create a web interface to this application as well (which is why I also created the local session bean interface).

  1. Create a new General Java Application project, QuizClient. Set the Main Class to elvis.client.Client.
  2. QuizClient needs access to several libraries:
    • The GlassFish Libraries. Right-click the Libraries node and choose Add Jar/Folder. Browse to your /lib and select appserv-rt.jar and javaee.jar.
    • The Quiz session interface. Right-click the Libraries node and choose Add Jar/Folder. Browse to your /Quiz/Quiz-ejb/build directory and select ear-module.
  3. Add the following to main, including the throws clause:



        public static void main(String[] args) throws Exception {
            InitialContext ctx = new InitialContext();
            TestRemote test = (TestRemote) ctx.lookup(TestRemote.class.getName());
            long id = test.makeQuiz();
            System.out.println(test.getQuiz(id));
        }

       
  4. Press Alt+Shift+F to fix the imports.
  5. Press F6 to run the QuizClient. You should see the following in the Output window:




Step 5: Spying on the Database

NetBeans has an excellent database explorer, so there's no need to download another tool.

  1. Switch to the Runtime tab, right-click the QUESTION table and select View Data.




Related Topics >>