简体   繁体   中英

JPA Performance: Entity or Entity Id as query parameter?

Let's say there are two entity types: Book (with primary key bookId ) and Author (with primary key authorId ). An author writes 0...n books. So Author is referenced in Book using @ManyToOne .

If we want to retrieve all books written by a certain author, we could do two things in JPQL (eg NamedQuery):

  1. SELECT b FROM Book b WHERE b.author = :author (entity as parameter)
  2. SELECT b FROM Book b WHERE b.author.authorId = :authorId (primary key ID of entity as parameter)

In the first option we have to watch out that the passed object is really of type Author and it already has a primary key.

But: Is there a difference regarding performance in the two options mentioned above? I guess (2) is less expensive, but (1) might be easier to optimize for the JPA provider. Is there a performance test or literature available on this question?

We can assume that the Author instance (whose books we want to search for) has already been loaded (eg to view his/her profile in the response), so it was no additional code writing effort to either pass the whole object or just it's ID to the book search method. But is there a difference in execution speed? Maybe depending on the JPA provider used?

I have tested both queries and the resulting sql was the same.

Answering to the second part of your quesion - there is a lot of relevant literature, but I can particularly recommend Pro JPA 2, 2nd Edition by Mike Keith , Merrick Schincariol .

If you want test queries manually, you can watch SQL-queries resulting from JPA-queries. One approach would be to get know your JPA provider and see what options he delivers for such purpose (eg Hibernate provides option hibernate.show_sql ). The second option (in my opinion - much better) is to use tool such as log4jdbc which is an additional layer (simplifying) between your JDBC driver and Persistence Provider and can log all queries sent to database along with their parameters. It can also measure time spend on each query, so I think it is ideal tool for performance testing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM