Transaction Management in hibernate in spring boot Interview questions | with Example | Code Decode

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys welcome to code decode today in this video we will be looking into the transaction Management in Spring boot hybrid application the interview questions related to diesel so let's get started please like share and subscribe to support us so that these video reaches to more of the people who are trying to crack interviews like you now how do you implement a transaction or how do you manage a transaction in the spring boot hibernate application so when you integrate your hybrid with your springboot application you do not use need to use any hybrid transaction management you can leave it to Spring declarative transaction management and the way to load it using Android transaction annotation too much of theory now let's understand with the demo first and then we'll come back to Theory I'll give you an example I have one spring boot project created for you for integrating your hybrid or JPM as an orm into it what we have done is in the pom.xml we have added one spring starter dependency for data jpf which will Implement also the high militant GPA for you now the next thing that we have done in the application.properties we have given the URL to connect to the database now here you can see this is the code decode database that we that we are going to connect to then we have given the username password the dialect and update this is everything something we have already covered in the spring crud video already next we have created a simple flow that is from controller to service to repository and the data that is going to be saved is created in the entity object so we have two entities employee and address so employee has ID and name and that employee details the address details are actually here in the address table so for each employee we have an address associated with it with the address ID and address location say here this name it can be the address tweet 1 Street 2 and Street something like that this is just for a demo purpose now the employee has having the one-to-one mapping with the address so we are just considering here that each employee stays at one single address and each single address is only one employee so this is just an assumption for the demo purpose now this is the entities that we have created now let's come to the controller so controller is the one who is going to interact first with our Postman we are going to hit a roller with the URL as localhost 8080 slash code save so 8080 slash code save and as the request body is employed so employee we are just passing the name not ID because ID is auto generated this is where the ID is auto generated so it is going to be taken from the sequencing page this is the hibernate sequence where the next value is going to be taken to so if this project status is clear let's go to the service layer here service layer we are passing an employee and we are saving it in employee as this and apart from that what we are doing we are creating an address class we are setting the ID name and employee here and then we are saving an address too so for this we call an address service in the add address to in the address Repository so this is the complete flow just for the demo purpose what I have shown here is we want to save both employee and address so it should be in one transaction in one go now here what happens is SM as soon as line number 26 you save an employee in some exception throws then address is not saved but employee is saved which we do not want the business says if an employee is to be saved for short there must be an address to be saved in the address table also so for that what we have to do is we have to make it transactional now I'll give you an example if you do not make this method is transactional then as soon as you complete your line number 26 and goes to line number 27 then your employees saved in the database which is EMP table here your employee will be saved but that is not what we want right we want that when everything is completed when address is also saved at the end both tables should have data if nothing goes wrong else you have to roll back and your data should not be saved in the database So currently I can show you if currently I do not have any transactional on the class or on the method level so what will happen so let me quickly debug this application so application has started successfully now when I am trying to add this then this is the employee the ID is null because it is auto generated automatically it will be taking the next value from this hibernate sequence so one comma code will be saved so when I do F6 and my flow goes to to like number 28 in the employee table since it is not transactional one comma code is saved so I'm removing everything I'm closing it and I'm going to make it transactional now if I make it at the rate transactional then what does okay so from where we have taken we have taken it from spring Frameworks transactional annotation so we are using the spring declarative transaction management here and what it will do whenever you mark a method is at the rate transactional then when everything ended when the closing bracket is reached then only the data is added to the database so that's the beauty of using a transactional it opens a physical transaction to a database layer and will perform everything keep it in the memory and we'll update to the database only when everything is right so now if I try to add it now let me debug this application after making it at the transactional as soon as you go to line number 28 you will see your employee is not templated in the EMP table so currently empty table is empty address table is empty and what is the hibernate sequence that is one so now if I try to add again the code comes here the name is code now if I do F6 at this point of time in the previous example where we do not have identity transaction annotation employee is saved now can we see if the employees same answer is no your empty table is still empty it is because you have marked your service method as a direct transactional now until you do not reach to the end nothing will be saved so that table is empty now we understand that since we have integrated our hibernet with spring boot application all the headache of doing the transaction management is taken away from hibernet and is given to a spring declarative transaction management and in Spring we do the transaction management using a direct transactional annotation so here we have used entity transaction annotation to Mark the boundary of transaction as soon as the method ends transaction also ends and the data is saved to the database now what all things we can use transactional for we can use transactional to wrap a database transaction a physical database transaction so if you have marked a method as adult transaction until the scope of that method is not ended nothing is going to be saved in your database but as soon as the scope of this method ends everything that you have done will be saved to the database now let me delete this right now and let's see the real example now so we are allowed to do many things with everyday transaction So currently what you have seen is until is the transaction boundary is not ended your data is not saved to the database now let's see a good example of this I am going to start again I'm going to set everything to empty is already empty the hibernate sequence I'm going to make it to one again and now let's try our happy case so at line number 26 the data should not be saved as seen before but at the end of line number 34 your data should be added in address table and an employee table both so here's the method to add data to the address class so I'm going to make this also transactional so that both of these are in the transactional boundaries now remember this is the part of transaction propagation that if you have an open transaction here and you call a method add address to go here this is also in a transaction so this is an inner transaction in created if you have a propagation type so propagation is how the transaction boundaries are managed when one method internally calls another method which is also annotated with either a transactional annotation so since employee method add employees already annotated as a direct transactional and address is also allocated as a very transactional then there are multiple propagation ways through which you decide that this address to be added into a table should create a new physical transaction should use the existing transaction or should not use any transaction so all these cases are derived using the propagation field of transaction Management in Spring let me debug this application at line number 28 whenever flow goes here your employee should not be added to the employee database but after line number 35 employee should also be added in interest should also be added so here when I do F6 it goes to line number 28 employee should not be added so see employee table is still empty because it is still a transaction in progress and method is not completed method is in progress and hence until next everything is not done nothing is going to be purchased to the database now I am going to create an address object and address object is going to have an employee reference to one comma code now whenever I go to address now here this is also transactional so current situation address should not it should also be empty even till here address is empty and employee is also empty now after this also the scope of this is not ended yet so if I do F6 we return to the employee class now here again still since you have already executed address service still your data is not added to the address repository why because we have used a default propagation when there is no propagation at the rate transaction uses the default one the default is the required the required propagation is the default propagation type it checks if there is an active transaction if there is an active transaction then use that if it is not then then create new in our case there was an active transaction coming from employee service so it has not created a new transaction and happily ignored this annotation at line number 17 because a transaction was already open why to open another new physical transaction because there is a limit to creation of transactional connections to the database so spring does it internally for you it does not create another transaction so even when the scope is ended the scope of this employee is not still ended this method which is the transaction being used is not ended it will end it line number 35. hence your employee and address table both are still empty if you can see these both are still empty now if I end the transaction now you try and see your data is added in employee as well as in address this is the beauty of transaction Management in Spring boot it does everything for you internally what you have done you have just added a transactional annotation here and you have used the basic propagation level that is required which says if there is an active transaction with employee who is giving me already a transaction why should I create new one I'll use the existing one and hence when it tries to save it the data is not safe to address table it is saved when the existing transaction boundaries ended which ended at line number 35 hail still line number 35 neither the address repositories are able to save anything nor the employee repository is able to save anything you are going to save everything only after the scope of this method is ended so that's the beauty of transaction in springboard now we have left lots of theory and theories also important so I've already covered this in the transaction is used in the spring even though you have hybrid implemented spring is capable enough to do things for you now at the rate transaction into institution gives you many many ways to implement transaction in different ways with the propagation levels isolation levels timeouts rollbacks read-only everything is given in the in this annotation as an attribute now it's so good to see it is working but how does it works internally is a main question in interview so internally usually what spring do is it creates a proxy manipulates the byte code spring will wrap some transaction management code around the invocation so from where is it called it is called from employee controller so what spring does is either it creates the proxy or it creates the dummy code whenever the add method is called and if the add method is at the rate transactional then this controller is going to call a method like this create a transaction and caller Ed method with trial by catch block if everything is fine then commit the transaction if anything goes wrong or some exception occurs then roll back the transaction and throw an exception so this is the code that it spring does for you when in the this particular call from the controller it calls a proxy or it gives a right call to a dummy byte code a byte code says do not call this directly call this method in a block and that block is a transaction boundary a physical transaction boundary for a database if everything goes perfectly fine and the add method is ended perfectly fine then only commit this controller says after this is completed after that commit and this whole line is replaced by these line of codes with try and catch so in the try add is called and then after that commit is called if anything happens wrong in the ad block then a rollback is created for you how to use at the transaction where you can use at the rate transaction you can use exactly transaction National on the method level on the class level so this is the class level so you can use transactional here also and if you use transaction here by default all the public methods will use this Android transactional automatically so if you do not make it at the rate transactional by default all the methods will create a transactional boundary so you can use it on interface superclass class method or super class method or method level now we are considering Venus class in method level if you have a class level annotation you do not need a method level annotation basically both of them will use all the methods will use the transactional only but if you give both you have either a transactional on class level also and on the method level also who will be given the preference always the method level transaction will be given the preference so here is an example your employee service is also annotated transactional and your add method is also annotated with the indirect transactional then the method in the class takes the preference over the transactional setting defined in the class level so remember if you have transaction on both then who works the method is given the preference now a quick check on your theory what is Transaction what are asset properties so a basic transaction is a way to make changes that you perform in one or more systems So currently we are making changes in two systems that employee table and the address table so this transaction is a way to maintain a transaction across these two systems so transaction manages the changes in one or more systems in our case employee and address table these can be databases message Brokers or any kind of software system in our cases it is database tables the main goal of transaction is to provide the asset characteristics and what is asset characteristics atomicity consistency isolation and durability atomicity defines All or Nothing principle so it means if you commit your transaction then you can be sure that all your operations got performed but in case you abort your transaction then everything that you have done is going to be rolled back nothing is going to be saved in the database so the in the secondary transaction make sure everything is atomic in nature then we have consistency that means this transaction that you are doing is going to take your system from one consistent state to another consistent state for example if you are doing some Bank transaction then if the data is deducted from my account and added to your account then it will not happen that it is deducted from my account but not add it to yours or it is added to you but nothing is reducted from my account that cannot be the case so the consistency says at the end your data is consistent if 10 Rupees is deducted from me 10 Rupees is added to yours in relational database that can also mean that all the constraint checking is also passing that is the foreign key and unique key constraint is passing in your database now isolation isolation means that your one transaction is not visible to another transaction until you commit otherwise you will have multiple problems like dirty read Phantom reads read uncommitted all such isolation levels will be seeing in next few minutes then we have durability that ensures your committed changes are persisted in the database so if you do everything your own logic is written everything is doing fine but after line number 36 your code is not added to the table then how what is the use of doing that much so durability says your data is going to be committed and persisted once you commit or you exit your transaction boundary so by the end of this boundary for sure your data will be persisted to the database now transaction propagation I've told you if there is one transaction already open and you call a method inside a method then and that is also a transaction enabled then how boundaries are managed the physical boundaries are managed in spring so there are multiple ways to decide your logical transaction boundaries with the propagation levels the first one I've already shown you the transaction propagation is required this is a default propagation it checks whether an active transaction is there so this has a property called as propagation and it is a propagation type it says if there is an existing transaction coming so yes existing transaction boundary is already coming here at line number 33 where it is getting called internally so at line number 30 even this is called a transaction is already open so this is conveniently ignored at line number 17 and the same transaction is used and hence even after line number 21 ended this transaction boundary is not even created ever because it is propagation type required this trans new transaction is not created and only when at line number 36 when the transaction boundary ended then only both the employee and address is saved even if you cry and hard and say repository dot same repository dot save nothing is going to be saved in your table because the transaction is still open and running the main transaction so that is the required propagation now let's see another type of propagation requires new now requires you say I want my own complete transaction and what is the keyword for that rather than required a Twist so these are all the annotations that we are going to see now I will be demonstrating requires new requires new says okay if there is a transaction coming I have a problem I want my own transaction I don't want to use anybody's existing physical transaction I want to create my own transaction so suspend the previous one so employee transaction will be suspended and a new transaction will be created with employee new and when at line number 21 everything ended the address will be saved in the address table employee will be after completion of line number 36 employee will be saved in the employee table so these are not dependent on each other after line number 21 initially with required address was not saved but here address will be saved but one cache here is that if you try to save an address before an employee the table does not work like that if you go into that address table it has a foreign key constraint if you go into the properties into foreign key constraint empids referred from employee and since employees transaction is not ended anything will not be added in the employee table employee table will be empty so they'll give you an exception to prevent that and to Showcase or require new propagation type I will comment this up so that there is no foreign key relationship which can cause a trouble to our program so we are going to comment this right now and what I'm going to say is save an employee after line number 36 but before that add an address now this add-in interest is and require a new transaction so a line number 21 a new address will be saved now let me try hitting it so at line number 29 again your employee which is saved will not be added into the database why because the boundary is ending here but before that if you can see our address class is called and the transaction propagation says I require a complete new transaction so what it does is it suspends the thread which is saving an employee to employee table and started a new thread which is going to add an address to the address table we have an address with me id1 and name as Bangalore White Field and when line number 2100 at least address will be saved so after line number 21 you can see our address service is done but our Employee Services is still remaining it is still not there so employee should be empty but address should have the data now so yes address has the data now though employed is null because I have commented the code but at this point of time I can showcase you that address service boundaries ended because a new transaction was created on Boundary ended in line number 21 hence address has the table but employee is still empty it does not have anything when will employ table has the data after line number 36 is executed and when the line number 36 is executed even your employee has the data so this is the employee and can you see the hibernate sequence to be moved to three so what happened here is employee one comma code was in the memory hence the address was saved as 2 because both uses the hibernate sequence only so though I have added the employee at the end but the employee was created first so during the save only the hibernate has created an employee with the id1 and later an address with the id2 but since you have created a new transaction here hence address was saved first and then employee was saved but what you have in the memory is one comma code and two comma enters so that was requires new so that was all about requires new I have many more things to cover like nested mandatory never not supported supported rules for transaction isolation management water isolation levels and how do we Implement that in spring so if you want me to cover all these remaining topics please let me know in the comment section then only I'll create the second part of this thank you
Info
Channel: Code Decode
Views: 9,497
Rating: undefined out of 5
Keywords: transaction management in spring, transaction management in spring boot, code decode, spring boot transaction isolation, spring boot transaction management interview questions, spring boot transaction management example, spring boot interview questions and answers code decode, spring boot code decode, transaction management in spring boot interview questions, transaction management interview questions, transaction management code decode
Id: b7Pev6i8fso
Channel Id: undefined
Length: 23min 7sec (1387 seconds)
Published: Wed Nov 30 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.