[JAVAEETUTORIAL-139] Criteria query code snippets use untype-safe metamodel classes Created: 11/Oct/12  Updated: 11/Oct/12  Resolved: 11/Oct/12

Status: Resolved
Project: javaeetutorial
Component/s: doc
Affects Version/s: 6.0.7-5
Fix Version/s: 6.0.7-6

Type: Bug Priority: Major
Reporter: Ian Evans Assignee: Ian Evans
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

From the feedback alias:
I've got a question about an example on creating criteria queries in Part VI Chapter 35 of the Java EE 6 tutorial. Link: http://docs.oracle.com/javaee/6/tutorial/doc/gjivm.html
In the "Querying Relationships Using Joins" section of the chapter, there is an example code that doesn't work for me.

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Metamodel m = em.getMetamodel();
EntityType<Pet> Pet_ = m.entity(Pet.class);

Root<Pet> pet = cq.from(Pet.class);
Join<Pet, Owner> owner = pet.join(Pet_.owners);

Since Pet_ is an instance of class EntityType, it doesn't define any attributes named "owners", which is why Pet_.owners gives an error. Is that a mistake?
Searching through forums I found a thread discussing this problem here http://stackoverflow.com/questions/3879743/jpa-metamodel-strange-inconsistent-example-in-sun-docs
If this is indeed a mistake, could you please correct the code.

The code snippets used dynamic metamodel classes for clarity on where, e.g., Pet_ comes from. But in practice, it gives the impression that this is a good practice for creating queries, which is not the case. The metamodel classes should be statically generated by an annotation processor at development time to make the code compilable and type-safe.



 Comments   
Comment by Ian Evans [ 11/Oct/12 ]

Fixed the code snippets to implicitly use static metamodel classes. The documentation will be updated in the next release of the Tutorial bundle.

Comment by Ian Evans [ 11/Oct/12 ]

And just for clarity, if you're using an annotation processor to statically generate your metamodel classes, the following type-safe query should compile:

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Root<Pet> pet = cq.from(Pet.class);
Join<Pet, Owner> owner = pet.join(Pet_.owners);
Generated at Wed Aug 31 02:55:30 UTC 2016 using JIRA 6.2.3#6260-sha1:63ef1d6dac3f4f4d7db4c1effd405ba38ccdc558.