Java mock interview | Hibernate / JPA | java interview questions and answers for experienced 5 years

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
it's not a game [Music] hello everyone today we have yash with uh us and uh again we're gonna have another mock here and uh yes is a software developer basically he is from java background so let's welcome yash and let's start the interview of him okay hello josh hi sir okay so yes before i get started with anything just let me know your you know backgrounds your current companies uh the current roles and everything and well before i uh before you answer this question i'll just tell you that there is no need to expose your company name and everything just normally just introduce yourself tell me your years of experience and just tell me the project the kind of project that you are working in right now yeah so hi all i do have a 3.9 years of experience as a full stack developer i have worked for two organization and the current company i'm working for now is in tech platform basically we do provide online platform where students do prepare for their examinations exams basically so in my current organization we are using a spring boot application and for front-end we are using timelife html javascript and for back-end we are using spring boot spring security java hibernate jpa and when it comes to a database we are using postgresql so this is something about my current organization or the languages i am currently working on perfect yeah it looks like you have a very solid background yes so yeah and before we get started you know uh we're gonna have a lot of discussion and as usual as i said i know yours pretty well okay and i know like you know the technology that he has gone through so maybe or whatever the discussion that we're gonna have that's all about our knowledge yes right so but you know i just want to let everyone know like you know if you are getting time just you know just prepare for the same question do some research by your own just don't go by our answer or our discussion but i will try my best to give you everything with this interview but you know uh always is good that you know if you can go for the other platform you can browse through wave and can collect more and more information about a particular question okay cool so yes just tell me uh from which uh category will be starting either it is going to be hibernate spring uh java from where you want me to get your interview started sir it's up to you but yeah i i have to choose i have already watched your first smoke so yeah that's a very good point very good point here and yeah so in the first mark i have taken him off with a kill that mock is available on youtube whatever the questions i have asked to occur i will not be asking to yash okay so i'll be um i have prepared a different set of questions for josh and my intention here is that to cover maximum number of questions and us also has done a switch recently and got placed in a very good package if anybody wants some treat you can just email to your short just connect with him on instagram so so yes yeah so let's start with hibernate and okay first of all before we get started with hibernate i just want to i just want to you know ask you a very simple question yes tell me the difference between the jdbc and the hibernate so why we should use hibernate here so basically why we should go with the hibernate it is an orm what does it really mean it's a object relation mapping that means the object classes we do have in our project that is known as entity it only maps that to our database it is not creating another different table okay so it helps us to provide more object oriented concept basically and when it comes to a jdbc it is simply related to a sql concept where we are writing sql queries for table only not for object okay so that's the main difference between these two uh the other difference is like if we go with jdbc we do have to write a query that is database dependent what does it really mean suppose if we are writing any query for mysql database and in future if our manager told us to change the database from my sequel to oracle or postgresql so then what we do need to do we do need to change a whole query structure that we have written in our project okay that's the menu but when it comes to a hibernate as i told you it's the orm so what hibernate do basically whenever we are using hibernate there are some configuration file in which we do define some property so the main property of hibernate is dialect what does it do it basically do a conversation or it simply translate our hql query to our database that we are using okay suppose if we are using mysql right now and if we have written any sql query or in future if we are going to change our database so we don't need to change the whole query structure that we have written in our project we can simply change the dialect according to the corresponding database and hibernate will take care of that it will automatically going to translate the query to the correspondence database perfect perfect okay so there is another difference that just come in my mind whenever we are going with jdbc concept we simply do need to take care of all the exception that can occur that means we do need to define our call inside our try and catch mostly okay but when it comes to a hibernate it simply take care of all those checked exception and convert them into a unchecked yeah so basically what you are trying to say yes in jdbc we whenever we write any code in jdbc and in simple java we need to handle the sql exception and sql exception is of course is a checked exception we have to handle those exceptions but in hibernate hibernate takes care of you know converting the sql exception to runtime exceptions right perfect pretty good answer pretty happy with that well whenever we basically talk about hibernate uh so in hibernate we have couple of things like you know station factory and session okay so can you just tell me the differences between session factory and session why we should use session factory in session okay so session factory and session okay i would like to go with the some simple example first just consider like we do have a big store okay and if we want something from that store what we simply do we go inside we buy it okay or we simply ask the distributor to provide us that object or that thing item as well so it is a similar like of concept session factory is like a big store it has only sessions as a item that is object okay and it provide that object as per our requirement so now let's come to a programming concept so session factory basically is a object factory as its name says factory so it provides a session as an object which we can use to perform for our crud operation current operation i hope everyone knows okay so the role of object factory is only to provide a session object okay now what does that what we can do with that session object we can simply use that sub session object to perform any insert operation delete option operation or update operation when it comes to a different scenario just suppose if we talk about a multi-threading environment okay so session factory object can be used by a different thread that means multiple threads okay but session object a particular object is only going to be used by a single thread okay so that is also a difference between both of them if we do thing like why we are creating multiple sessions so yeah that is the main difference but there is also another difference like if we talk about a session factory object it is a heavy weight what does it mean if we are going to create multiple session factory object it is going to slow our processor okay perfect and as we know uh sessions are simply kind of caches so they are lightweight so yeah these are the some simple basic difference between session factory and session perfect okay i'm gonna count it right now uh okay i'm gonna just turn off my ac a little bit uh just give me one minute josh okay sure the electricity is back by the way okay okay so right now i think we can have a very nice discussion because there was no electricity and it was waiting and now i think that things are normal all right so okay yes so you have uh given me the very detailed information about the station and the station factory you said that the session factory is a heavyweight and the session is lightweight right okay and you said that if we are creating many session factory objects our you know processor is gonna take a lot of processor a lot of memory basically it's gonna take so here is my next question can we create multiple session factory in our application yes or no yes sir okay so can i create multiple session okay so should i create multiple session factory object in my application yes or no we shouldn't mean it's not like we shouldn't create yeah we can create if our company is telling us to create because there is no side effect in which scenario you should create multiple session factory instance yeah in means uh we should go for multiple session factory in instance if we are using multiple databases suppose for image upload yeah that's what i want to hear if you are using many databases for each database we should create only one session factory instance because it's heavyweight and it takes a lot of memory so we should go for only one and only one session factory instance perfect and you said the session is shortly right okay so if you want to compare the session listen to this question very carefully if you're gonna compare the session uh session is a hibernate thing right and if i want to compare the session stuff with the jpa then what is the similar object we have in jpa to deal with uh various uh you know crowd to deal with various broad operations we should have methods in jp also just like in hibernate you have methods like you know save saver update you know delete okay you have different methods remove method you have server update method you have a save method you have update method you have right in hibernate api just like that in your jpa also you have different uh you know methods right and uh here you are dealing with the session they are what is the similar object you'll be creating in jpa and and how we'll be performing those crowd operation which over which object okay so basic basically when it comes to our gpa we do have some basic uh okay but yeah it's an entity manager so there is a persist persist method okay yeah persist method but i i haven't used particularly jp because i have worked on only hibernate so i never find it but we have we have a uh in a class called entity manager in jpa right and the similar class if you compare jp and hibernate we have session and hibernate basically you know exchange the future of jp and provides us some much more functionality uh with much more functionality methods uh in terms of like you know save server update if you want to say persist method in jpeg it does the same work as the sub method in the hibernate right perfect uh cool so basically yes what do you mean by persistence context in hibernate okay persistence context is a jpa thing or a high winner thing you said you are not using jp pretty much in your company yeah but but yes but it is a hibernate thing it's a it's a gpa thing but hibernate basically does use use the same terminology okay okay that's fine okay tell me about the persistence context i know if you're going to compare the jpa persistence context and the hibernate persistence context they both are same because obviously hibernate is basically extending the jpa uh stuff that oracle is providing right not only hibernate any or any um you know orm tool that we have like just like hibernate mybatis and whatever right they all are basically uh providing the features for us by extending the jpa right perfect okay tell me though tell me uh basically what do you mean by persistence context and why we are using it in having it so yeah resistance context is just like a block okay what does it really mean so it comes into a picture whenever we open a session okay whenever we open a session that time the block particular block is created inside our memory and that block is known as the persistence context the what is the role of that position context the role of that particular context is to maintain or to store all the states of our objects and inside that memory area we do also have a session object that communicate with our database so this is just a simple definition when it comes to a persistent context okay perfect so basically have you ever or heard about the caching in hibernate yes sir means how many label of caching should we have in hibernate yeah basically two levels are there let's talk about the first level let's talk about the first level okay first level of caching imagine i have created an entity object okay and then i did save it when i when i did save it so i should i should do session.save then i should pass on my entity object inside the save method isn't it yes then do you think uh that object is managed by persistence context the moment you are going to the moment you are going to open a session everything is managed by your persistent contextual so imagine yours you have an entity right and basically uh you have an entity you have set some value to your entity then you are trying to save it so you are doing session.save and you are passing that entity with your swipe method right now the moment you're gonna do you know save you said that everything will be managed by persistence context and the persistence context that means your station is going to keep track of uh you know every data that you have put inside your entity right and the moment that you're gonna do transaction dot commit is gonna commit those changes right to your database perfect now i want to understand one more thing let's say right now um you know i have an entity okay and i'm keep changing the entity value okay i'm keep updating one of the value let's say i have entity called student and keep setting the student name multiple times let's say thousands time do you think thousands time my row is going to be get updated in my database or it is going to be only updated once uh in the last time that i have did the update with that changes only it will update the database so um so how many times is gonna hit the database if i'm gonna keep modifying my entity again and again before i do a commit so basically what will it do here i i i am guessing what you are trying to say whenever you fetch any record from your database and then you try to change that entity particularly okay so what what will the persistent context really do whenever we fetch any record it maintains a copy of that object so suppose if we do simply call session.get and we are getting any object for particular id suppose student s1 so what will it do it will keep a copy it will it will make our original reference as a s1 in the resistant context and up after that suppose if we are doing any changes like we are changing its address name or whatever we are changing it won't update that as one object it will create a new reference object okay or we can say a clone object okay and then it will perform all those change operation in that object now suppose after doing these changes hundreds of times like we are we have set the name hundred of time so whenever we are going to call our transaction dot commit or even if we won't call that what will that persistent context do it will check in the memory block that is there any object that is available in the context or not but then it will found two object okay the original s1 and the s copy of s1 that we were continuously updating so what it will do it will then compare both those object if there is any difference between those object it will only hit the update query single time it won't hit it the 100 times it will hit only one time okay so yes it will update that record only single time can we say that's the first level cache yes that that is the first level cache that's the first level cache because it's the all the records are managed in cache memory so this is the first level cache example perfect so that's what i want to hear that basically the persistence context is a first level cache when we say session session is the persistence context isn't it station is a persistence context so anything we are doing that is kept track of the session i mean any any time we are trying to modify our entity those uh you know changes are being tracked by our in by our session or our persistence context right so and it does it compare like okay well this is the role let's say this is the object that i have pasted from my database and this is the data that i have and now when the user is trying to do a commit do that data change if the data does not change then of course you know uh it will not uh not do anything if the data changed you don't even need to update the things it will be directly you know commit the data to the database perfect um cool so can you just tell me the difference between the get method and the load method yes in hibernate okay get and load are the hibernate method of the jpa methods so basically get is coming from jpa if i am not wrong but the load one was created by hibernate people okay what is the difference between the gate and the load method yeah means okay so basically both methods are used to fetch the records from db and both the calling way is same for both method but yes there is some different like suppose if we are going to call a get method for uh okay let's take a simple example suppose we do have five record in our table and if we are going to fetch a record for any primary cure and any id that is available in database so what will get method do the moment we are going to call a get method it will it will hit the database at the same time and fetch the record okay but when it comes to a load method even even the object is present in our database what will it do it won't hit the database at that time suppose if i am calling session.load it won't hit the database that time then it will hit the database the moment we are going to use that object even if we are going to use that object for printing only at that time it will hit the database so what is the what is the design pattern it uses the load method so yeah it is the lazy one it's the hd one and how how does it make how does it work internally what is the design pattern it use okay proxy proxy oh yeah proxy okay so you are talking about the proxy one yeah i'm talking about that only yeah so the get method basically hit your database the moment you're gonna need something it's gonna do a query it's gonna get the thing from the database right and uh you know the load method is basically gonna do a query whenever you will be actually needing the thing right let's say you are doing session.load and you are giving the primary key of a particular entity then it is not going to paste the data in that moment rather it is going to assign a proxy object right to that reference and the moment you gonna do i mean the moment you're gonna use that reference now use that particular proxy that is available at that time it is gonna make a call and it's gonna get the data from the database and gonna make it available for you and it is really good whenever you need something let's say you have a very uh if you have a relationship between a couple of entities and it has a bunch of data you don't want all those data to be retrieved maybe if you're using a proxy there then it won't be making those data available unnecessarily so basically whenever you'll be needing it it is gonna face this data i'm gonna show you some um in a code yash and maybe i'm gonna ask you some questions and get and load but we'll be doing that a little bit later and i'll be asking you like you know how this things gonna work internally okay so do you think there is any other differences with get and load with respect to the exceptions that they throw yeah basically get get method won't throw any exception if the record is not there what will it do it will return you a null okay but when it comes to a load method it simply return as the object not found exception when there is no record found for that primary key so yeah that is also the other difference between get and load method perfect okay first you look at this we have a hibernate first project here i'll go to my uh demo okay i'll open the first program that i have coded over here look at this particular program and familiarize yourself right i'm creating the session factory object right here with this sm factory i'm opening a session and i'm beginning the transaction okay and right here from the line number 24 look at this much chord i'm trying to get something okay i'm trying to load the song let's say i want to load a song which id is one okay so i'm writing session dot get off song dot class of one okay and i'm loading that particular song and then i'm logging something here called method executed and here i'm doing song dot get song name okay now tell me what should be the method execution flow first tell me as i'm writing get method over here do i have the secure query fired in this line the first question is that if this line will fire me a select query it is going to look for the song in my database and it's going to load it and if that is going to happen then of course this particular line will hit a sql query a select query then this particular method executed will be printed and then i'll get my song name this is going to be the flow of execution or what is going to be the flow of execution can you help me with the flow of execution what i'll see in my console and by the way in my hibernate config.xml if i'll if i'll open this particular file open with generic texture the other one is not working for me look at this i am uh i'm just turned on the so sql to true so obviously my all the sql will be shown in my console so now tell me the flow of execution so what you are expecting from this particular program the first line is going to hit the database or not yes it will hit because we are using the get method to fetch the records okay this will be a proxy object or this will not be a proxy object this won't be a proxy object okay first you will see on your consoled uh select query after that you will see method executed and after that you will get the name of song okay let me try that do right click run is java application okay pretty good first i'm getting my select query my uh my if it is facing my song then i'm getting method executed then it is getting me the song name which is believable perfect now if i'm gonna change it to hundred or thousand and let me tell you that in my database i don't have any thousand record available right over here in the table so what do you think what kind of exception you are expecting right here in this case in the line number 29 so you basically if there is no record the get method will return as null okay and the moment we are trying to fetch the record from a null object it will throw some exception with exception this is null right you are saying yeah it will be now then no dot point null pointer null point yeah then do a right click run is java application okay we'll get the null pointer over here we are getting the null pointer exception of course it is trying to hit the record but whenever it is trying to hit the database if i'm going to put a breakpoint here in the line number 27 do a right click debug as java application you will see in the line number 27 we will have null as you have said earlier let me just debug it for everybody okay so right here whenever i'll do step over you will see the sql statement is fired okay and here in the song we don't have any song object over here assigned to the song now whenever i'll do step over here i'll do null dot something and it is gonna hit me 12. exception if i'll do resume i'll get null pointer exception for sure okay null pointer perfect now let's switch to the next next thing yes i want to change it to um let's say load now tell me the behavior here first tell me i should see my sql query or not in the line number 27. no sir okay then what will be the flow of execution what should i see in my console in which order so the flow flow will be like also yeah let's go with this one number one this record exists in my database tell me whatever so the flow will be like you will see the method executed first and the moment you are trying to get the song name from song object and that time you will see your hibernate will hit the query to database and then you will see the select query and after that you will see the line number 29 the mean the result of line number 29 that is the song name all right okay so let me run this let me save everything and run this and as you have said can i run this ctrl s right click let me run okay which one i'm running right click run is java application okay so method executed is first because this line will not hit the database right and which kind of object this will have uh your shell device will be a proxy object this should be a proxy object so method executed will be printed first and then this line whenever we will be writing song dot get song name this is gonna actually hit the database and gonna get the data back right now here it is getting me the believer data back right so to make it practical do a debuggers java application and if i'll go to line number 27 here i have a breakpoint i don't want to switch or let me switch okay you'll see right now whenever i'll hit this there will not be any database um you know query triggered here by hibernate but the song object is basically a proxy object this song uh um you know some dollar and some hibernate proxy it is giving me and if you can open this you can see this is basically a proxy right so when did i when basically i'll hit the proxy it is gonna call the uh you know the database database uh query it is gonna make so maybe i'll just resume it and again i'll do that again i'll try debugging right click debug as java application so line number 27 it will not do anything it will it will basically not hit the database so the next time if i'll do step over it will be method executed and as you have said if i'll do step above one more time it is going to hit the database and get me the it is hitting the database and getting me the data okay only one question left yes you also have answered that in your interview if i'm gonna change it back to a hundred then what kind of exception will have fifteen will be object not found exception perfect do i right click run is job application and will have a object not found exception i believe object not found exception no row with the given identifier exist and this is the identifier of the song class perfect good job okay cool so can you just tell me yes what is a transient state uh in hibernate when we say an entity is in transient state yeah okay so as as i previously to mention that there are some state in persistent context so this state is one of them what the this state really means so transient state is the state whenever our object is mapped to the session so whenever any object is mapped to a session object particularly that object state is known as a transient state okay do you think okay listen to me listen to this question very carefully do you think whenever an object is managed by a session that's called a transient state when i say let's say i'm creating an entity object let's say i have a entity called student i'm creating a student object student s equal to new student do you think the s the reference s is in transient state or it is in persistence no it it is not in a transient it is in a persistent state why as i told you all in order is it isn't persistence that you are saying yes sir whenever we are creating a single object like student as equal to new student inside the open session block no i'm not opening any session i'm not opening anything okay you are you're you're okay no no no no no no that that that is not attached to any state of persistent contact that is a simple what is that can i say that transient no no no we can't say that because what is that state that's the transient state yes that's the transient state let's say okay hold on let me give you an example i am simply creating an entity object the entity object is not mapped to any session then that state is called transient state i'm just simply let's say i have a class called yes i'm creating the yes class object there you go that's in transient state that means it is not managed by my session or that is not getting managed by the persistence context all right the moment i'm gonna do session.save of that class object let's say i have a student entity i've created a student class up there student has secured a new student right and i'm gonna do session.save up student right and the moment i'm gonna do session.save and i'm passing the student entity reference here inside the session uh save method then the station is going to maintain that particular student object and as you have you know explained me previously the session is going to manage the student object and it's going to keep track of all the things and then that student object goes into the persistent state because it is getting managed by the persistence context or by your session uh in simple word in hibernate right so an object a plain object which is not which is not maintained by the session or the persistence context is called a transient state okay at that time we can say that object is in transient state the moment we're gonna put that object inside the session that's gonna be your persistent state and one more very good thing that i want to say here that you know when the object that you have if it is not getting managed by your persistence context right then that object doesn't have if that object is not mapped to your database isn't it imagine i have just created an object student security new student and i have set the property that means that object is not met that object is not mapped to your database whenever you actually do a save it goes to the database right so the moment you're going to have an empty store i mean just created a student update by your own that does not have an identifier or a primary key and if you don't have a primary key then that i mean the database doesn't know about that particular record because the persistence context doesn't know about it like you know uh that object is present inside the database or not right so whenever the object is in persistent state you will always have an identifier you will always have a primary key isn't it because the persistence context know that this object is right now represents to this row of my database right or this row of my table but if the object is in transient state you never know let's say maybe i i will have an identity i will set the identifier in my wishlist 300 400 500 or i will not give any identifier most of the time creating the primary key or the identifier is the responsible of the database by the auto generation but by that auto generation stuff because we can just uh let the let the database decide what is gonna be the primate what is gonna be the primary key of a particular entity right so yeah that's the thing so identifier oh if the object doesn't have an identifier it is in the transient state if it is in the persistent we have an identifier there cool uh so what is uh the detached test yes a detached state what does it mean so detached state is the one whenever our object passed means whenever our object is released by a session object but yeah that state is known as so when does that data state happen so i mean how can i say the object is in the tested and i mean after what i mean what should i do to make my objecting data yes yes so we we do need to close a session once we close the session object that state of object is known as a detached state okay if i don't want to if i don't want to close the session i will be confu i'll be start confusing you by now yes because now i think you are comfortable i am comfortable even though there is no electricity even though i'm sweating still i'm comfortable right now because you know i'm equated with this environment right now but anyhow just tell me without closing the session without closing the session if i want my my entity to get detached from this persistence contextual from the session which is basically managing then how can i make my object detached from the session what should i do if i don't want to close if i don't want to close my session or if i don't want to commit the transaction without that can i make my entity to come to a detached state from a persistent state are you getting my question yeah i i'm getting means is just not sure if i am getting it right or not but yeah i i hope you are what you are trying to say if you are not going to manually manage these closed session yes no no i want to manually i want to manually uh do what i want to manually detach entity object from the persistent state i i see you said we have a transient state then we have a persistent state now imagine the entity is in persistent state okay i want that entity to get detached i don't want my session to manage that entity getting it yes yes you said okay close the session close the session the entity will be detached for sure yeah i i know i have told you guys that one now is the because you guys asked me a lot of question conversations right so this is my enter so without closing the session if i want to detach an entity from the session from the persistence context i think i am asking the correct question there is a method called evade or evict do you know yes i think you should be out about that e v i c or i'm not sure that method evict method event i don't know how do you pronounce that do a session.edit oh sorry uh yeah session.evict i think do that okay and pass in that object actually actually i haven't used that method frankly it's fine but yeah maybe now people are going to learn from this i am also learning within this move no no see i'm just taking revenge from you guys right right now everyone i'll be inviting the moment i mean you guys basically bombard me with questions right okay tell me this tell me that okay this is my term okay all right so cool uh yes you know okay i will ask you another simple question anyhow we will be i'll be asking you these things with code then it will be more easy because it will be uh i mean you will be visualized that better but still you know without showing you the code i want to ask you a few questions then i'll be asking the same question with the code well imagine yours i have a transient object okay i want to move that transient object to the persistent state then what is the method i can use so means any save update method will do that thing for us perfect save or server update okay yeah okay what are the other methods which are available okay uh so that i can say my entity is in persistent state let's say i'm retrieving an entity by using the get method or load method yes sir the moment i do session dot load or session.gate and i'm gonna pass in my primary key of your particular entity i'm gonna get the entity back so the interior that i'm gonna get back do you think that ntd is in persistent state yes sir because that entity will be managed by your persistence context right yes sir perfect cool okay look at this application one up one look at this same program i have coded i have the session factory created over here i'm finding the system right over here in the line number 18. i'm beginning the transaction of the session and here i'm trying to save a song objectives okay so i have couple of question in the line number 22 this object is in which state uh i mean the song object is in which state line number 26 the song object in is in which state and in line number 30 this object is in which state the song object is in which state yeah can you just tell me line number 22 here it's just in transient state it's in transform state because the instance is not yet mapped to the session perfect and in the line number 26 or in line number 26 we are mapping our song in chance to the session object so it's state changed from transient to persistent it is in persistent state and uh the the other one here once once i close the session then the session object will be destroyed right yeah so the moment the section object will be closed it stayed again change from persistent to uh detach yeah this this will no longer get transient straight because this object was previously managed by the session and once you're gonna close the session this particular object state will be changed to data state right yeah that's the question that i wanted to ask you now this leads me to the next question okay so do a sev let me go to the app too now look at this and answer me the question here i'm creating a song object yash see i have a song uh you know the song name and the you know singer name now here i'm creating the session factory i'm opening the session over here and look at this session. contents do you do you know what what do you mean by the contents method like you know what is the work of the contents method yeah yeah basically basically it checks the is if there is any instance available or form inside the session or in the persistence context yeah so do you think the line number 27 is gonna return me true or false and why look at this so yeah basically it is going to return true okay just wait session dot contains no it is going to return false because we haven't mapped our we haven't mapped our song instant to the session yet okay so this is going to be false because you are saying that this is just a object and it is in transient state right yes and here we are just opening the station but till now this this object is not maintained by the station because we have not used any persist method or any persistence method so far right but look at this i'm saving the song object right now so as i mentioned that have given me right now the song object is managed by the session now look at this so what this particular line is going to return me true or false this time you will get true true okay because it is right now managed by the session of the persistence context the song object you right click run as java application just look at that first i'm getting false and then when i do a save when i do a save over here obviously the song object is managed by the persistence context and then i whenever i'm trying to again find that whether that object is available on the station or not it is giving me true can i do the same thing one more time over here if i'll do control c v then what will happen now i have change i have closed the session and i'm doing session dot content sub song i'm getting false or i'll be having an exception because i have closed the session over here confusing yo okay let me run this okay we got a exception illegal state exception so entity or session is closed right because i have closed it over here okay if i'm gonna move it to here do i control x and command v over here then what will happen this time it will be true could be true one is job application true okay perfect good job so okay these are very nice questions isn't it okay so um okay tell me us what do you mean by connection pooling okay right now you can mix up a spring a little with your hibernate answers i don't have any problem if you're mixing up you know spring what is connection pulling okay how do you create connection pooling tell me everything you know about it and then i'll keep adding some more information to that and anyhow the electricity is again gone but right now i just said uncomfortable again it is a concept of kind of managing our session object instead of creating every time we do need to hit a query new session it helps us to use the old object okay so which object yeah old session object basically the inside the pool we do have uh we we can create some sessions are you referring the connections as sessions yes sir but in yeah yeah correct only correct you know with uh if you have a connection object then only from that connection you will be get a session object right so basically you are saying it's a pool of connection the connection pooling is a pool of connections now tell me why do you want me to have a connection pool if i can directly hit my database and can create a connection why do you think that it is important to maintain a connection pool yeah so okay so suppose if we won't go with the connection pooling concept what we will do in normal scenario we simply create a multiple session object to perform any operation but suppose if we have hit a particular query that is taking too much time to be execute okay so we are creating multiple session objects for each threads that means we don't need to create multiple session objects we can simply use the session object that is created one time we can simply use that again and again whenever we want to use the that is the main concept of going with the pulling thing perfect answer so basically you are talking about the reusability yes sir that the exact word so basically what happens is whenever we directly hit our database and create a connection and the moment we're gonna query the database and get the data back from the database the connection is closed right but the moment we're gonna connect to the database we need a lot of information like the id the url the password and the authentication the authorization will happen in the database and then it will allow us to query the data and creating connections is obviously you know what we call that you know uh it's a heavy resource right it's basically heavy lifting job and this is basically costly operations so we don't have to do that again and again because each time you're coding data you don't want a new connection to get created rather what we can do we can maintain a connection pool so we in in which side we will maintain the connection pool in the database side or inside the server or in the server side server side not in the database site so all the connection pooling is managing whatever server like we are using suppose tomcat or glass fish or there are some other servers or something whatever yeah always in the server side only the connection polling will be managed in the server side only we never create connection pull in the database side so so whenever our server is going to be put off at that time our server is going to talk to our database and create a bunch of connection for us and we'll store those connections inside our server so that we can use those connections for connectivity with our database isn't it yeah so every every time a new request come so if if that request needs some database uh you know some database operation it need to do if you need to save something or delete something if the user want to do that then a specific connection object will be assigned to that particular user then once that connection um is getting used by that particular user once that user sign off or once that operation is done that connection will go back to the pool again and will be again reused by another user is connect who is basically connecting to our database so connections will be there so instead of directly creating a connection with our every request or every hit to our database we're managing a pool and in our server end [Music] [Applause] [Music] [Applause] [Music] so [Music] so basically uh josh uh to implement connection pool okay so what are the what are the different vendors that we have in spring let's say how do you implement connection pooling in server side yeah so we uh we do have some vendors like dbcp perfect okay d3po dvcp is provided by whom so it was it is provided by the tomcat people apache apache also has connection trolling that also has connection pulling vendors another popular one is there another couple c3po is also there hikari one is also he carries that that is the default yeah that is the default one used by hybernet hikari is the default one used by hybernet means internal implementation i if i am not wrong ikari is the default one used by springboat yeah spring boot okay so springboard basically whenever we use the starters data jp in our form file spring boot internally creates a connection pool for us and that connection pool the vendor that springboard uses is the carry connection pool even though if someone will go and add the starter data jp into our spring framework uh pom file and the moment you're gonna see the map and dependency you're gonna see hikari connection pool will be there by default and you don't have to maintain any connection pooling or you don't have to add any connection pulling uh you know dependency into a form file uh internally springboard is springboot is using hikari but as you said we have couple more vendors like dbcp using that you can create connection pool you have c3po uh basically all this c3p or dbcp yash if you're gonna create a connection pool basically who manages the connection pool for us what what is that interface or what is that class which internally manages the connection pool or a particular connection for us who's that guy oh data source is the one exactly this is what we do here data sources yeah data source is basically maintains the connection pool for you okay the the default data source that comes with our with our normal jdbc called driver manager driver yes sir all the spring also provides us provides us at the i mean the default class called driver manager data service right so do you think the driver manager data source or the data the simple driver manager interface which is available on high on jdbc those uh classes provides us the connection pulling feature or those classes are not providing us any connection pooling feature okay again it's uh something i never provides us yeah because i only use data source so i yeah because i haven't used them but yeah we we are using data source concepts we haven't used them means means on a practical level mostly i have used data source so that is the only thing right now in my mind we have done connection pulling stuff so many times in our stations yes we have tried with driver manager data source but at that time it was not driver manager data source is the one that we use because that comes by default with spring yes and that because if you go to that i mean the documentation spring they are saying do not use this for your production it does not provide any connection pooling this will work the same way as your normal driver manager and it will not give you any you know connection pooling support so every time someone is going to query for something it is going to hit the database and going to create a connection but for if you as you said if you're going to go for hikari c3po or something else at that time we don't need to create uh the driver manager data source instance or driver manager sorry uh driver manager instance we can use combo pull data source if you are using c3po if you are using uh dbcp you can use basic data source for hikari also we have some data source implementation class in hikari uh vendor for for the hikari vendor hikari vendor as well so they are providing us the data source which has the connection pooling support but the normal spring or driver manager data source does not have the connection pulling support so what are the different test type that we have in hibernate yes yeah okay so we we do have two types of fetch concept in hibernate so the the first one is like lazy one and the second one is eager okay what does it really mean so the lazy one is like suppose okay suppose if we do have a entity and it does have any another entity that is particularly mapped that means it has a relationship with the undifferent entity so what will it do the moment we are going to fetch record for our main entity when i am talking about the laser concept only so if we are going to fetch a record for our main entity that has a relationship with some different entity at that time it won't fetch the records for that b entity what does it really mean suppose if we are going to get a data for a table or a entity and if we have enabled our problem of the property of hibernate that will show us the sql query that is hitting on the database so what we will notice it will only trying to fetch the record from a table only it won't try to fetch the record from b table but in reality it is already mapped to a table so it should fast but the default concept of fetching a record or this fetch type property hibernate people have done like whenever there is a relationship like one too many or many too many so at that moment they have provide a default fetch type as a lazy one because they sometimes we don't need to fetch the record of all the dependent entity we simply need the single record and when it comes to a eager type that means simply fetch the record for all the dependent entity at a single time okay there is a another good example like we talked about the load one so whenever we call the load method load method basically go with the lazy concept okay because whenever we are trying to fetch a record it won't hit the database it get us the record whenever we are simply going to perform any operation on that proxy object okay this is the example or difference between lazy and eager concept okay so do you think the lazy one we should use or the the ego one we should use and in which scenario you will go for the lazy one in which scenario will go for the eagle one so mostly mostly we should go with the lazy one because some most of the time we don't need the dependent entities result okay it totally depends on the time that we need it okay suppose if we want to display some we want to perform some particular operation and our different different entity has that result or managing that input so we should go with the eager one because we do need to fetch the record at the same time but if we won't need to perform operation on all the tables or we don't require all the results we should simply go with the lazy one it simply depends on the situation perfect hang on should i hurry right now or i mean when should i discuss the salary i'm i'm holding an offer so if you do have any counteroffer we can discuss okay you're applying the same trick on me huh yeah i have learned from you now okay very good yes okay whenever i have a freelance project surely allow for you yeah okay all right so right now let's talk about eager and uh lazy face type just has done a program and he'll just give us a quick walk through how that eager and lazy phase type works and what is the use of eager and lazy first time yeah yes please go ahead so please explain me a little bit like you know how many entities you have and how oh yeah basically i have one main file here it is and i have two entities one is college and the other one is student so what i am doing call college can have many students so that's why i am on line number 21 i am using one too many annotation for students object because one college can have one so one college can have many students so other table is student fund so many student can belong to our one college so that's why i am mapping one many to one annotation here and yeah i am using address join column annotation to map the college id to this student table perfect so you have okay let me summarize in the student table uh in the student entity we have college dependence in line number 22. okay many students can belong to one college right and can you go to the college side okay you have a college entity and one college can have many students that's fine the line number 21 can you highlight that you have written many to one right okay now tell me now tell me if you talk about college and student relationship right over here you have a couple of panties now college entity has the student entity over here so what kind of page type you will be using generally and why so basically whenever here we are using the eager one because we are going with the one too many but sometimes we only want the college details so we don't want to fetch the student record because one college can have many black student okay so what will happen it is going to take some time to fetch do student result also so here it is not a good scenario to go with the default fetch type which is eager one okay so basically you are saying that one too many has igor phase type by default it is eagle right one too many annotation has ego face type right okay so if you are facing all the student i mean if i want to paste all the college then as the student has the relationship with the college so all the students also will be by default faced let's say i have i want to face all the college records of a particular district or of a particular country then along with those scholars all the students who belongs to that colleges those data also will be passed and of course it will be a very heavy lifting job can you show me can you prove this particular point it just said one too many is by default is having eager type so can you show me your database how many colleges you have and how many students are mapped to those colleges yeah so i have already inserted some data so if we move to a college table i have three different college igno hrm and you all right okay and the id is one two three so if we move to the student table you will see i have nine students basically and each student is mapped to some different college like the first three are mapped to the college id one that is igno the next three are mapped to the college id2 that is hrm and the last three were mapped to due so here we are mapping college id3 okay so right now can you go back to your entity yes the college entity okay so right now if i will be by default if i'll retrieve my college entity so all the college entities i'll be retrieving or one college entity if i'll be retrieving then it will be by default will page all the students according to you in line number 21 because you have mapped that entity with at one to many and one to many default phase type is ego right here can you put a breakpoint in your outdoor java and can prove that to me okay can you can you can you log that c1 in the line number 27 okay put a breakpoint in line number 26 okay can you start your program in debuff all right can you can you do a step over i just want to see whether that will that will hit the query i think that will hit the query but is it going to pitch my student data with that college can you do a step over so let's look at the query it is finding the college details so is it finding the student title as well no can you can you hover and see one so are we having the student yes we're having the student uh over here as well now you can see when did you when you basically click on that look at your console right now it is also calling your student one because you did hit that particular you know uh um object right can you resume it and can start it one more time can you resume that and start this one more time okay and we want me to run in a debug mode yes and are you having are you having uh the two string method inside the call list yes sir in both tables yeah can you go to the college and comment out the two string method in both of the table because here you are accessing the object also the student object can you also come in the same in the student table as well all right go back to your app.java debug it one more time start it in debug mode please debug as job application all right now can i go to like can you do a step over [Music] okay the get method will be called can you do uh can you do a another step over yes so this time it won't fetch the recorder okay can you hover on the c1 okay can you uh can you see can you look inside the student i think the moment you're gonna hit the student see it is padding the call because that's that's using a proxy okay and that that is basically fetching the student right now only isn't it but this this way is the lazy one yes yes can you do resume okay so can you tell me right now it is using ego type or legit type okay yeah this one is a lazy type this one is the lazy type right so lately it is instantiating okay can you make it ego and check what is happening so basically can you tell me in the c1 whenever you are printing the student object uh so they are also you are having the child object as well right yes sir but i'm not i'm not using the child object i'm not and i'm not i'm not basically using the student object isn't it but how it is coming in line number 27 and line number 27 basically we we are not using student object but we were trying to do a debug and in debug mode we have hit that okay can you can you um okay can you just run this normally only one curry is getting fired right that's what he was trying to say can you make it can you can you make that face type too one too many is a lazy one and magnet to one is eager one can you make it ego okay can you run this example right now let's see how many queries are getting fired yes correct because by default in one shot only it is trying to face all the data isn't it yeah perfect so here it is basically in one go only it is hitting your database and it is facing all the all the data whenever it is eager type and by default it is lazy type and whenever it is lazy it is only facing the college data but it is not bringing in the student data which are available right so that's the difference between igor and lazy so basically you know uh maybe if you guys are working i mean you guys are already working you should have know that in lot of places we should have master detail view okay so whenever we are loading the master but we are not loading the detail for an example there is a food cat application and you are just seeing the menu of a food but you you don't want to see the detail of the food like you know let's say you only want to see the menu but uh whenever you are only inquiring the menu just show the menu don't give him the details but whenever someone wants to see the details he can click on the view details button and then there is there will be another query will hit the database and will face the detail about that particular menu if that is not needed there is no need to get the details of a particular menu just show him the menu items right so basically in master detail view uh always always get the master data in one shot don't get the master and detail data together okay for performance reason but if it is if your application is allowing that go with eager but most of the time lazy is recommended right perfect thank you yes so let me ask you the next question what what do you mean by generated value in hibernate yes okay so this this is also a designing concept used by hibernate people so generated value is something related to our primary key concept because as we know hibernate internally uses a identifier which is known as a primary key to manage all the entity so generated values are the concept that is managed by hibernate to manage that primary key so basically it has maybe four or five way of managing these values like the auto one the identity one the sequence one and i guess there is also a table one okay okay hold on hold on auto versus identity what is the difference what is the identity uh when you when you define generated value as identity and when you define generated value as auto then what is the basic difference with that yeah so basically when we go with the auto concept okay when we are defining generation type as a auto what does it really do it go with the default implementation or default method that is defined by hibernate people to generate a primary key okay so that means it won't depend on our database to generate a primary key it will generate by itself okay the default implementation used by hibernate people for auto internally is the sequence one if we go with the documentation so internally they are going with the sequence one for the auto one but the auto means you are saying if i if i if i end it in layman term yes then auto means the identity or the entity primary key that will be saving let's say we are creating an entity and we are saving that entity to our database then the primary key generation will be taken care by the framework itself by the hibernate primary yes sir that's what you mean to say in okay what about the identity so the identity one is the concept that is totally based on our database hibernate will first try to understand which type of database we are using okay once it figured it out then it will generate the primary key on the basis of that like if we like we know our mysql uses a identity concept that means each table is going to have a different primary key okay that is a default implementation of mysql okay so when it comes to identity hibernate we will simply check which database we are using and then it will figure out the default implementation of that generated type and then it will use that okay but not sure the bug is still there in hibernate or not but the last time i have checked there is a still a bug in hibernate for when it comes to auto concept even if we go with the auto concept it is calling the sequence one but in reality in their documentation they have mentioned the auto one is the same thing the identity one is doing it automatically check which database we are using and then it generate but there is a bug that why it is internally going with the sequence one okay okay here i'll be asking you two questions okay so if i'll keep all this uh conversation in simple warriors two things identity means it will check have i defined the uh i mean i'm basically giving the primary key generation capacity to my database my database should generate the key for me and that key will be used by hibernate framework or by my entity all right if i am not defining the generated value as identity if i'll be defining as uh you know auto that means my database will not generate any identity key or a primary key for my entity rather the framework will attach the identity key with my entity and then the entity will be set to my database because every time we'll be saving and data i mean id i mean every time you're saving your record to the database we obviously need a id or a primary key attached with a record that's however it worked perfect and you told about sequence right the auto basically you just sequence behind the scene i don't want to go in depth of that right now yes but if you talk about mysql i think mysql you know doesn't support sequence isn't it we sequence means what you know we can store some records in our database just like uh my primary key first should be two let's say after after two i want four to come then six to come then eight to come then ten to come then i'm increasing my primary key by two each time right i'm going with a sequence right i think mysql does not support that but oracle support that yes and sql server support that there we can define sequences in those databases and i think to define those sequences in hibernate we can use sequence uh generated value as well okay we also have one called table do you know about it yes sir so when it comes to a table concept basically to generate a primary key they are maintaining a single table which internally also use the sequence concept okay but there is only a single table that is managing primary key for each entities we do have in our database suppose if we have a student table or a teacher table if we are inserting a element uh first in first row at that time it will generate the primary key one for that student okay and then they it will automatically going to create a sequence table okay that will manage that primary key when next time we are going to insert our record for teacher table even if there is no record in that table what will it do it will simply check that is there any we mean as we have defined the generated type as a table so it will hit that table first and trying to get what is going to be the next primary key because one is already inserted so there will be it will found two so at that moment it will provide two as a primary key for teacher table the next one app three let me go to here let me close out the app too and here basically i i i will ask you a very simple question yash okay because you have already answered me this question and i just want to do a little bit of practical right you have told me about the generated value you have explained me about it right and here in my entity i have an entity called song so here right now the generation the generated type i have given identity as you have told me this is going to be um dependent on my database in my mysql database the table that i have for this song if i'll go into the setting of this the auto incremented or the auto incrementation i have saved it over here now my database will take the responsibility of incrementing the auto generation key or auto generated key of my song the primary key will be assigned by database now my question here is i'm gonna go to my app up three and if i will be put a breakpoint here in line number 27 okay and also i want okay let me put a breakpoint here in the line number 27 i'll do right click run as java application so okay okay sorry why did i run this i want to debug it debug as java application look at this in line number 27 okay i don't want to switch i'll do no as of now yash the data is data is saved in the database or not we have not saved the data now this sound yeah now this will have the identifier or will not have the identifier it will hover on this not yet okay i have the song id will be zero can you explain this line what will happen right now basically whenever we are going to execute line line number 27 what will happen the song object will be mapped to our session object the movement it is going to map to our session object it is going to execute a insert query okay but that query will be only available for our cache that means it won't be committed it will be insert the data into the cache memory so what will happen the moment it is going to insert that record inside a cache memory it will fetch the primary key or it will assign a primary key to the song instance so the moment you are going to execute lineup 27 do you will see that the id is assigned okay let me do a step upper okay so right now if i'll hover over here i have a song id is assigned over here right now this is given by my database and right now that database id is mapped to the song id perfect now you just tell me by this time the song class object is in started to my database are not inserted to my database no not here the line number id 15 okay so should i have id15 because i have already ran the snap method over here no no we won't have it it is it is it will be available inside cache okay inside the first distance context only till 9 14. uh till till song id14 is available so when it will be go into the memory exactly exactly the moment you are going to hit the commit query yes as of now as you have said already the insert has been made by data by by hibernate but it's not committed yet but whenever i'll do step above then only it will be uh you know uh hitting the data otherwise uh it will not it will basically roll back the changes as of now if i'll go to the database i'll see that the commit has been met okay 15 is there kavikavi ykk because this commit has been done perfect now now just coming back to the four type of uh generation type that you have explained me previously if i'm gonna change it back to auto okay now you uh now can you please explain me what this guy will do and if i'll do the same thing if i'll put a breakpoint here in the line number 27 let me let's say copy copy new and i'll say the actor kk new okay do control s i'll debug and put the debug i mean breakpoints m in the same place only in the line number 27 do you think right now the song will have the identifier or it will not have the identifier basic basically the table is already created so the moment you are going to execute this it won't update our table so by default the id will be available but the moment you are going to fetch it will be generate the sequence a sequence number that is already available in the database so you may get the primary key exception because by default it is using sequential mode even if we are defining as a auto so it is internally calling the sequence way of generating id so if i hover over here i'll see the id assigned or i'll not see the id assigned no okay perfect good job because whenever i'll do the step it'll check the logic that you have explained right so it will basically right now automatically okay hold on i did a save okay so i had an exception right now here yes why did i have that exception as i said the table was created by auto incrementation auto incremental mode okay but by default the hibernate auto mode for mysql is sequential mode okay so that's why we are getting that exception perfect it is so it is saying my internet is not stable so can you guys hear me or you are yes but your voice is continuously breaking why are you not telling me we are your student from past one year if you are not be able to understand what you want to say how come you can call us or your student so yeah so maybe i am recording with the camtasia so uh yeah so i think it will not be any problem uh i think your voice is clear cool okay cool so i'm gonna do a resume okay so sorry i'm gonna hit resume and well you can see right now as you have told me for the sequence hibernate is maintaining a table internally and it is trying to find the next value from my um you know from that hibernate sequence table but well we will not go with the sequence this time because i don't want hibernate to manage my you know generation type or generated value rather i'll go with identity so that you know my mysql can do the job for me and mysql will assign the key and it will be automatically mapped to this particular song id when the slab method will happen it will automatically update the song id the framework will update the song id automatically right perfect okay perfect so generated value you have explained everything i'm happy with that next question should i ask you a little bit tricky one right now yes maybe maybe i'll i'll just keep this question for our tomorrow discussion anyhow i don't want to pack anything to the people we're gonna have take one right now we're gonna have another tech tomorrow because we are shooting it in our evening and let me tell you that you know we have rescheduled this interview at least you know 20 times if it is not yes if it is somebody else if if it is me in your place i would have hired the interviewer like okay go away i am not going to give your interview so yours has managed a lot and i just want to thank you very much for that yes uh really really thank you very much for coming in because i'm sure that this is going to help others all right thank you for sharing your knowledge and yes so tomorrow i'm going to give you some little tricky questions maybe i can ask you a few more questions right now uh tell me about the name corey what do you mean by named korean hibernate uh what do you need why do you need named query and what is the importance of that a name query is the concept to use at the rate named query annotation over the entity that we are declaring that means if we want to provide or write a query that we do know that is required for that entity some basic query like select record update record okay so if it pre we know that these queries are going to be required for that particular entity we can go with the name query concept and to implement that concept we can simply mark our entity with add the rate named query inside that we do need to define two property basically the one is like name the name is simply like the alias that we do need to provide for that entity and the other property is the query query is like the simple query a sql query that we want to provide okay and if we have done that so whenever in our dow layer or in a method whenever we want to hit our database but we can simply call the session.createnamedquery method and inside that we only need to provide uh the name of that entity that the alias name we have defined inside at the right name query annotation and simply we need to pass other object the object we do need to perform a pressure on and then yeah hibernate will hit that query perfect what do you mean by criteria api in hibernate criteria api what is the use of criteria api what is criteria what do you mean by a criteria in hybrid so okay that one is tricky okay it's not tricky yeah means no one has to eat it for you yeah maybe i do know what it is but when it comes to our definition but i'm really not good with that okay no problem tell me tell me i i really don't care about definition yeah you know that yes right yeah tell me technically yeah technically technically criteria one is the way of defining which type of query we are defining like the native one or like the hq element ah perfect with the and class name with that what is the difference between sql and sql query and the native query in hibernate or in spring data or wherever it is yeah so when it comes to a hql concept in that way we are simply calling our entity name to hit or perform any operation inside database okay when it comes to a sql we do need to define a table that is available in our database and as as as i told you hibernate is the object relation managing system so what does it really mean because we are defining our entity name that means the object name and hibernate is pretty much smart to understand if we are defining the entity name it is simply check if there is any entity available it will understand that yeah we are talking about that entity and it will use the hql concept to hit database okay and if it is native query so yeah you have to write the exact sql yes table name that is present inside the database basically so basically you are saying that the same query that we run in our you know in our database right let's say we have a sql work uh sql workbench or if you have a uh sql developer or sql server workbench the same query that we write there to interact with our database we have to write the exact same query while we are using native sql in hibernate and um we can use those criteria methods right but if it is your you know the what do we call that sql then you have to mention there the entity name instead of the table name right and you have to generate the sql query i mean the hibernate query language you have to use instead of the you know structured query language right yes sir perfect good job josh um okay so we are wrapping off the session right now and we'll be continuing from tomorrow morning and uh not session i'm taking a mock right so yeah we'll be continuing from tomorrow morning uh well that's it well uh for tomorrow morning i'm giving you another question on hibernate do some research and let me know if you if you know this answer just tell me right now have you heard about the exception called lazy initialization exception don't you know yeah yeah i i i have get that accepted when that exception occurs in hibernate okay cool cross check it and just come back with some more answers tomorrow with this exception right tell me what are the different scenarios when the lazy initialization exception i think i'm pronouncing or i mean just telling you the right exception name lazy initialization exception or lazy instantiation lazy initialization exception i believe yeah you just check that and just let me know what are the different scenarios that exception will offer okay sure cool so we will go with spring tomorrow and yeah that's it let me stop the recording yes [Music] think about a requirement you have an entity called song and you have a requirement that you have to page all your song objects from your database if you want to do that you will be going to your main application so in this class i have just written some base code so that i will have my session object using what i'll be writing my uh you know query so i'll write session.createquery and i will be choosing one of the method and maybe here i'll be writing my query let's say i want to face all the song object from my database the song is my entity name right over here and on top of this i can just do a list right here and this is going to get me all the song list by piecing it from the database so here i'm writing a sql query or a hibernate query language i'm using to face my song object i can do a simple sis out and list over here to face all the all the songs and it's gonna print me all the songs that i have in my database there we go okay so now here i have used the sql to paste all of my song object from my database right now what i want let's say i have the same requirement in multiple places of in my project okay in that case i have to write the similar kind of code that i have written here in multiple places and i have to create multiple sql just like this instead of that you can simply do a cut from here i'll do a control x i'll remove this piece of code i'll go to my song.java which is my entity on top of my entity i'll be using a annotation called named query and choose the first one coming from java extract persistence i'll use the first parameter here as name and this is gonna be the query name and right now the query name is going to be anything i can say my app dot all song because this query that i'll be writing here can i can i give a comma and write query this query that i'll be writing here is going to face all the song from my database right that's why i'm giving a valid name and i'll be using this particular name across my application whenever i want to execute this particular query right now let's go to my application and let's run this query by using the name i'll go over there and i will be using the session object again and i'll be writing say some dot um you know gate named curry and here i'll be giving the query name okay in my case the query name for for this is myapp.olson let me copy that go to app3.java and simply paste it over here and on top of this you can just do a list and this is going to get you the list of object the list of song object that you'll be getting through this particular query okay this is the name but this particular name contains a query that you have defined right over here which is your sql query let's run this and let's try to print this particular list and see that whether we are having our song list printed in our console over here or not ctrl s do it on to this application let's observe the console there we go we got all our song object right over here now it saved us for writing the duplicate query all over our application whenever we need to run this particular query instead of writing this one more time i have written the same query on top of my entity by using the add named query annotation so whenever i'll be using this frequently i'll be just using the name instead of writing the entire query right now here i have a very small query but this query can be really really long okay and maybe if you have any questions okay belas i have three different queries which i use frequently in my application so can i can i use couple of named query annotation right over here can i can i just do a copy and paste over here of course you cannot do that okay you cannot you cannot have multiple named query annotation over here but one thing you can do you can use the annotation called at the rate named queries okay you can see at the right named queries coming from java access persistence go with that and this one will accept a value of you know named queries and this can be an array so you can just copy your all your named queries that you have in your project paste it over here give some comma to separate this and there you go you are done so here you can just give different name for an example for for this named query i can create a different name query like you know from song i want to face all the songs where the artist name is something let's say song s where s dot artist name maybe i'll copy the artist copy that paste over here this is the column name is equal to kk okay so this is a another particular query and you can say my app did all song dot uh kk all right now let's try to execute this particular query by using this particular you know name copy that go to your app three dot java and right over here you can just do my app.all song instead of that paste your new query that you have written over here and run this and right now you'll see instead of all the songs of uh you know you know some different artists right over here you will be getting all the song of kk only so can i run this let's observe the console well we have a unknown column called kk can i go to song.java oh sorry i have to write artist this kk will be in court okay can i go to up3.java run this application there you go you've got only the song which are done by kk right hopefully this is making sense and also instead of doing things like this you can also use some uh persistence method like create named queries which are coming from your entity manager or also you have a session method a method from the session called create named query you can also use this method instead of using get named query so in this case you will be just writing create named query give your name query name for an example go to your song.java copy one of the named query that you want to execute copy this go to your r3.java paste it and give the type that it will be returning in this case the entity object that it will be returning is song and of course right now it is basically a typeset right now if i'll do command one over here and do assign statement to a new local variable i'll have a query over here created which is which is which is a type staff of song so basically i can take this create named query over here and i can just do as list or list to find out all the list of uh in a song uh you know with the criteria that i have defined over here in this named query can i go to my application do a run and the query will run as usual [Music] okay it is basically facing you all the songs because you are running my app.olson and that's the query that you have defined over here [Music] all right here is a simple requirement for you i have an entity over here called song and also i have established a relationship with my database table which is called songs which carries all my song data and here is the entity class for that i'm gonna give you a requirement to you to get all the song objects from my database of course there will be many solution but one of the famous solution is going to be writing a query a query can be a native query a native sql query or you can write query in jpql or in sql perfectly makes sense right now here is another way to query your song object i'll go to my app3.java and here i'll start writing my code and i'm going to show you another way to query data from your database you're going to use your session object for sure and in your session interface you have one api method called create criteria so you can use criteria object to query data and the difference is gonna make is that you can query data programmatically the way you're gonna do that you have to choose the method here called create criteria and you have to give the class name or entity name that you want to create the criteria for for an example i want to create a criteria for my song class or song entity so i'm going to say song.class and there you go says create criteria and i'm going to hit ctrl 1 and assign the statement to a new local variable and i'm going to say create criteria let's let's go with the default name given by my id well so before i'm going to tell you anything let me tell you that this create criteria method i think is deprecated from you know hibernate five i'm going to tell you another way to create criteria um in a couple of minutes but let me just convey uh the message that i want to convey that well the criteria api is used for what it is used to face data programmatically without even writing a query the query will be returned by hibernate dynamically here is an example i have created criteria over here i can say create criteria dot list okay and hit control 1 right over here assign the statement to a new local variable okay and print out this list and this is going to be the list of song which is available in your database if you're gonna run this example you're gonna see in the console all your song object are right now retrieved from the database from song number one if you go all the way uh to the last you can see song id is 15 here so all your song objects are retrieved um and the query has been fired this query if if you are seeing this query this query has been fired by hibernate dynamically not only simple query like this you can also create complex dynamic query for an example let's say i want to give some uh you know order clause for this um entity okay for an example the criteria that i'm creating over here i can add restriction to it i can basically uh do the pagination i can do the filtering i can do whole variety of things here is an example with this criteria object that i'm creating i'm going to say create criteria dot order or add order and i can i can order something for example let's order something let's see that all our song objects right now sorted and is sorted by the id and sorted by the id ascendingly first number one then number two followed by number three and this goes all the way till number fifteen okay let's sort it descendingly let's sort all these things descendingly by song id and if you want to do that here you can add something called order use this order over here and this is going to help you sort properties in in ascending order or in descending order let's say i want to sort something by the descending order and what i want to start with i want to start with the song id i can copy the column name and i can paste it over here and i'm saying that right now with this criteria i have added a order property and here i'm saying i want to order in a descending way with the song id over here let's see that whether it is working right now i have just added one more condition to my criteria do ctrl s run this and you can see right now the way you are getting your query is basically sorted descendingly based on your id 15 14 13 and it will go all the way if you swipe to your right and the last one is going to be the id one okay not only this even you can make it even more complicated you can basically add something called create criteria dot add let me add something over here i will just add some restriction to this and to to do that maybe i'll be creating a restriction over here i'll say restriction dot and you can see you have a lot of methods over here you have variety of methods like you know if you want to restrict by what let's say you want to use some and clause you want to use some between you have to add some equal to you have to add some greater than equal to you have to add some greater than you have to use some like close you know if you want to use some in clause you know there are a lot of different way let me use something called between and let me say okay the property name let's say here i'm gonna give my property name my property name again is going to be song id let's say i want to find all my songs between the number two uh two number four okay between this id i want to find all my song i'll do i'll do hit ctrl 1 i'll assign the statement to a new local variable and maybe just give me a valid name over here make the seek smaller copy this and add it over here to my criteria query and i'm just adding one more condition to this right now we'll see i will not be getting all the you know song over here i'll be getting songs between the number two to number four and also i'm adding one more condition that all these things will be sorted in descending order let's see that whether that is happening or not run this so this time i will not be getting all the records and i'm getting number four number three number two and i think one is not there okay if you're gonna comment this out this time you will not be getting the data in descending order you'll be saying number one will be first okay so obviously number one is not there so you're getting number two number three number four right so you're getting the data in between this particular range just like between you can add a number of different kind of closes over here and the query that you are seeing over here this will be this will be fired dynamically and will be built dynamically by your hibernate okay this is all about criteria not only this i'm going to tell you some more interesting thing let's say i'm going to remove this particular thing and i don't want to use any order by or anything right over here i'll do ctrl s i'll run this it is going to get me all the queries and also here you can basically do pagination or you can do filtering okay for example it will go for a pagination example maybe i will just define some variable here let's say int let's say page size let's say i want to get only four records per page right you you have seen google search right you have different numbers right there zero one two three all are the page number maybe per page you get certain number of data okay so that thing you can define over here and you can set some properties to your criteria for an example right over here to your criteria you can say criteria dot set first result let's say my first result will be start from my zeroth index and i'll say create criteria dot set max result let's say the max result will be base size and of course the page size is 4 i'm defining so what i'm what i'm saying over here try to face the data from zeroth index obviously in my zeroth index right now the song id one object is there and go till the page size okay the page size is four that means it's gonna pick the first four data from number one to uh number four okay the control s you run this and you will see you'll get only four data over here starting from number one and go all the way to it it goes all the way to four change the change the page size is five that means you'll get five number of record uh for one shot okay if you wanna run this you're gonna start from number one and it goes all the way to uh number five right just like that from the second phase you'll be starting showing the data from the number fifth maybe i'll you can just place over here number four uh or number fifth right over here do run this and it will go till number six and it will it will paste you another four records over here till number 10 okay you can also make it dynamic the way you can make it dynamic is basically by defining another variable here let's say int page number okay let's say your page number is 2 and programmatically i'll just give you a formula right now pretty pretty easy and pretty simple formula is called page number -1 into page size that's it let's say right now the page number is 2 and for each pages i want to show uh five number of data during this you'll be seeing that um for the page number two we are showing data from number six till number ten okay for the page number three it will be starting from number 11 you'll be seeing run this it will be starting from number 11 and it'll go till the number 15 okay for each pages you will be having the data and just write this simple formula over here and it's going to work for everything right do do do apply this logic and think about it and this is gonna work for all this thing and of course this particular page number you can fetch it from the end user uh using your framework okay so basically the criteria api helps you to build dynamic query it is helping you to do pagination it is helping you to do filtering and also basically if you have a very complex query and you are doing a lot of string concatenation with those queries instead of that you can follow this approach to create the queries dynamically and of course string concatenation in sql queries are bad because of course if you're doing a lot of string concatenation a hacker can basically inject some malicious data to your sql query which we call sql injection so one of the safety tips for sql injection is do not use string concatenation while you are building your sql query but instead of going through that we can also use criteria api and this is also one of the options and of course the session that create criteria is deprecated maybe it's where you can do something like this so of course if your project is using a higher hibernate version you can do things like this session dot get criteria builder and that's going to help you to get a criteria builder and assign the statement uh to a new local variable now from the criteria builder you just can do create criteria and sorry create query and you just need to provide the class the entire class name for example song.class and there you go this is gonna basically get you the criteria query once you get that do whatever you want to do create curry dot order by you can just do whatever you want to do just the way we have done in our previous lesson so this is basically the best way of creating a criteria query uh in 2021 so basically i'm recording this video in the second half of the 2021 and the previous approach is deprecated so this is the way you can create the criteria query and you can take this object and then play with that and i'll definitely recommend you to go to the wave and check out more about the criteria query i'll be building more and more advanced and complicated query using the hibernate criteria query or the jpa criteria query okay [Music] so [Music] you
Info
Channel: Selenium Express
Views: 24,372
Rating: 4.9035368 out of 5
Keywords: java interview questions coding, java coding interview questions and answers, java interview questions for experienced, java interview questions experienced, top java interview questions and answers, seleniumexpress, interview question and answer hibernate, java hibernate interview questions, java interview questions, interview questions in hibernate, Hibernate interview questions, java interview questions and answers for experienced 5 years, Java mock interview, Hibernate, JPA
Id: -lsFW9Wp2Y0
Channel Id: undefined
Length: 114min 12sec (6852 seconds)
Published: Mon Sep 20 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.