The NetBeans New File wizards greatly simplify writing boilerplate code. One specific instance is the creation of JPA Controller Classes from an Entity Classes. The class file, or files, written for you will contain all the basic methods of JPA for CRUD operations on the entity or entities that you have. The only small issue is that this class is written for a standalone environment such as what you would find in an environment that does not support Context Dependency Injection. To use this class in a GlassFish environment or other container we have to make some minor changes.
When working with GlassFish the first step is to create the glassfish-resources.xml and then the persistence.xml file. If the database and its tables have not been created yet then this is the time to do this. Now create the Entity Classes from Database, also shown in the New File dialog below.
With all this in place you simply have to create a New File for the project in the category Persistence and the File Type of JPA Controller Classes from Entity Classes.
The next dialog will ask you which entities you wish to have a controller class written for. It should show you the entities you have created for your project. They will appear in the Available Entity Classes box and you use the buttons to move the ones that you want. In my example there is just one entity and I have added it to the Selected Entities Classes box.
In the next step you must select the package name for the classes that will be created for you. You can use a package that already exists.
When you Finish you will see the package you created with a file that has the name of the Entity class followed by JpaController.java. In my example it is FishJpaController.java. You will also find an additional package that ends in exceptions that contains custom Exception classes that provide more informative exception types.
When you open the file you will see the class that has been written for you.
The changes that you have to make are quite straightforward. First, we need to make this class a managed bean and change the EntityManager and UserTransaction into Injected references.
NetBeans will help you in adding the necessary imports. The next step is to delete the constructor. As a managed bean you must have a default constructor. If you dislike not seeing a constructor in your class then you can add an empty one.
Delete the method getEntityManager(). CDI will take care of creating the EntityManager for you.
The last step is to modify every method in the class that has as a first line:
We don’t need to call upon getEntityManager nor do we need to close the EntityManager when we are finished.
The create method:
The query method findFishEntities:
Clean up the rest of the methods and your controller will look like, with my added comments, the following:
You are now ready to use this controller class in your JPA/CDI project.