Showing posts with label Persistence. Show all posts
Showing posts with label Persistence. Show all posts

Friday, August 20, 2010

SerialVersionUID Generator for NetBeans

Are creating serialVersionUID values getting you down?

I have been using 's SerialVersionUID Generator For NetBeans tool for a couple of years now. It used to be available for download from the NetBeans update site, but version 1.9.6 for NetBeans 6.9 has not been available. The current version for use with NetBeans 6.9 can be downloaded from here: eu-easyedu-netbeans-svuid-1.9.6.nbm

This fantastic plug-in is great for generating the serialVersionUID values as part of the Serializable interface contract. If you are doing work with Java Persistence API (JPA) you will definitely want this little plug-in to make your life easier.

  1. You will get a hint on the class about the missing serialVersionUID if you implement Serializable.
  2. Right-click on the class and pick from two options:


    • Add default serialVersionUID
    • Add generated serialVersionUID
Enhanced by Zemanta

Saturday, March 01, 2008

JPA and Web Examples using Project Woodstock and Netbeans

I was looking at some of the examples from the Netbeans site and trying to find a basic example to demonstrate. After looking at the examples I found on the web, I thought I would create a quick example myself.

First I created a project in Netbeans. I picked Java Library. Then I selected create entity classes from database and used the sample JavaDB database that comes with Netbeans. It prompted me to create the persistence.xml and I accepted the defaults.

Next I created a Web project in Netbeans. During the project creation wizard, I selected Visual JSF to include the JSF and Woodstock libraries.

Next I clicked on the properties for the project and added my library to the project.

Next I created a created a new persistence.xml file. After it was created, I modified it so that it would include the specific entity classes that I created in the library project.

Note: This is required otherwise the entity classes will not be detected.


Next I added this code snippet to SessionBean1

This fetches my data so that I can display it later in a table.

Next I compile the project (no deployment yet). This refreshes the beans so that I can manipulate them visually.

Next I create a table on Page1 from the palette. I right click the table and select binding and point it from the DefaultTableProvider to customers in the SessionBean.

Now I deploy it. Poof the magic is complete.

The link to my example Netbeans 6.5.1 project on Bitbucket: SamplePersistenceWeb

Sunday, February 10, 2008

Book Review: Java EE 5 Development using GlassFish Application Server

Let me start by saying that I am glad that Kshipra Singh, Packt Publishing, contacted me to see if I would review the book. I would also like to note that I am glad that David R. Heffelfinger wrote the book. We need more books on projects like GlassFish.

My overall opinion of the book is good. The book is very well written, and the code examples in the book work. Working code examples are the number one criteria for me. The code examples start with some examples in Chapter 2 that are used throughout the remainder of the book. This provides a coherent flow through the book. You may also download the code examples from the Packt Publishing support site.

I would recommend it as a book to have on your development bookshelf (3/5 stars).


The book claims to be the complete guide to installing and configuring GlassFish. I would not give it that much credit. There is room for more extensive books on GlassFish. There are a number of topics that are very general and have nothing to do with the actual configuration of the server. A better book summary would be a guide to installing, configuring, and developing applications for the Glassfish server. It is really a Java EE 5 tutorial which features Glassfish.

As a book on GlassFish, it is very light in its coverage. As a tutorial for developers acquainting themselves with Java EE 5 and deployment on Glassfish it is very good. In my opinion it is targeted at developers familiar with J2EE who want to switch to JEE5, or junior developers trying to get a better comprehension of the EE environment. It is not for novice programmers.

Chapter 1

Getting Started with GlassFish


This chapter covers getting and installing GlassFish. It is very basic, but will get you up and running. It also includes how to set up your JNDI database connections. The majority of this information can be readily found on the GlassFish site on Java.net. There is a good example of how to set up multiple domains on GlassFish which is not easily gleaned from the site. There is a chart which shows how the --portbase command line option is used to set the ports on which GlassFish services connections. This provides the best explanation for this command line option and graphically depicts what the results are.

Chapter 2

Servlet Development and Deployment

This chapter is a very basic tutorial on servlet technology. It includes writing a simple servlets, web.xml files, and deployment file layout (war files). It includes some examples on html forms, request forwarding and response re-direction. There is nothing GlassFish specific and the files will just as easily deploy on Apache Tomcat unaltered. There is one item of note which is sun-web.xml related which has to do with how to change the context root. This is used if you do not want the default deployment context to match the name of the war file.

Chapter 3

JavaServer Pages

This chapter again has a basic tutorial on JSP technologies. There is a really good example of creating custom JSP tags and how to use them. Again, there is nothing that would prevent the war files from being deployed on Apache Tomcat. I wish that the author would have covered Unified Expression Language (EL) in more detail. It is more central to this technology on JEE5 platforms.

Chapter 4

Database Connectivity

This is the first chapter which covers a really important topic in the enhanced JEE5 database access functionality, new Java Persistence API (JPA), and its reference application server (GlassFish). The first example shows a servlet and how to connect to a database using the old form of JNDI lookup without resource injection. The next example shows the simplified version using resource injection of the DataSource. This removes all the plumbing of fetching our data source.

