background image

Creating Queries

<< Persisting Entity Instances | Named Parameters in Queries >>
<< Persisting Entity Instances | Named Parameters in Queries >>

Creating Queries

cascade
element set to REMOVE or ALL in the relationship annotation. If remove is invoked on a
detached entity it will throw an IllegalArgumentException, or the transaction commit will
fail. If remove is invoked on an already removed entity, it will be ignored. The entity's data will
be removed from the data store when the transaction is completed, or as a result of the flush
operation.
public void removeOrder(Integer orderId) {
try {
Order order = em.find(Order.class, orderId);
em.remove(order);
}...
In this example, all LineItem entities associated with the order are also removed, as
Order.getLineItems
has cascade=ALL set in the relationship annotation.
Synchronizing Entity Data to the Database
The state of persistent entities is synchronized to the database when the transaction with which
the entity is associated commits. If a managed entity is in a bidirectional relationship with
another managed entity, the data will be persisted based on the owning side of the relationship.
To force synchronization of the managed entity to the data store, invoke the flush method of
the entity. If the entity is related to another entity, and the relationship annotation has the
cascade
element set to PERSIST or ALL, the related entity's data will be synchronized with the
data store when flush is called.
If the entity is removed, calling flush will remove the entity data from the data store.
Creating Queries
The EntityManager.createQuery and EntityManager.createNamedQuery methods are used
to query the datastore using Java Persistence query language queries. See
Chapter 24,
"Introduction to the Java Persistence API"
for more information on the query language.
The createQuery method is used to create dynamic queries, queries that are defined directly
within an application's business logic.
public List findWithName(String name) {
return em.createQuery(
"SELECT c FROM Customer c WHERE c.name LIKE :custName")
.setParameter(
"custName", name)
.setMaxResults(10)
.getResultList();
}
The createNamedQuery method is used to create static queries, queries that are defined in
metadata using the javax.persistence.NamedQuery annotation. The name element of
Managing Entities
Chapter 24 · Introduction to the Java Persistence API
699