Java Reference
In-Depth Information
The
edit()
method is used to update existing entities. 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
destroy()
method is used to delete an entity. It takes the primary key of the
object to be deleted as its sole parameter. It first checks to see if the object exists in
the database. If it doesn't exist, 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, and all we need to do to perform CRUD (short for Create, Read, Update,
and Delete) operations involving our JPA entity is invoke these 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, which saves us a lot of potentially tedious work.
In this section, we will use a custom database schema. In order to create the schema,
we need to execute an SQL script that will create the schema and populate some
of its tables. In order to do this, we need to go to the
Services
window, expand
Databases
, right-click on
JavaDB
, and select the
Create Database...
option.