Java Reference
In-Depth Information
q.setParameter("id", id);
Edition edition = (Edition)q.getSingleResult();
return edition;
}
Similarly, add methods
getSectionById
and
getArticleById
. In order to
create
Edition
,
Section
, and
Article
instances, add methods
createEdition
,
createSection
, and
createArticle
. The
createEdition
method takes
Edition
entity properties as arguments. In the
createEdition
method, create a
Edition
object and set the values of the different properties:
Edition edition = new Edition();
edition.setId(id);
edition.setPublisher(publisher);
edition.setJournal(journal);
edition.setEdition(edition_date);
Persist the
Edition
entity object using the
persist
method of the
EntityManager
.
The Entity instance data is synchronized with the database when the transaction
with which the entity is associated commits. To synchronize an entity instance with
the database, invoke the
flush
method, which explicitly commits the transaction.
The
flush
method also synchronizes the entity data of the associated entities if the
cascade
element is set to
PERSIST
or
ALL
.
em.persist(edition);
em.flush();
Similarly, in the
createSection
method, create an instance of
Section
from the
argument values and persist the
Section
instance to the database. However, creating
a
Section
instance is different, because the
Section
entity has a many-to-one
relationship with the
Edition
entity. Therefore, we need to add the section to the
associated
Edition
entity instance. One of the
createSection
method's parameters is
editionId
. Retrieve the
Edition
entity instance using the
getEditionById
method:
Edition edition = this.getEditionById(editionId);
Next, merge the state of the
Edition
entity into the current persistence context using
the
merge()
method. Without merging the
Edition
entity instance, we won't be able
to invoke methods on it.
em.merge(edition);
Retrieve a parameterized
List
of
Section
entities from the
Edition
entities using
the
getSections
method, which we defined in the
Edition
entity class. To add a
new
Section
entity to the
List
, create an
ArrayList
from the
List
:
List<Section> sections = edition.getSections();
ArrayList<Section> sectionList =new ArrayList<Section>(sections.
size());
Search WWH ::
Custom Search