Java Reference
In-Depth Information
The method to create a new entity is called create() , it takes an instance of our JPA
entity as its sole argument. This method simply invokes the persist() method on
EntityManager , that takes care of persisting the data on the JPA entity to the database.
For reading, several methods are generated, the findCustomer() method takes the
primary key of the JPA entity we wish to retrieve as its sole parameter, then invokes
the find() method on EntityManager to retrieve the data from the database
and returns an instance of our JPA entity. Several overloaded versions of the
findCustomerEntities() method are generated, these methods allow us to retrieve
more than one JPA entity from the database. The version of this method that does all
the "real work" is the one containing the following signature:
private List<Customer> findCustomerEntities(boolean all, int
maxResults, int firstResult)
The first parameter is a Boolean that we can use to indicate if we want to retrieve
all values in the database. The second parameter allows us to specify the maximum
number of results we wish to retrieve, and the last parameter allows us to indicate
the first result we wish to retrieve. This method uses the Criteria API that was
introduced in JPA 2.0 to build a query programmatically. If the value of the all
parameter is false, then this method sets the maximum number of results and the
first results by passing the appropriate parameters to the setMaxResults() and
setFirstResult( ) method in the Query object.
The method to update existing entities is called edit() , it takes an instance of
our JPA entity as its sole parameter. This method invokes the merge() method on
EntityManager , which updates the data in the database with the data in the JPA
entity it receives as a parameter.
The method to delete an entity is called destroy() , it takes the primary key of
the object to delete as its sole parameter. It first checks to see if the object exists in
the database, if it doesn't, this method throws an exception, otherwise, it deletes
the corresponding row from the database by invoking the remove() method on
EntityManager .
At this point we have all the code we need to persist our entity's properties in the
database, all we need to do to perform CRUD operations involving our JPA entity
is invoke methods on the generated JPA controller from our code.
Automated Generation of JPA Entities
In many projects, we will be working with an existing database schema created
by a database administrator. NetBeans can generate JPA entities from an existing
database schema, saving us a lot of potentially tedious work.
Search WWH ::

Custom Search