The next section covers Java Persistence API (JPA) and provides an in-depth tutorial. This is a key concept in JEE5. It introduces the Entity annotation on a POJO to convert it to a persistable object. The simple example that follows it demonstrates correctly how to to use JPA in a non-thread safe environment of a servlet using a UserTransaction. It also covers the persistence.xml file.

This chapter is a must for anyone who wants to learn JPA. The sections on entity relationships, and composite primary keys are done extremely well.

This chapter concludes on Java Persistence Query Language (JPQL) which is the follow-on from EJB QL.It is very light. I wish the author would have covered this very important topic in more detail. That being stated, the code sample is a perfect example.

The book is worth purchasing for this chapter alone.

Chapter 5

JSP Standard Tag Library

This chapter is a basic tutorial on the JSTL. I found a number of syntax mistakes, which were submitted back to Packt. The SQL JST Tag Library is covered. It was very simple. There is one note on No Suitable Driver SQL Exception which is often a hard thing to track down.There is nothing substantive about this chapter.

Chapter 6

JavaServer Faces

This is another JEE5 technology that needs more coverage in general. This chapter provides a good foundation on the reference JSF implementation. It is very well written. I am a big advocate of JSF and thoroughly examined this chapter.

The introductory examples are well done and give a good overview of the technology. The example Customer bean is the same bean that is used in JPA in chapter 4. This shows the consistency and flow between chapters. In this case we use the bean as a managed bean in the JSF context.

The chapter also explains the changes needed in the web.xml file for JSF.

The section on validators is very well done. It includes an example using the Apache Commons Validator framework. The point is to show that you should look for good validators rather than creating your own. Roll your own for domain specific requirements. It also covers validator methods in some detail. It also covers another useful utility from the Apache Commons Language Library.

There is a section on customizing messages that provide feedback to the user on various validation errors. It contains a section on how to modify the default messages on GlassFish. It is nice to know how to do this, but I would encourage users NOT to do it. You can Google for the default messages to see what they mean. If you change them, that option no longer exists. Also it is not intuitively obvious where the message is coming from. There is another example using a message bundle for your customized messages. I would HIGHLY recommend using this method.

There is a wonderful section on integrating JPA and JSF. This is a must read, and covers the practical side of JSF and JPA. It uses a model-view-controller paradigm. It shows how to use the JPA as a managed bean that gets set from the JSF page and saved/modified from the controller servlet. This is an excellent example of how to do it.

Finally, the chapter closes with a reference to the JSF Core components. I personally believe that this should have been an appendix. It really does not contribute to the flow of the book, or chapter. I went through the reference with a fine-toothed comb. The examples are really clean. I submitted some errata for the section, but it was done very well.

This is another chapter that makes the book worth purchasing.

Chapter 7

Java Messaging Service

This is a chapter that has a very specific setup for GlassFish. Most of the previous chapters were general enough on the specific technologies that they could be used on Apache Tomcat. The JMS server setup which is covered for GlassFish is very specific to the server.

The first part of the chapter covers how to set up the JMS connection factory, and JMS destination resources (Queue and Topic).

The examples that follow are very well done on how to use the various topics and queues.

I was really impressed with the authors examples. They were clean. I questioned one of the examples on durable topics, only to discover that the author was correct.

Chapter 8

Security

This chapter seems out of sequence. The Enterprise Java Beans (EJB) and Web Services chapters follow it. I would have recommended it to follow those two chapters. The author does cover securing EJBs and web services which require a security pre-cursor, but it seems to disrupt the flow of the book.

This chapter was a big disappointment. The topic is covered in minimal detail. This chapter is so important that it needs more coverage.

Here are some of the major omissions:
  • Setting up a SSL/TLS connection using a self-signed certificate, or CA certificate
  • Setting up an LDAP realm
  • Optional attributes for the various realms
There is coverage of the various realms with a focus on file and JDBC.

The JDBC realm is complex. I understand that setting up a JDBC realm requires more work, but I am not sure how many people would use this type of realm.

The file realm coverage is detailed, but I am not sure that any enterprise would use this arrangement. It is not scalable.

The example login form using j_security_check is very useful, as well as, the example LogoutServlet.

The certificate realm is covered in fine detail. It is one of the best examples of how to configure this setup.

The LDAP and Solaris realms are weak. There is nothing here but a placeholder explanation. I can imagine that most enterprise users will have an LDAP domain that they will connect to. This topic could have included an example using OpenLDAP with its configuration in an appendix, or using openDS.

The JDBC realm setup has a number of serious errors which were reported as errata.

The section on defining custom realms is ok. It glosses a topic which requires more detail. I would HIGHLY recommend using a pre-defined realm instead of defining your own.

Chapter 9

Enterprise JavaBeans


This chapter provides a good tutorial on the JEE5 EJB 3.0 technologies. It covers the use of the new @Stateless, @Stateful, and @MessageDriven bean annotations.

