With the T getReference and the T find method, JPA’s EntityManager seems to provide 2 methods that do the same. Both of them seem to get an entity by its primary key from the database.
There obviously is a difference between the 2 methods. An established and well-defined API like the Java Persistence API doesn’t contain 2 methods that do exactly the same. And I have to admit, that depending on how you use the object returned by the getReference method; you might not notice the difference in your current application. But that doesn’t mean that you don’t need to be familiar with it.
Using the getReference method can improve the performance of some of your write operations. It can also delay the execution of read operations, which might cause unexpected exceptions at runtime. This shows how important it is to understand the differences between the find and getReference method and that you need to know when to use which of them.
Links mentioned:
Hibernate Proxies – Why they’re used and how to unproxy them: https://thorben-janssen.com/hibernate-proxies/
Eager vs Lazy Loading in Hibernate and JPA: https://thorben-janssen.com/entity-mappings-introduction-jpa-fetchtypes/
Like my channel? Subscribe!
➜ http://bit.ly/2cUsid8
Join the free Member Library:
https://goo.gl/dtyIIC
Read the accompanying post: https://thorben-janssen.com/jpa-getreference/
Want to connect with me?
Blog: https://thorben-janssen.com/
Twitter: https://twitter.com/thjanssen123
Facebook: https://www.facebook.com/thorbenjanssenofficial
Linkedin: https://www.linkedin.com/in/thorbenjanssen
#JPA #Hibernate #getReference()
3 Comments