Retrieving objects

Figure 846. ReadStudyCourseById retrieval by primary key Slide presentation Create comment in forum
final EntityManagerFactory factory = Persistence.createEntityManagerFactory(
   "strategy_none" );

final StudyCourse studyCourse =
  entityManager.find (StudyCourse.class, "CSM" );

System.out.println("Read '" + studyCourse + "'"); 
Read 'Computer Science and Media(CSM)'

strategy_none refers to the second persistence unit definition in resources/persistence.xml:

<persistence-unit name = "strategy_none">
           ... <!-- JDBC related stuff omitted-->
    <property name = "javax.persistence.schema-generation.database.action"
             value = "none"/>

JPA will not touch the database schema.

The EntityManager.find(...) method tries to retrieve a database record corresponding to an @Entity annotated instance of the desired Class value.

The desired study course's primary key value.

Print study course's value.


Since the transaction has been committed changes to studyCourse are transient and won't be propagated to the database until being attached to another transaction.

Figure 847. Retrieving all instances Slide presentation Create comment in forum
final Query query = entityManager.
  createQuery("SELECT S FROM StudyCourse S" );

final List<StudyCourse> studyCourses = query.getResultList(); -> "Read '" + s + "'").

A JPQL statement resembling SQL but actually retrieving Java objects rather than attribute value composed database records.

Notice: List in favour of Set respecting database ordering.

Unchecked assignment java.util.List to java.util.List<StudyCourse>.

Figure 848. Type conversion problems Slide presentation Create comment in forum
final Query query = entityManager.createQuery(
     "SELECT S.shortName FROM StudyCourse AS S");
final List<StudyCourse> studyCourses = query.getResultList();

try { -> "Read '" + s + "'").
} finally {
Exception in thread "main" java.lang.ClassCastException: java.lang.String
  cannot be cast to de.hdm_stuttgart.mi.sda1.model.StudyCourse
 at de.hdm_stuttgart.mi.sda1.JqlTypeViolation.main(

try block required for later cleanup.

The culprit causing the ClassCastException.

Cleaning up persistence context in presence of an exception.

Figure 849. Reading shortName values Slide presentation Create comment in forum
final List<String > studyCourseShortNames = entityManager.
  createQuery("SELECT S.shortName  FROM StudyCourse AS S").
  map(s -> "Read '" + s  + "'").
Read 'CSM'

Corresponding to s.shortName our result will be a list of strings rather than a list of StudyCourse instances.

The attribute shortName from class StudyCourse.

s already represents an instance of String thus no toString() conversion is being required.