There is an excellent example of using a stateless session bean as the Data Access Object (DAO) controller for JPA. It is well done. This is followed by another excellent example of how to use DAO EJB in a web application using resource injection.

Transactions are covered in very good detail. There is an excellent table which explains the various types of container managed transactions, and the @TransactionAttribute annotation.

The real jewel of this chapter, in my opinion, is the section on Bean-Managed Transactions which includes an excellent example with all of the correct annotations.

There is a section on the new EJB Timer service. I wish they would have included a practical example, but the included example gives you a feel on how it works.

EJB Security is covered lightly. There is a great note about automatically matching Roles to Security Groups on GlassFish. It is a very well hidden feature, and one which I was not aware of. This simplifies some of the security mapping and is a great time saver.

This is another good chapter.

Chapter 10

Web Services


This chapter provides a good tutorial on Java API for XML for Web Services (JAX-WS). It has some simple examples, and demonstrates the great GlassFish web service testing facility built into the platform. The tester is a web based page which allows you to enter values and see the results, as well as, the SOAP messages (Request and Response). This is a real time saver and can help a developer check the expected messages quickly.

The chapter includes a section on how to include attachments and expose EJBs as web services.

The chapter concludes on a light coverage of web service security.

Chapter 11

Beyond Java EE

This chapter covers some alternative and complementary technologies for JSF like Facelets, Facelets Templating, Ajax4jsf (providing AJAX functionality to JSF applications), and Seam. The chapter includes some sample applications and how to install and set up these technologies.

Appendices

The appendices include coverage of using JavaMail and integrating GlassFish into various IDEs.

Again, I would recommend this book for anyone who wants to learn the basics of JEE5 programming with GlassFish.

Thursday, May 24, 2007

Java EE5 Persistence and Generics

The new Java EE5 Persistence provides some really cool functionality. It was designed with backwards compatibility in mind. This has resulted in some interesting issues. For example if you perform a Query which returns more than one object, the objects are returned as a List. The List is a very generic Object List. Generally we know that if we perform a query that it should return specific types back to us. For example we expect it to return a collection of the entity itself. If we accept the default which is to return a List, the compiler will report an unchecked warning. If you use the -Xlint:unchecked option, it will point out that we are getting a generic Object List and it can not verify the type of the Object.

The Solution... is simple...

When you get the List back cast it into a specific type. For example:

Query q = em.createQuery("SELECT OBJECT(p) FROM PuzzleBox p");
List puzzles = q.getResultList();
A rather elegent solution... alternatively you can have a more complex version such as

ArrayList puzzles = new ArrayList(q.getResultList);

This works because an ArrayList can accept a Collection as noted in the Javadocs:

ArrayList(Collection<? extends E> c)


The last and most inelegent solution is to annotate the methods which use the generic List of Objects to suppress the complier warnings with a @SuppressWarnings("unchecked") annotation.

Java EE5 Persistence Annotations for Web Applications

I am taking the time to create some cliff notes from a wonderful presentation at JavaOne TS-4593 "Guidelines, Tips, and Tricks for Using Java EE5 from Java Blueprints" (Inderjeet Singh, Marina Vatkina, et.al.) and an article in JavaOne Today by Rick Palkovic. When the technical sessions are released to the general public, it would be a good read for any Java EE5 developer.

The problem has to do with thread safety on web applications. If you are using servlets, or a technology based on servlets like JSF, you must consider thread safety for persistence. A common injection is to use the container managed persistence context. This usually takes the following form

@PersistenceContext(unitName="myContext")
private EntityManager em;

The problem is this is NOT thread safe if used in a servlet. A servlet processes many requests and the container handles many requests. Even if you use an injection to get a UserTransaction, it lulls the programmer into a false sense of safety.

In their talk, they mentioned four methods to ensure thread safety on servlet based technologies
  • Use a request-scoped bean Java Server Faces. The life of the bean is a single transaction.
  • Use class level annotations with JNDI lookups
  • Use a @Resource annotation
  • Use the "old style" JNDI InitialContext lookup method
Here is an example of the "old-style" method:

public EntityManager getEntityManager() throws NamingException {
Context ic = new InitialContext();
return (EntityManager) ic.lookup("java:comp/env/EM");
}
Another alternative is to use the @PersistenceUnit annotation to get an EntityManagerFactory. The EntityManagerFactory is a thread-safe object. From the factory we create the EntityManager. This is also thread-safe since it creates a new EntityManager per call.

@PersistenceUnit(unitName="myContextPU")
private EntityManagerFactory emf;

public EntityManager getEntityManager() {
return emf.createEntityManager();
}
These methods should help the developer maintain thread-safety.

Sunday, October 29, 2006

Persistence Unit or Persistence Context?

Which to use for a particular application depends entirely on the environment, or preference.

  • @PersistenceUnit annotation is used in J5SE applications to handle Java Persistence API (JPA) persistence management. You may use a PeristenceUnit in an application inside a container, but it must be managed by the developer instead of the container.
  • @PersistenceContext annotation is used for Container Managed Persistence (CMP). This relieves the developer of having to worry about connection management.

Popular Posts