The Query By Example feature builds a Post entity that is going to be used as a reference when matching the properties given by the provided ExampleMatcher specification. Using a fidnBy query to fetch an entity to check for its existence is a waste of resources since not only you cannot use a covering query in case you have an index on the slug property, but you have to send the entity result set over the network to the JDBC Driver, only to silently discard it.Ĭhecking existence using Query By ExampleĪnother very popular, but inefficient, way to check existence is using the Query By Example feature: P.slug = 'high-performance-java-persistence' The problem with this approach is that an entity is actually fetched just for the sake of checking whether there is an associated record for the provided filtering criteria: PostRepository.findBySlug(slug).isPresent() Since the findBySlug method is meant for fetching a Post entity, I’ve seen cases when this method was used for equality checks, like in the following example: Spring Data provides a way to derive queries from method names, so you can write a findBy query to emulate existence, like interface PostRepository How NOT to write an Exists query with Spring Dataįirst, let’s start with various methods which, while popular, you are better off avoiding. The slug property is a business key, meaning it has a unique constraint, and, for this reason, we can annotate it with the Hibernate = "post", Let’s assume we have the following Post entity: While doing consulting, I’ve encountered several options that are commonly used without developers knowing there are actually better alternatives. In this article, I’m going to show you the best way to write a Spring Data Exists Query that’s efficient from an SQL perspective. So, enjoy spending your time on the things you love rather than fixing performance issues in your production system on a Saturday night! Well, Hypersistence Optimizer is that tool!Īnd it works with Spring Boot, Spring Framework, Jakarta EE, Java EE, Quarkus, or Play Framework. Follow having a tool that can automatically detect JPA and Hibernate performance issues.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |