Hibernate implements the analysis of adding, deleting, modifying and querying operation examples through session
Today, I learned how to add, delete, modify and query the database through hibernate. Here is a brief introduction:
First create a student class:
Then create a teachertest of JUnit test case type:
Let's talk about session Save() method, that is, add:
Bright result:
Let's talk about session Delete () method, that is, delete:
Bright result:
Then come to session Get (), that is, check:
Bright result:
Another query method: session load():
Here we explain the difference between the two queries: first, when the object to be queried does not exist, the returned information is different. The get method will return: Java lang.NullPointerException
The load method will return: org hibernate. ObjectNotFoundException:Norowwiththegivenidentifierexists
Secondly, load returns the proxy object, and the SQL statement will be issued only when it is really used; In addition, get loads data directly from the database without delay.
Finally, let's talk about the most commonly used update methods, which are updated through HQL statements:
Bright result:
Through the update, my native place of Moro has been updated from Huangshan to Anhui
In fact, it has a session Update () is the update method, but it is only this update method. If you update only part of the columns at a time, this update method will also update all the columns. The efficiency is not too high, so it is not recommended. Of course, there are also compensation methods. For example, if XML is used, You can set update = "false" in the property tag of a column in the configuration file that does not want to be updated; In addition, you can also set dynamic update after the class of the configuration file: dynamic update = "true"; Of course, if annotation is used, you can set @ column (update = "false") on the column you don't want to update; In fact, these are not flexible. Using HQL is the best, so only the updated code of HQL is posted here.
summary
The above is all about the analysis of Hibernate's add, delete, change and query operation examples through session. I hope it will be helpful to you. Interested friends can refer to this website:
Quickly learn about session in Hibernate
Hibernate attribute level annotation instance code
Hibernate uses HBM XML configuration mapping relation parsing