Java Reference
In-Depth Information
The code gets all instances of Category in the system and makes sure that all Item s
related to the Seller being deleted are removed from referencing List s first. It then
proceeds with removing the Seller , cascading the remove to the related Item s.
Not surprisingly, the remove method must be called from a transactional context or it'll
throw a TransactionRequiredException . Also, trying to remove an already re-
moved entity will raise an IllegalArgumentException .
Having finished the basic EntityManager CRUD operations, let's now move on to the
two remaining major persistence operations: flushing data to the database and refreshing
from the database.
10.3. Entity queries
Queries are as important as storing the data. Once you get the data into a database, you need
a mechanism to query the data. With JPA you have several different options for querying
data, ranging from JQL to the Criteria API, native SQL queries, and stored procedure quer-
ies. Each has its own advantages and disadvantages depending on what you're trying to do.
Up to this point you've retrieved entities using the find method on an EntityManager
instance. The find method enables you to perform a query that retrieves an entity using
its primary key. Although this is extremely useful, most of the time you want to search on
something else. To do so, you need to make use of the javax .persistence.Query
interface. This interface is used to define, bind parameters, execute, and paginate.
There are several different types of queries that we'll examine starting in this chapter and
continuing in the next chapter:
javax.persistence.Query— Represents either a JPQL or native SQL
query. If a query is typed, a javax.persistence.TypeQuery<T> is re-
turned, thus eliminating the need to cast results.
javax.persistence.StoredProcedureQuery— Represents a query that
invokes a stored procedure.
javax.persistence.criteria.CriteriaQuery— Represents a query
that's constructed using the meta-model.
Search WWH ::




Custom Search