7 Tips to improve your Hibernate performance

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

I'm so grateful that Hibernate is saving me all this time mapping relations to objects. Now I can spend it watching videos like these and performance tuning Hibernate.

👍︎︎ 17 👤︎︎ u/[deleted] 📅︎︎ Jan 26 2017 🗫︎ replies

Best performance tip. Please don't use things like hibernate.

👍︎︎ 9 👤︎︎ u/nimtiazm 📅︎︎ Jan 26 2017 🗫︎ replies

Quality tips shared, i will keep myself busy in reading hibernate blogs too.

👍︎︎ 1 👤︎︎ u/Ashish_Bishtt 📅︎︎ Jan 28 2017 🗫︎ replies
Captions
hi I'm Tommy unconfirmed thoughts on Javadoc today I want to talk about hibernate performance tuning and gives you seven tips to avoid common pitfalls and to get the best performance out of your persistence tier let's get started tip number one find performance issues with hibernate statistics finding the performance issues as early as possible is always the most important part the main problem with that is that most of them are hardly visible on a small test system they are caused by small inefficiencies which are not visible if you test with a small test database and only one per user on your local test system that changes dramatically as soon as you deploy these issues to production while the performance issues are difficult to find on your test system you can still see the inefficiencies if you have a look at the internet statistics one way to do this is to activate hibernate statistics component by setting the system property hibernate or generate statistics to true or by setting this parameter in the position study XML file you should also set the log level for october netstat to debug to get a few additional information hibernate will then collect internet statistics about each session like the number of perform queries and the time spent for them or the number of cache hits and misses let's have a quick look at an example in this example I activate the statistics in the resistance dot XML file you can see it here hibernate will now collect a lot of information about each session and write a log message with the most important metrics when it closes the session I prepared this simple test case to show you the log output as you can see it's quite simple it just fetches the list of author entities from the database and writes lock message for each of them with the first and last name and the number of books she's written when you see this code for the first time you probably expect that hibernate performs only one query to get all author entities but that's not the case as you will see in these statistics here you can see hibernates lock message with the most important session metrics you can find the number of SQL statements and the time spent for their preparation and execution here as you can see hibernate executed 12 queries to get all the required information one query to fetch eleven author entities and eleven additional queries to get the books each of them has written that is a typical example of n plus one select issue it's the most common hibernate related performance problem if you want to learn more about it I have a free video course in which I'll show you how to find and fix these issues I add a link to it to the video description okay before I end this video let's have a quick look at hibernate statistics API you already know this part from the previous example I use the same query and block messages as before then I unwrap hibernate session factory from JPAC entitymanager factory and call the get statistics method that returns the statistics interface which provides you access to detailed information about the current session you can for example use it to get the number of executed queries and the number of fetched collections output the statistics API provides more details than hibernates log message the log message draft told you that hibernate executed twelve statements within this session when you use the statistics api you can see that one of these statements was a query and did the other eleven statements were performed to fetch collections from the database in this example hibernate had to initialize the book association for each author tip number two improve flow Cleary's slow queries are not real JPA or hibernate issue this kind of performance problem secures with every framework even with plain SQL / JDBC you need to analyze and fix them on the SQL and database level when you do this you will quite often recognized that you cannot implement the more complex or optimized SQL queries with jaql or the criteria api in these cases you need to use a native query to perform a native SQL statement it allows you to use all SQL and proprietary database features I explained native queries in great detail in another video let's have a quick look at a small part of it and if you are interested you can watch that video afterwards I put a link to it into the video description creating a dynamic native query is quite simple the entitymanager interface provides a method called create native query fluid this method returns an implementation of the equilibria interface which is the same as if you call the create query method to create a JDK equity the code snippet on the slide shows the simple example in which I use the native query to select the first and last names from the author table and I know there's no need to do this with the native SQL query I could use the standard shape you click view for this but I want to focus on the JPA part and not bother you with a complex SQL query the resistance provider does not pass the SQL statement so you can use any SQL a statement that is supported by your database and one of my recent projects for example I used it to query post create create specific JSP columns with hibernate and map the queries ID to pojos and entities okay let's get into the IDE and executing native cuy here you can see the same query of Ashoke on the slide it selects the first and last name of an author you can use the query in the same way as any jpq query I didn't provide any mapping information for the result and so the entity manager returns a list of object arrays which you need to handle afterwards instead of netting the without yourself you can also provide additional mapping information and let the entity manager do the mapping for you here you can see the FBI query and the log messages written by the test case as I said hibernate doesn't pass native queries it just takes the query and executed that allows you to use all SQL features supported by your database okay that's all for now as I said I provide you a link to that video in the video description so that you can watch it if you want to dive deeper into native queries tip number three true throughout fetch type another common issue is the usage of the wrong fetch type it is specified in the entity mapping and defines when an association gets loaded search type eager for the hibernate to initialize the association when it loads the entity that can reside in a huge number of additional queries search that lazy on the other hand give hibernate the option to fetch the association only when you use it okay that doesn't seem to be complicated but the main problem is that you can only define one fetch type for an association hibernate uses it every time it fetches an entity from the database so you either have only queries that have to request the same Association which I doubt or you are not able to define the best page type for all of them you need to choose the best default search type which in almost all cases is fetch type lazy tip number four use query specific fetching as I explained in tip 3 you are not able to define the optimal fetch type for all queries in the entity mapping the good thing is that you don't need to do that you only need to specify the optimal default behavior which in most cases is fetch tag lazy you can then define either fetching for the queries for which you need it that allows you to prevent lazy initialization exceptions and to avoid n plus 1 select issues you have multiple options to define either fetching for query you can either do this as part of your JDK a statement by using fetch join instead of join another option is to use the named entity graph that is one of the new features introduced in JPA 2.1 and allows you to define a graph of entities that hibernate shall fetch from the database if you need a more dynamic way to define your entity graph you can also do this by a Java API let's jump into the IDE and have a quick look at the different options here you can see an example with a simple APK query that selects the author entity with ID 1 then I commit the transaction and close the session before I call the get books method on the selected author this is the Guetta method of a lazily fetched relationship and hibernate we'll have to initialize it let's run this test and see what happens as you can see here the test favorites with lazy initialization exception because hibernate isn't able to fetch the related book entities without a hibernate session so let's add a joint edge statement to the query to fetch the related entities you can see the change clearly here I added a joint fetch statement for the book relationship this time hibernate initialize the relationship when it got the author entity from the database it did that with this ask you a statement that selects the required columns from the author and the book table the facts join is a good option if you want to define the ego fetching for one query if you are looking for the usable solution which you can use with multiple queries named entity graphs are the better option it's an annotation based approach to specifying a graph of entities which hibernate shell fetch from the database here you can see an example of a simple named graph I use the name graft or author books and define a node for the books attribute that has hibernate to initialize the books attribute when it loads the entity you can provide multiple named attribute nodes and names up graph if you need to define more complex graph the only thing you now need to do is to tell hibernate to use this graph for your query you do that in two steps first you need to call the create entity graph message of the entity manager with the name of the graph to instantiate an entity graph you can then use this graph instance as a query hint can see the test successful hibernate generated the same SQL query as in the previous example your third option for a clue a specific ETA fetching is to define the entity graph by a Java API that is useful if you want to specify the graph based on user input here you can see the definition of the same graph as I showed you in the previous example I instantiate an entity graph for the author entity and add an attribute note for the Box attribute of the author entity and then I provide the graph to the query with the same hint as before this test was also successful hibernate use the entity graph to generate the same SQL query as in the two previous examples tip number five that the database has data heavy operation okay this is a tip that most Java developers don't really like because it moves parts of the business logic from the business here into the database and don't get me wrong there are good reasons to choose Java to implement the business logic and a database to store the data but you also have to consider that a database is very efficient in ending huge data sets it can therefore be a good idea to move not to complex and varied data heavy operations into the database there are multiple ways to do that you can use functions to perform simple operations in jpq l or native SQL queries and if you need more complex operations you can call stored procedures with the name stored procedure query for the corresponding java api here you can see the definition of a name stored procedure a query I use the name KQ date and it calls a stored procedure with the same name the procedure is very simple it takes two input parameters and returns the sum of them you need to register all three of these parameters for the name store procedure Kui I do that here x and y are input parameters of type double and the thermos an output parameter also of type double that's all you need to do to define a name cathedra query you can now instantiate and call it in your business code I do that here by according the create named store procedure a query method on the entity manager with the name of being named store procedure query then ffp two input parameters execute the query retrieves the result and write a short dog message as you can see he recall of the store procedure was successful it calculated and returned the sum of the two input parameter you can also define the store procedure call via a Java API it's pretty similar to the previous approach this time I call the create stored procedure query method with the name of be stored procedure then I define the two input and the output parameter the sub procedure call is defined now and I can set the input parameters called the stored procedure and get the result you tip number six use caches to avoid reading the same data multiple time modular application design and parallel user sessions often reside in reading the same data multiple times it is quite obvious that this is an overhead that you should try to avoid one way to do that is to catch the data that gets read often and not change too often let's see which options hibernate has to offer here you see the schematic representation of to hibernate sessions and a database most developers have this in mind when they talk about using hyman a to get data from the database but it's a little more complex there's the first level cache which is directly linked to a hibernate version and which is activated by default it contains all entities which were used during a specific session and hibernate uses it to avoid additional database requests from read operations and to delay all right operations as long as possible and then there's also the second level cache which also keeps entities but it's independent of the hibernate session that means that all hibernate sessions share this cache so session a can put an entity into the cache and session B can read it from there it needs to be activated by configuring the shared cache mode property in the persistence XML file the caching of specific entities can be activated by adding the Java expositions catchable or the orc hibernate annotations cache annotation to the entity the communication is the only one which does not store entities it caches query results and contains only entity references and scalar value you need to activate the cache by setting the hibernate cache not use communication property in the persistence XML files and set the cacheable property on the query as a complex topic and you should be careful when you introduce it to your application if you'd like to learn more about it please have a look at my hibernate performance tuning online training you can find a link to it in the video description seven perform updates and deletes in bulk updating or deleting one entity after the other fields quite natural in Java but it is also very inefficient hibernate creates one SQL query for each entity that was updated or deleted the better approach would be to perform these operations in bugs by creating update or delete statements that affect multiple records at once this can be done by RJ pql or SQL statements or by using the equity were update and material delete operations you probably know how to write an SQL or jpk update or delete statement so let's get into the IDE and have a look at a material update of equity we are update statement is pretty similar to the definition of equity really here you can see a simple example in which I increase the price of all books by 10% I first get the criteria builder from the entity manager and use it to create a criteria update instance for the book entity then I specify the forum clause in the same way if I do that for equity really and the next line I define the Fed clock I set the value of the price attribute to the product of its current value and 1.1 so I increase the price of each book by 10 percent then I create a query and execute it that's all let's run this test and have a look at the log files here you can see a few with the titles and prices of all books in my test database then execute the criteria update and hibernate generates this FQ a statement that multiplies the price of each book with 1.1 and as you can see here the next select statement returns the updated prices for all books the criteria update triggered only one SQL statement to update all books in the database that is a lot better than executing an SQL statement for each book entity but they have also downside to this approach it doesn't update hibernate caches so you either need to make sure that you don't catch any of the updated entities or you need to invalidate your cache and hibernate feature that you can use to avoid inefficiencies and to improve the performance of your application in my experience the most important ones are the hibernate statistics which allow you to find these issues and the definition of divide fetch type in the entity mapping and the query I get into more details about these and other performance tuning tips in my hibernate performance tuning online training you can find a link to it in the video description and before you leave make sure to join my free thoughts on Java library to download your hibernate performance tuning cheat sheet which summarizes the tips of this video okay that's it for today if you like this video please give it a thumbs up and subscribe below I you
Info
Channel: Thorben Janssen
Views: 25,413
Rating: undefined out of 5
Keywords: hibernate performance tuning, hibernate, performance, jpa, tutorial, how to, java
Id: F5asq8ZG_1k
Channel Id: undefined
Length: 23min 43sec (1423 seconds)
Published: Wed Jan 25 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.