Transcript for:
Advanced Hibernate Interview Questions

hi guys welcome to code decode so today we are going to cover the advanced our interview questions topic which is hibernate so let's get started for that the very first question which will arrive to you in an interview is what is hybrid and why to use it so the hybrid is nothing but an object relational mapping tool so this is orm tool object relational mapping tool used to map java objects which are the objects and relational means database tables so if you have a java object and you have a database table how do you communicate with the object oriented thing with the database thing that is how you do with rm orm so hibernate is nothing but an orm tool now the next question i raises is how does this mapping is done between the object and database tables so basically hibernate provides you two methods so that you can connect with your database tables the first is the annotations which is the jp basically annotations and the second is xml configurations so xml configuration i understand that this is something related to hibernate like dot xml files and all but how come hibernate uses jpa annotations the interviewer may ask how can in hibernate you can use jp annotations so the answer to this question will be that hyphen it is nothing but an implementation of jpa jp is just like an interface and hybrid is just like a class so jp provides you some interfaces on how to do it but what to do but how to do is actually defined by hibernate so this is nothing but an implementation of jpa hence you are able to use the jp annotations while connecting to your objects to your database tables now a very important question which arises in many of the interviewers is that why hibernate why not jdbc as in why do you actually need to move to hibernate if you already have jdbc in place so if you if you like given answers in such a way that yes my project uses hibernate they will really ask you why hibernate why not use the simple jdpc so the answer you will be giving to that particular thing is that hybrid eliminates the boilerplate code now the next question arises what what is the boilerplate code so boilerplate code is nothing but the extensive coding which is required for making the jdbc connection to the databases so many times you have to write the same type of code again and again to do one particular kind of transaction or something so it eliminates the hibernate it does it all for you and you just have to focus on your logics you don't have to need to think about those boilerplates or boiler code plates or the repetitive code that you have to write with jdbc it is actually done under the hood the second important reason why we use hibernate is because of hibernate query language and being an object oriented developer i always prefer uh moving towards the object-oriented technologies rather than using the jwc or the legacy ones the third important thing is that it provides transaction managers in management implicitly so in jdbc you have to manage the transactions by yourself manually but in here uh transaction management is actually done for you by hibernate itself so you don't have to worry about it the fourth important reason why i use hibernate is because it shows adbc exceptional hybrid exception which are unchecked exceptions so i don't have to use try and catch manually if you write jdbc then you always remember that you remember you have to use try and catch and then you have to handle your exceptions there but hybrid actually converts all your checked exceptions into unchecked exceptions and since they are unchecked exceptions you don't have to worry about handling it if some error comes it will automatically let you know the last important reason why i use hibernate in my project and not jdbc is that hibernate supports caching for the better performance i'll be covering this in the later topics the second important question uh which will arise for sure is what are the interfaces that you use in interf in hibernate so there are basically three important interfaces which you use in hibernate the first is session factory so why do you use this particular interface because the instance of session factory is used to retrieve the session object and we need to initialize this once and we can always sketch it and you reuse it again and again but you have to remember one thing very very importantly that the session factory object is per database connection so if you have one for oracle then you have to create another session factory for connecting to mysql or another type of databases so remember session factory with session factory you can get the session object now what is session session is nothing but an interface important interface using hibernate and it is again a factory to transaction so from session your factory you get session object from session you get transaction object and why do you need session object session object is used for connecting your application or the object with the persistent store like hybrid framework or databases so basically it is used to get physical connection with the databases so it's very important thing if you don't have session you will not be able to make the connection to databases and basically it provides the crud operations like create update delete or something for the session part so this is how you make all your operations done on your databases transaction what is transaction a transaction is nothing in interface which is used to specify a single atomic unit of work so you know what transaction is right i can start a transaction i do some particular operation like crud operation i i create something i read from some i read something from database i update something in database i delete something in database what will happen all these crud operations may be part of one transaction and once it is then i can commit it if if it is failing then i can roll back that particular thing so these are the three important interfaces i will show you in a dry grammatical way that the section factory is the parent of all with the session factory you can always get the session object and once you get the session object you can get the transaction object so how do you do that now this was the logical implementation but how do you do it in programmatical way the interview may ask you that so this is the code i have given to you the metadata with the get session factory builder you can get the session factory object so once you have a factory object you can do factory dot open session once you open your session now you can create a physical connection with the databases so with this session you begin your transaction and as soon as a transaction begin you can in the session object you can save something you can get something you can update something you can delete something in databases and once everything is done you can commit your transaction so once you have the transaction available with you with the begin transaction from the session object you can commit it once your transact with this commit your transaction is completed so now you don't need your session because your transaction is completed so you need to first close your session and then you have to close your factory also so remember if you open a new session always close it this is how it is done the third important question which arises what are the annotations used in in the hibernate so these are some inter annotations use the entity why is it at the right entity used edit entity is used to specify that these are entity beans means they are going to be stored in the tables what is this etheric table used for it is used to define the corresponding table name so if on a pojo class you have written the rate entity but it should be mapped to some table so giving how do you say that this particular entity is mapped to this particular table so this particular iteration in the red table is used then what is a excess excess annotation it is used to define the excess type so it can be either field or property the default is field but if you want to use the getters and setters method that you need to set the property then you have to always use accesstype.property and use this particular thing only if you're very sure that you are going to use the getters and setters and not the property or the field itself for getting and setting the values in the hibernate from the table or into the table the fourth important is at the rate id it is used to define the primary key in the entity beam so at the right entity is the class level aggregate table is class level but at the rate id is the field level annotation what is it embedded id embedded id is used to find a composite primary key because every time you are not going to have a single primary key in your table if you have two ah two or three columns making together as a primary key then you have to use iterate embedded id then what is like the rate column it is used to define the column name this is similar to eight derived table so either a table is class level thing it used to define the table name and the red column is a field level thing it is used to define a column name then generated value basically this is used for generation of the primary keys i always prefer the identity one so i have given an example of this this generation type dot identity so this is always used with the conjunction with generator type because this is an enum and it is used to define the strategy with which you are going to generate your primary key values the another one is one to one this is used for one-to-one mapping between the beams and similar to uh this we have one too many many to one or many too many i'm going to cover this in the next few seconds the next is eight direct cascade cascade is used for the uh basically cascading between two entity beans used with the mappings it works in conjunction with the cascade type similarly the last and the very important one is primary key join column it is i'm going to show this in the next few seconds but understand that it is used to define the property for the foreign key so if i have a table employee i have a table address so if address is a pr in case it is a foreign key then you have to use primary key join column on the address so that on you you don't actually end up in adding some of those addresses which are not already in the address table so this is how you use this particular annotations and that was all about these annotations next question that may arise is what are the type of mappings in hybrid so something we have done like a two seconds back i have told you we have annotations so basically we have three type of annotations and three types of mac mappings association mappings in hibernate that is one to one mapping many to one mapping and many too many mapping so what this one to one mapping says i'll give you an example if i have say employee and say i have a phone number so employee has one phone number and similarly this phone number will always be associate mobile number will always be accelerated to one employee so this is one to one mapping only one particular instance is applicable to one particular instance of the another object so one mobile number is associated only with one employee and one employee is associated with only one mobile numbers maybe there can be chances but i'm taking that particular case that it is always one to one mapping now many to one mapping you can always say that uh many employees can stay at one particular address but one address belonging to many employees so that is how many to one works and many too many i'll give you one example here so like what about the code part so that was the logical one that it has mapping of one to one many to one many to many so but how do you explain that to an interview in the coding format so this is how you do in a coding format uh if you have a class employee and i have a private code decode variable and it is one two one mapping so it has one to one with a target entity is code decode dot class uh in the employee class so this is how you make a one to one mapping now what about many to one mapping so i have a student i have an address so i have the example i've just told you that i have many students staying at one address maybe hostel type of thing right so that can be a situation where you can denote it with the programmatical wave would add rate many to one and type all annotation now many too many examples now suppose i have a student class and i have a degree class so i have one student can have my degrees like i can have bsc msc be b tech anything so one student can have multiple degrees similarly one degree is not allotted to just one student so be might be a degree done for multiple students so for one particular degree there can be multiple students enrolled into it so this is how you do the many too many mapping but see one to one and many to one of one to many is is like less complicated because it has only two tables and this is how you map but in many to many there is a third table created automatically into the database so even if you see only two classes a student class and a degree class but still they will be third table created apart from student and degree which will be named as degree student third table which i have given here as of now why i have given that particular thing because i have many too many relationship between student and degree that is student class and degree dot class but how do you actually map these into the databases so there will be third table created named as whatever name you give x y z here and then there are two properties join column and inverse join column so suppose i have student id 1 which is degree 1 and 2 i have student 2 which is also degree 2 and 3 so there will be third table created where it will be one two and one two three so these type of uh mapping will be done in the third table where the join column will be the primary key of the for the the the class in which we are creating so the students i primary key will be joined column and to which you are connecting to with the many too many relationship that is degrees uh primary key will be inverse join column so remember these two are the very important things and this is always asked when you are when you appear for the hibernate interview that in many too many the third cla third particular table is created and basically two two extra fields are added that is join column and inverse join column join column will be the primary key of the current class and inverse join column will be on which you are using at the right many to many relationship that is degree dot class so that will be inverse join column so i hope this much is clear let's move on to the next question the fourth question is this is very important question what are hibernate configuration file so hibernate configuration file is something which looks like this so what why do you need hibernate configuration file because somewhere you have to put your database properties like what is the database and what is the driver so i am using the oracle driver here what is the username code decode what is the password code decode what is the url to connect what is the dialect how do you want to make this auto or you want to make it non-updatable how do you want your mapping resource to be in the xml hbm.xml so all these database conf related initializations are actually done here once you have all the properties here these properties are used to initialize your session factory remember i've told you session factory a second below that it is used to get the session object with which you can create a database physical connection so this with this particular database connections available to you you will be able to create your session object conventionally this is named as hibernate.cfg.xml very important question which is asked in this particular file is fine you have given oracle driver here now i want to connect to the sql uh database this is a different database then what will happen will the session factory work so the answer to this question will be no you need to create another session factory with the different properties because all the properties will be different when it comes to the different databases so if you have n number of database connections you have to create you have to create n number of session factories so this is how you create n number of session factories in your hibernate configuration file the parent is hibernate configuration so i hope i am clear with the hibernate configuration file let's secondly go quickly to the hybrid mapping file this is another second important uh file you have in your hibernate so first what you have done you have actually created your this particular thing um hibernate configuration file but now what will happen if you have all your database connections already in place but now you have to map your tables to your objects then how will you map your object with your table so this is hibernate mapping file conventionally it is always named as whatever your classname.hbm.xm so suppose i want this mapping file for my employee class so this will be employee.hbm.xml similar to something i've shown you here right employee.hbm.xml so this is your mapping file so employee this is my table class name so let's let's start it from the first part does the for the root element is hibernate mapping then the interview may ask to explain all these properties so what you will say the hybrid mapping is the root element the child or the sub child of this hibernate mapping is the class class actually defines the persistence class so employee is my class which i want to persist but in what particular table you want to process so it will be emp table now if you have your class in place the sub child of class will be id because i agree that you at the table must have some primary key and even this should have some primary key so how will you define the primary key with the id the name is id but fine okay that is also fine but how you want your uh tables to generate this particular ids of employee id one two three four want it to be either assigned or something auto generated so that generator class will be defined here so hibernate mapping has 2 has a child which is class then it has a child which is id which is a sub child that is generator class now parallel to id you have property child this this property child is nothing but used to specify the property names of the persistent class say for example first name should be persistent last name should be persisted so that was all the childs of class class tank now this is how you and your root element hibernate.mapping so that was all about the hibernate mapping file you have for any of the class you have for the persistence purpose now the six important question which may arise after this is that now if you know about the mapping files if you know about the hibernate configuration files now can you create a can you give me some simple steps how you actually enter and create a hibernate application so this is very important you should be thorough with your logics that first you have to create a poju where which is nothing but a persistence unit for you say for example i want to persist my employee object into employee table so first you have to create a java object for that once you have created the java object you have to create a mapping file once you have created the mapping file the one i have shown you just two seconds back where we have employee we have class we have generated ids we have properties the one told you with the sub classing thing once you're sure that your particular object is having perfect mapping with the table now you have to create a configuration file so this is the place where you start creating your database connection so this was java this was all java and from here you will start connecting to databases so for creating two database you have to create a configuration file where you will give me the driver name the dialect name and ever the all the session factories that you need for creating the connection to the databases once you have created your database connection the last thing you have to do is to write a class which is a implementing class which is used for storing or getting the data for using the pojos from the table like using pojo you can put some return to table you can fetch some data into your pojo into your java application so you need some utility class for that this is also java part once you have get this you can run your application and you can check your results so these are simple five steps you need for sure to implement your hibernate application the seventh important question which may arise is what is the difference between open session and get current session so this is a very common question which is asked but you need to get into the concepts of it get current session actually returns the current context session that is the current session which is going on so this session object actually belongs to the context of the hibernate so it is okay if you don't close it once the session factory is closed this current section will automatically get closed so you don't have to explicitly write a close code to close it but while you use open session remember while this this particular method is used you always create a new session and you don't use the session which is already in the context of hibernate so once you create a new session you have to make sure that you also close it once you are done with all your applications so closing this this particular session is very important and also you should open a every new session if you are using a multi-threaded environment so every time you get a request you have to open a new session for it in a multi-threaded environment eighth most important question which arises what is the difference between get and load method so both the methods are nothing but actually used for getting some data but get loads the data as soon as it is called but load actually returns a proxy object and loads data only what is actually required so very first important difference between both of them is uh the load actually supports lazy loading and hence the performance of load is far more better than get but if this is so good why not i should use load only why do you need a get because load throws an exception whenever you don't get a data in the database so if you're very sure that you are going to get the data then only use load otherwise it will give you an exception and your code will block then and there so that is why you can use get because when you want to make sure that yes data is there if you're not sure that okay data may be there may not be there but i just want to know whether it is there or not you can use the get method so if you have if you're very sure that you know the data is there in the database you can use load because it is very good in the performance wise because it is lazily loaded but if you are not sure the data will be there in the database or not and you don't want your application to abruptly stop then and there use the get method okay now the last thing which is very important part of the whole hibernate thing is the question part so the interviewer will for sure ask you like this is like 100 surety that if you are giving an interview for hibernate they will for sure ask you about caching part because this is the very important property of hibernate so the first thing first what are the types of fiber net caching you have so there's a first level cache second level question query level question so now the questions won't ask here we won't stop here the questions will move ahead and they will ask you what is first level question what a second level question query level question so let's get started for the one by one questions for rich and the first level question is nothing but it actually is firstly it will ask you why caching why why not jdbc or simple no caching technique so caching is nothing but it used to make our application faster and improves the performance because if you have some data into your cache you don't have to go hit the database again so the basic idea behind caching is to reduce the number of database queries if you have less number of database queries you have lesser number of hits to the databases and hence your performance will automatically increase because time will automatically get reduced so the hibernate has the first level cache which is associated with the session object so remember the session factory gives you the session object that such a object automatically has the first level cache associated with it and it is by default enabled and there is no way you can disable the first level cache hence hibernate actually gives you some performance by itself by giving you the first level cache automatically enabled into the session object but do you think there is any way through which you can delete the session object or uh a way where you can clear the cache completely yes st cybernet is not that inflexible for you it actually hybrid provides you some methods which with you can actually clear your cache completely and then you can start overall again so any object cached in a session will not be visible to other session why so this is a very important interview question so a interview may confuse you or trick you with asking that if the first level cache is associated with a particular session object will that a particular object which is being cached will be visible to another session or what will happen when the session is closed so the answer to this will be that if you have something enabled in your first level cache an object in is in your first level question then that won't be visible to another session simultaneously if in case your session is closed all the cashier object in your in the first level question will be lost so this is very important thing to understand about first level caches so you understand that as soon as your session is closed everything is gone that is why there is a concept called the second level cache now second level cache is basically by default disabled but we can enable it to configuration i'll tell you how and there are basically few implementations for enabling the second level cache the two important such level caches eh cache and infants man provides the implementation for the second level caching we can use them but i always prefer eh cache over everything because the performance is far more better so even if you say that yes you prefer eh cache he will for sure ask you how if you have used eh cache in your project how did you use it so the answer to this question is very straightforward there's only four steps required the very first step is that you need to first enable eh cache by using the dependency in your maven project or if not then you have to implement it using the jars and add it to your build part so hibernate each cashier of over dot hibernate is the way you how you can implement your eh cache in your project in the memorized project if not then a jar of it this was first step implement each cache jar the second step for the same is to add the below property in hibernate configuration file i have already shown you configuration file now in there only you have to write these particular line of codes that is your region factory so this particular is nothing but your eh factory what do you do with the factory class you actually get your object of each cache simple as that now the second level caching yes i want to make it true if you make it false your second level cache will not be enabled your query level caching you should always use remember this is a very important interview question query level cache should always be used in conjunction with second level cache only query level cache will never work with first level caching so for making a query level cache it row first make the second level cache now what is the xml file where all your eh caches can like um configurations will be done so that would like for me it is code decode eh cache.xml file so you have to give your xml file name here in your hibernate configuration file where you have one object created for uh the factory where you will get the eh cache object then you have your first level second level cache enabled your query application enabled and your file name where you have eh cache enabling properties available so the third important thing which is very obvious from here is you need to create your code decode xml so before creating this eh configuration file i have given you a sample of it but first understand because if they particular the particular interviewer may ask you to explain whole eh cache configuration file for that you need to understand that the very important thing is disk store so what will happen if my cash overflows say i have 10 objects capacity on my caching but i have to question 11th object also so this is the path where my overflow and cache data will be stored okay then the second important thing is the default caches so this is actually the place where all your regions will be decided or if if there is something called as default caching place so the total time and id is time to live these are the default and this is the very important configuration this is compulsory configuration you have to give so this is the default cache regions properties that you define here now question name equals to employee so this is nothing but caches region so there is some region in cashier right so in that region i am defined that maximum entries are thousand the time to live is 10 and the strategy will be local time swap but it will be very easy if i name this particular cache region so i've given it a name as employee so this is how in the configuration file you define different regions in your whole cache this is how you define how my cache will look and how what will be the region so these basically two more regions standard query cache region all my queries will be actually query if this is a standard query reason then all my queries will be cached here there is update timestamp caching this is another region where you will have your update timestamp cache with all these common uh persistent strategies so we have seen three steps there the first one was to get your dependency the second one was to create the configuration file where you define where my ehk says all xml configurations will be there then you have to define that particular xml file and the last or the fourth step is now use your use your caching technique so how do you actually use your caching so i have my entity entity i've already shown you this like we have some classes the pojo which is to be persistable with accurate entity you have a table and then this is a very important thing where you use your caching part at the rate cache usage is this particular strategy which defines how your strategy for caching will be and the region name so in the previous side i've shown you that in a whole cache part you have different regions and you have name this that region with name equals to employee i have shown you right so fk name equals to employee you remember this name employee this particular name is actually used here and whatever data is required to be cached this particular name of uh region will be found in that particular cache location and all your data from this particular cast will be cached or stored into that particular region only so this was all about how you enable eh cache in your application if you want me to give you a live demo on this please let me know in the comment section this was all about i have for this particular hibernate questions because the time is running out if you need more of such questions please let me know in the comment section then only i will create a second session which will have the high level interview questions for the hibernate only if you allow me in the comment section then only i will create the second part with the high level hibernate configuration questions for you that's all thank you and we'll next we'll meet in the next session thank you