JPA And Hibernate Tutorial For Beginners with Spring Boot and Spring Data JPA

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to this video from in 28 minutes thanks for helping us provide awesome learning experiences to more than 300,000 learners across multiple platforms udemy Safari and pact let's welcome our lead instructor Ranga Rao Khurana welcome to this section of the course JPA in 10 steps in this section we learn the basics of JPA and also how it compares with the earlier attempts of storing data to database how does it compare to JDBC how does it compare to spring JDBC and mybatis we will understand the basic concepts of JPA entity mappings entity manager and also relationships we'll also understand how spring data JPA makes it easy to use JPA to make things easy for us we'll use an in-memory database h2 the whole folder for this section of the course is inside spring web services there is a folder called JPA in 10 steps if you go in here you'd find the details of each of these 10 steps a few useful links related to h2 concern and also the complete code example at the end of this section will again start looking at restful web services and enhancing them to connect them to JPM I am excited to introduce JPA to you I'll see you in the first step welcome to this video where we are going to discuss a little bit of theory about Java per citizen the API what we want to understand is what is the problem that Java persistence API is trying to solve and what will the alternatives to java persistence api and how does java persistence api solve that problem that's basically what we would want to understand the next couple of steps will be little bit of theory if you are a hands-on guy then it might be a little boring for you but I think it's important to understand the theory behind Java persistence API what is the problem that Java persistence API is trying to solve think about it the programming language we are using is Java we want to take data from Java where you want to store it in the database how are databases designed these databases are typically relational databases right nowadays there are a lot of big data and other stuff no SQL stuff which is coming into picture but even now for the most part we use relational databases and in relational databases we use tables in Java side we have objects on the database side we have tables how do we store data from objects to tables the way we design java programs is using object-oriented programming so we use object-oriented concepts however on the database we use something called normalization object-oriented programming typically consists of concepts like encapsulation inheritance interfaces polymorphism and things like that however when we talk about relational databases we are talking about things like tables foreign keys primary keys first normal form second normal form and third normal form there is a mismatch between these two there is a mismatch between how we design objects and how we design tables but we would want to establish a relationship between them you would want to establish a mapping between them let's consider a few examples of this impedance mismatch I have a very simple example here I have employees and tasks right so you have an employee who can have multiple tasks a task which can be associated with multiple employees and what we would want to think about is what are the possible mismatches when you are trying to map this problem statement to objects and tables let's look at the first example right first mismatch is in terms of the basic details an object is made up of fields table is made up of columns how we name the fields is different from how we name the columns for example here we using des e and here in the table the column is description here we calling it target date however in the table we are saying its target underscore date Easter is underscore done this is kind of a basic trivial example let's think about relationships between tables relationships employee can have multiple tasks and a task can have multiple employees associated with it so how do we represent it in Java employee we will put a list of tasks to him so employee class will have a list of tasks this is how we put it and a task is associated with a list of employees this is how we recognize that in the Java world in the object-oriented world how do we do that in table typically in a table employee tasks we create a new table called employee underscore tasks and show the relationship in there so the way we design the tables is different from how we design our classes or objects how do you take data from here and store it in the table and the third example is multiple classes are sometimes mapped to a single table so here we have employees two kinds of employees full-time employees and part-time employees full-time employees have a salary part-time employees have a hourly wage and you can see that these extend employee there are three classes here but when we talk about tables we just have one table we have an employee type to distinguish between full-time employee and part-time employee and we store the values of the part-time employee in hourly H so this is one of the attributes which is specific to part-time employee and for full-time employee we are storing this salary the data from these three classes has to be stored to just one table until now we were looking at a few examples of object-relational impedance mismatch what we were talking about is the fact that how we design our objects is different from how we design our tables and that's really the problem that all persistence frameworks have been trying to solve typically frameworks which use to solve the persistence problem were jdbc spring JDBC and my Baptist in the next video we'll look at how those frameworks try to solve the problem of object-relational impedance mismatch the last video we talked about object-relational impedance mismatch we saw how we design tables is different from how we design our objects we discussed that there are three options that were used before JPA JDBC spring JDBC and mybatis in this video we'll get a introduction to how JDBC spring JDBC and mybatis solve the problem if you are already familiar with that you can skip this video and move on to the next video where we would be discussing about JPA the other approaches before JPA what JDBC spring JDBC and my batteries in JDBC spring JDBC and my VAT is what we do we write queries once we write the queries we need to do two things one is these queries have parameters so over here if you look at it these are called parameters I blade to do set user is equal to something so these are all different parameters so I would need to populate these parameters so once you write the query you need to set the values for these parameters the other thing I would need to do is once the query is executed for example I am executing this query right so I would need to take the values from the query so the results are coming back in the result set I would need to take the values from the result state and store it to DB in here at the beam is to do so I would need to take the values from the result set and put it to the beam if it's a update or a delete query then you don't really have any results coming back but if you are doing a select query then you have results back so you need to take those results and populate into your Java objects or beans how did JDBC do that JDBC is basically Java database connectivity and the way that did it was through things like statement prepared statement result set etc so what we do is we write a query so we write a query and then we had to create a statement or a prepared statement for it and set the parameters into the query set each value so we said the value here is 1 the value here is 2 here is 3 and so on and once the query is executed if it's a select query then we would need to get a result set and we would need to map manually what we would need to do is to do something like this we would say we'll get the result set and then take the values from the result set and put into the beam so we are explicitly doing that in here you can see that I am actually taking one by one from the result set and putting it into the beam if you look at the code that we wrote with JDBC it was a little complex right so just to update something just to do a simple update I had to write like 15 20 lines of code and I am not even talking about exception handling code in here this kind of becomes really a lot of code that I would need to write what spring JDBC did was it tried to provide a layer on top of JDBC instead of using low-level things like statement prepared statement other things the EBC said I will provide you a JDBC template you use the JDBC template if I wanted to do a update I still had to write the query the basic approach is still the same you had to write a query but what JDBC template did was it made mapping parameters to query very easy so it said okay you can call JDBC update with your query and all the parameters what I will do is take the first one and replace it here take the second one and replace it here take the third one and replace it here and also it introduced a few simple concepts like row mappers by default if your names match then you don't really need to create a mapper at all so then you can use something called bean property row mapper but if you want to define a mapper then go ahead and create a to do mapper once you create a mapper this mapper can be used in multiple queries over here we are using this to do mapper to map the results from the query to the beam so what it is written is it to do you can see that all the logic I would need to typically do in JDBC I don't need to do that when I am using a JDBC template so what did spring JDBC do simply provide a simple layer on top of JDBC so that I can easily map parameters to queries and easily take the results from the result set and map it to Java objects or beans now what's the other framework which came in my batteries actually sometimes people call my batteries as an ORM framework object relation mapping but I don't really think it's object relational mapping framework because it's not really mapping objects to tables what it does is it Maps objects to queries mybatis provides a simple XML or annotation based configuration so whatever mapping that we did earlier from your parameters parameters to queries and taking values from the result sets and putting them to beans what we can do with mybatis is you can do the same stuff using XML or simple annotations in JDBC you are spring JDBC what we used to do is we used to write queries like this so we used to put question marks and we would use to replace the values but what mybatis did is it provided a simple mapping framework so instead of question mark I would say hash user and you what is user user is the name of the attribute in the beam for example over here you can see target date target date is equal to target date and what is targeted target date is the target date from the beam if I wanted to use this query it's very simple I just need to say I want to update I want to use this update query and use this beam because you have already mapped the name of the field in here I bet this would be able to recognize that and execute the update statement for you we took a quick look at how things were done with JDBC we took a lick quick look at how things were done with spring JDBC and also my bat is the fundamental thing for all these three approaches was the fact that they are still based on queries right we still write a lot of queries the problem with queries is when relationships between tables change then you have to modify all your queries have worked in a lot of applications where there were lot of big big queries which were written like have worked in applications where there were queries of 100 200 lines of code and understanding these and maintaining these is a really tough job you need to really have a great understanding of how things are done in the database to be able to write these queries and that's the real problem the problem was the query were becoming so complex that it was difficult to really maintain them and whenever there were changes in the relationships between tables it was really becoming difficult to maintain these queries that's the world where JPA stepped in in the next video we'll look at half JPA tries to solve this problem welcome to this video where we would try and understand how JPA solves the problem of object relational mapping the problem we were talking about is the fact that the application classes the way we design our objects is different from how we design tables on our database so the way we design this employee tasks part-time employee full-time employee objects is different from how do things on the database task employee employee tasks so how does JPA solve the problem JPA provides a mapping you can map application classes to tables you can say this class maps to this table with JPA you'd be able to define mappings between your classes and the tables using things like entities relationships you would use something called an entity manager to manage your entities I would want to save a task to the database I can use entity manager give it a task object and it would be able to save it to the database I would want to get the values of a certain amount of tasks or I would want to get the values of all the tasks related to a person I can use the entity manager JP also has these features of criteria API and JP QL which provides additional ways of finding data from your database so I would want to find some data from the database I want to do some certain kind of searches against the database then instead of using SQL you can also use jpq l or criteria api to query the database jb ql is similar to SQL however you would be using entities instead of tables in jpq l and criteria api represents a way where you can write JPL using java api s-- before we get our dirty with JPA we'll look at a few examples of how you can map application classes to database earlier we looked at an example where in the task table there was a mismatch of how things were in the task class or the task object and the tasks table how do we solve that JPA provides annotation so here there's an annotation called at table the at table annotation helps you to map your object to your table so here I'm saying okay this task is going to be stored an instance of class tasks would be stored to the entity tasks I'm representing this as an entity by putting an at entity annotation on top of it and also I'm saying this ID is a primary key by putting an ad ID and on top of it I am saying this description field which is present in here should be stored in a column called description so that's how we map so we are saying description target date so in the table it's called target date so how do we map it by putting at column name is equal to target date so this is a simple example of mapping fields to columns you can also establish relationships between the different entities so employee is an entity task is an entity we already looked at the fact that they have a many-to-many relationship you can use an annotation called at many-to-many so here I'm saying at many to many and at many to many this establishes many to many relationship between the employee and the task class and the third example which we looked at was the full-time employee and part-time employee these classes are all mapped to just a single table in the database they are all mapped to employee so JPA provides a inheritance mapping so it says I would want to use an inheritance mapping the strategies one table all the subclasses of employee are stored to one table and we are also saying how do we distinguish is using the employee type so we are also saying that in here so we are using the discriminator column is employ eat in the specific step until now we look at a few examples of how JPA provides mappings between your objects and the tables the most important thing that you need to understand is we are just trying to highlight a big picture of how things are done with JP if you are not able to understand these things at in-depth that's not a problem at all we are going to do a lot of this stuff step by step in the future steps in this step we took a quick overview of the big picture of JP a we saw how JP a helps us to map or objects to tables we looked at how we can map specific attributes specific fields to table columns we looked at examples of how to map relationships and we looked at how to map inheritance relationships between objects as well the idea behind this step is to give you a quick flavor of what you can do with JP a we have not really got our hands dirty yet in the subsequent steps we'll start getting our hands dirty welcome back it's time to get our hands dirty in this step we will create a simple project using spring boot we'll use something called springy initializer spring initializer is very useful to create your spring boot projects very quickly we would want to use maven so I'll use maven project languages Java and I would use a spring good version of 2.00 snapshot I think any of the versions which are greater than two point zero point zero should be fine so you can just go ahead and choose snapshot on any higher version of two point zero point zero that should be cool and I would want to use the group comm in two eight eight minutes learning JPA and let's use the artifact ID JPA in ten steps one of the things that you need to choose when you start creating a spring boot project is what dependencies you would want what the hata projects you would want to use let's add in a web because at later point we want to address services so let's add in web and we would want to use JPA so i'll you right JPA in here and press enter and the other thing which we want to do in this specific example this user in memory database in memory database provides you a lot of advantages compared to installing a real time database we will discuss a lot about in-memory database as we go on so we'll add an in-memory database the in-memory database we are going to use is h2 so I'm adding H dude we chose maven languages Java any version greater than two point zero point zero of springboard should be fine and we gave a group idea of in 28 minutes learning JP a common 28 minutes learn in JP and use an artifact of JP I in ten steps we chose web JP a and h2 as the dependencies and we are ready to create a project enough so just click generate project this would download a zip you can unzip the zip to some folder your hard disk and open up your eclipse I'm clicking generate project this would download us zip into my local machine I've opened up Eclipse and I'm ready to import the project in so I would need to say file import existing maven projects actually I want to use existing maven projects and say next I've copied the folder where I have copied the zip file to I have extracted my zip file to this poll of all JPA intense steps so I just need to copy that folder in here or you can even browse to it so you can click browse and browse to the folder ok I've done that and you can see a project coming up in here so this has our group ID and our artifact ID so JP Haynes 10 steps and we use the group ID common 28 minutes learning JPA I can click finish when you click finish what may when does it would start to download all the maven dependencies inside our dependencies we have chosen web JPA and h2o web and JP are actually starter projects spring good starter web and spring good starter JPA this would spin good starter web would help us develop web applications jps would help us develop JPA based stuff there are a lot of dependencies that spring would need to be able to set these up what is happening in the background right nervous all these dependencies would get downloaded and a project would be created this might take a few minutes so be patient and once the entire thing is set up you'd be able to see simple things like this so you should see a source main Java with a simple application file in here source main resources with an application that properties and you should see a certain Tower with a simple test which is present in here you can see if you open up the maven dependencies there are a lot of maven dependencies which are present in here the most reported dependencies as far as the hibernate and JPA are concerned a hibernate JPA API and the hibernate core fight or 2.10 final Roger these are highlighted in the screen right now one of the questions frequently in the minds of people who are beginning to learn JP is how what's the relation between JP a and hibernate JP a is a interface JP a is a specification hibernate implements JP a it's like you have a interface and you have classes implementing that interface similar to that JP a is an interface and hibernate is an implementation JP a defines all the annotations so these are the different annotations which you can use these are the different things you can use to different criteria queries these are the different things that you can use define attributes that's what JP a defines and hibernate provides implementations to all these con ceps once you map an object once you put all the annotations on a class hibernate would be able to read them understand them and would be able to save your entities to the tables hibernate is one of the most popular ORM framework so our M is object relational mapping and JPS standardizes ORM so JPS says ok this is the way we should do o RM this is the way you should define mappings between objects and tables what does the API do it says ok this is the way you define entities this is the way you map attribute this is the way you map relationship between entities and this is the way you manage the different entities that's basically what JPA does hibernate is the implementation whatever JPI defines hibernate implements it let's get back to what we were doing you are setting up a simple project so let's start this and see if it starts up fine so the way I can execute it is by saying right click run as java application and you'd see that the application would start up we are not really defined any entities as earth enough we have not really mapped anything we have not created any tables or anything of that kind for enough let's just start the application just it should not do anything right now the application starts up you can see that in here we are using Tomcat as the server because that's the embedded Tomcat which comes in built in with spring boots strata web and we see that the application has started up what we'll do in the next steps is we would start adding more features we will start adding entities and try mapping them to tables [Music] welcome back in this step we would start looking at entities in the previous step react set up a simple project there are things which we need to still understand about that project will understand them as we go and now let's focus on creating a simple entity what we want to do is to create an entity called user let's create a simple class so class name it as user I would want to store it in a separate package I would want to just say this entity and say finish now you'd see that the user is created in a package called entity that's cool so this is where we would store all our entities in this the package where we would put all our entities in and user is an example entity what we want to have is a few attributes in the user so I would say first thing is an ID so I'll say instead of public actually should be private private long ID and I would want to store a couple of attributes of the user private string name and private string one thing you need to understand is this is not really perfect designed because a name might have first-name lastname and other stuff so you might really need to actually have a class called name ideally you would want to have a enum defining that lets keeping simple for now so let's just have strings and I would also generate the getters and setters and stuff like that so what I'll do is right click source and say generate getters and setters I would only want Gators so I'll say select getters and say ok I will also create a two string so right click source generate tooth string and say ok it would generate a two string method for us and also what I'll try and do is to generate a simple constructor so generate constructor using fields ideally we will not use an ID field in the constructor so I will remove the ID I'll use the other fields so we have a constructor in here it's a simple constructor two parameters name and role one of the things that JPA expects in every class is a default constructor so if we create a constructor like this then we are overriding the default constructor which is why did JP I expects a default constructor so let's go ahead and define a simple default constructor as well so this is just like a simple bean there is nothing JP a specific in it right now it's a simple bean it has three attributes ID name and role it has a simple constructor accepting name and role and it has a couple of Gators and a two string method this is very similar to any bean that you define there is nothing JP a specific in here so now I would want to take this user and I would want to store it to a table called user in the database so I would want actually take the data from user and be able to map it to a table how do I do that then I would need to make this an entity so if I want to be able to store this user to a table then what we need to do is we need to define an annotation that's at entity as we discussed earlier we are going to use the Java X dot persistent Java X dot per disk persistence is the package where Java persistence API annotations are present so I'll use Java X dot persistence entity you can see that that's imported in here so entity specifies that a class is an entity this is something which should be persisted to a database what we'll do is we'll also want to say this is a primary key how do I say this is a primary key by using another annotation called @ ID user has a primary key called ID this becomes the primary key one of the things I would want to do is I don't really want to assign the primary key so I would want this to be generated how do I make this to be generated by saying it's a generated value I'm adding an annotation saying this is a generated value so until we have created a simple entity called user we added an annotation called entity and we added couple of annotations on the ID field ID and generated value to say that this is something which is generated once we have created an entity you need to be able to save this to a database how do we store entities to the database and get them from the database if we we do that is by using something called entity manager in the next step we would start defining a service to get these values from the database in the last step with the simple entity we would want to be able to save this entity to the database what we would need to use we need to use an entity manager to be able to save this user entity to the database I'll create something called a user service so let's say you use a new class we want to call it user Dao service so we're creating this a Toa service in the sense that the data access object so this is something which helps us access data from the database so that's why I'm calling it user Dao service I'm clicking finish one of the things is I would want to move this to a package instead of dot steps I would want to actually create it in a service package what I've done is I've moved the user Dao service to the package jpn 10 steps service so now we have this class and in this class we would want to be able to manage user entity would won't be able to save users and retrieve users from the database one of the first things that we would need to do to be able to get the values from the database is create an instance of an entity manager so I'll create a private entity manager I'll import Java exposition sample entity manager with this entity manager I would want to be able to save data to the database so I'll create a save method public long insert and this would accept a user and save the user down to the database let's import the user how do I save an entity to the database user is an entity right there is an annotation at entity defined on it how do I save it entity manager provides a method so entity manager dot persist versus this the method which can be used to make an instance managed and persistent I'll say persist and what we want to do is what the user is persisted we want to return the ID of the created one so user dot get ID this user Dao interface is something which helps us store things to the database in spring we call that that kind of component as a repository so a repository is an annotation which is defined in Spring Framework so you can look at it or Spring Framework stereotype proposed to indicate something which interacts with the database the other thing is when we want to insert we want to modify something to the database you need to be inside a transaction what we need to do is we need to be able to do something like open transaction here open transaction make the change whatever changes that you would need to do and then close the transaction instead of implementing transaction management in each method what JPA provides is a simple interface to do declarative transaction management the way we can do that is by saying transactional so you can use this annotation on the class as well as on the methods we are using Java X dot transactional that's the thing which is imported so this says each method would be involved in a transaction the important thing that we need to understand is the concept of a persistence context and how it relates with the entity manager if I say user jack is equal to new user jack admin it creates an instance of the user Here I am creating another instance Jill I'm saying entity manager dot persist Jack so enough jack is something which is managed by the entity manager into the manager is actually a interface to the persistence context when I say something that persist Jack what it does is it says it to the database and also starts tracking it in the persistence context Jack is now inside the persistence context so whatever changes I make to D Jack are now being tracked by the persistence context important thing to understand is entity manager only tracks those objects which are persisted through it so here I'm creating something called Jill and Jill I am not doing anything with the entity manager to Jill and I'm saying Jill dot set role changing the role of gel this will not be tracked by the entity manager only those things which are in the persistence context are tracked by the entity manager so we need to put an annotation so that this is Auto white so what is the N in its persistence context so I'm going to use an Java X annotation Java X persistence annotation persistence context this is cool right so I have a service which is having a simple method called insert to save the user now I would want to be able to call this and be able to save this data down to the database let's do that in the next step in the previous steps we defined our entity called user and we created a do service to manage this entity I would want to be able to call this Dao service at some place one of the things that we have already set up is a simple project which launches a purse Pring context so this project because we created using spring boot and uses use a spring boot started this is already starting something called the spring context what we can do is at the launch of the spring context we would want to insert a user in how do we do that there's a concept called command line runner so these command line runners are typically executed when the context launches up when the spring context launches up you don't really need to worry about the context of right enough all that you need to remember is the fact that this command line Runner launches up when the application starts up so whenever we start the application the code in the command line runner gets executed let's create a simple command line runner I will call the new class user because I'm talking to this service so I'll say user Dao service command line right now this command line runner I would want it to be managed by spring so I'll say add component and input to make it a command line dilemma I need to implement an interface within interface as you can guess is command line so I can import the command runner in now I have to implement a method called run so I want to implement the run method inside the command line runner inside this run method I would want to be able to save the user so I would want to be able to say user user is equal to new user of Jack I would want to give him a role of admin I would import the user in and I would want to be able to do a persist for this I would want to be able to save him to the database how do I save him I would need the user Dao service I'll say user Dao service I've created a simple instance of the user da service I would want spring to auto wire it in I'm saying import auto world that's cool I'd want this user data service user Dao service to save this data so how do I do that insert user one of the important things is the fact that these user Dao service also returns the ID back so what I'll do is I would want to log this ID so I would want to say like lock the ID which was created to be able to log it I would need a logger so what I would have done is I've used the log of factory get logger for this specific class actually it should be here so it's User Dao service command line run another class I am getting the logger I'm using a cell f4 J here so I'm going to use SL for J it's love for J we created a simple logger so we can log this stuff out so now I would say log dot info and I would say new user is created plus user okay let's take a quick look back at what we are doing so we implemented the command line interface command line internal interface because we would want this to run at the launch of the application we added in a user Dao service because that's what allows us to insert a user we created a user who is called insert user and we are logging it that's basically what we have done until now let's launch the application and see what happens right click run as java application if you get a port conflict what you need to make sure is that you kill the earlier instance which was running I've already killed that instance and started a new one enough so let's see what happens it's starting up and one of the things that you would see at the startup in the log is the fact that it prints a new user so new user is created user ID is equal to this so this is present in the log so what we are able to do now is we are able to successfully save something down to the database the thing which you need to understand here is the fact that we have not really created a database yet how is this magic happening where is this data really getting stole to where is the database present do not worry about that we'll look at it and more in the next step until now what we have created is very simple right we have created a simple entity called user we have created a service called user Dao service to be able to manage the user and we are calling Dao service in the command line runner so at the launch of the application we are calling this service to be able to store the user in and we saw that the user was created fine this is a lot of magic that is happening what's the magic that is happening in the background that's basically what we would look at in the next step [Music] you in the previous steps we created entity we created a dhow service and we created a command line runner to be able to save the data down to the database however they were a lot of unanswered questions the first one is where is the database created what schema is used to create the tables where are the tables created and so on and so forth in the step let's answer all those questions the simple answer is all the magic is happening because of spring boot and it's startup projects let's open up our pond rod XML when we created this project using spring initializer at star dot spring dot IO we chose three important dependencies we chose a web it shows a start a call start a data JPA and we chose h2 as the database let's focus on the in-memory database first that h2 typically we are used to databases like my sequel Oracle for all those kind of databases you need to first install them on your machine then create the tables and then you'd be able to save the data from the application this would mean that there is a lot of setup involved at the kind of data bases called in-memory databases these databases are directly created inside the application the schemas are defined the tables are created the data is populated and once the application stops the entire database is destroyed and removed from memory the great thing about these databases is you don't really need to maintain them I don't really need to install manually I don't need to install the tables in there and all that kind of stuff I'm going to application that properties this is where we can configure this springboard application and what I would want to do is spring dot JPA dot show SQL I'm making it true so I would want to show the SQL which is generated and the other setting I would want to turn on is something called spring dot H 2 dot console dot enabled is equal to true I would want to see the SQL which is generated and I would also want to enable something called H 2 console let's drop the application and start it again there are a few important things that you would see you would see that there's a sequence being created and the table being created as well there's a sequence called hibernate sequence and the table called user being created the other thing you would see is that there is a insert into user name role ID these are the queries which are being executed I can see them now because I turned on logging for queries I said spring dot JPA not show SQL true we can see that the tables are table is created and the data is inserted into it can I see the data in the database one of the important things that you need note is the URL is localhost 8080 /h - console so it's H - - console localhost 8080 H - concern and we need to use a DB URL of JDBC hits - mem test baby so Jerry we see H - mm - 2 DB so I'm going to H to console you can leave this as a default so if we want to connect to the generic H - embedded and this is the JDBC URL so we are putting a JDBC URL of JDBC H - mm test DB and I'm saying connect enough you can see the database you can see the user table the user table is created ID name and role can do a select star from it so I am doing a select star from it and you can see the row which is inserted in what I would recommend you to do is to play around with this we saw that the database is created in memory using h2 we saw that this keema also is being created at application startup and also we saw the tables which were created we saw the data in the database as well even then a couple of important questions remain who is creating the data source how is this keema being generated answer to all that is spring boot and the auto configuration of springboard so the magic the entire magic is done by spring boot Auto configuration to be able to understand spring boot auto-configuration much more what we'll do is we'll turn on debug logging logging dot level for org dot spring framework so first spring framework i'm turning or logging level to be debug that's basically what we are doing in here and let's restart the application if you look at the log now because we turned on the bug logging you'd see a lot more logging there is something called an auto configuration report which is printed I'll extract a few things from here here is a quick preview of what we observed in the log one of the things is spring boot is intelligent it identifies if you are connecting to in-memory database or not since it saw that there is h2 on the dependencies list it has configured in memory database h2 you're using h2 in memory database the spring booth knows that if you are using an in-memory database then you would want to initialize this schema so it is able to understand whether your database is embedded or not so it sees ok you are using an embedded database so you would want to initialize the database so it uses hibernate property called create drop so it creates the schema application launch up and drops the schema when the application is terminated that's number one the other auto configuration staff that is enabled is hibernate JP or Auto configuration because we have hibernate on the classpath hibernate JPA auto configuration is triggered other things which are auto configured are a data source there's a data source which is auto configured and entity manager con factories auto configured and the transaction manager is auto configured if you actually look through the log there are a lot of other stuff which is auto configured by spring boot what we are looking at some of the important things that are auto configured from the perspective of JPA and hibernate auto configuration is a very important feature of spring boot spring good what it does is it looks at the classes which are available in the class what it looks at the jars which are available in classpath and it decides what is the best configuration for you for us it decided that because h2 is in the class path because hibernate is in the class but I'm going to use hibernate with JPL so I'm going to use hibernate as the default implementation for JPA and it also decided that I would want to use H 2 as the in-memory database and it auto configured the schema for me and also Auto configured the entity manager the data source and a transaction manager for us so all this happened in the background and that's why when we ran the application we were able to easily execute the queries against the database and insert a user role into the database in this step we were trying to answer the important questions where is the database created what schema is used what are the tables created how can we see the data in the database how are we getting hibernate data source and all other stuff we saw that the answer to all of this is spring boot and the in-memory database h2 we had to do no project setup no configuration at all using an in-memory database we don't really need to maintain anything I don't really need to install a database or something of this kind this makes it a great combination for learning and for writing unit tests the other important thing is with little configuration with some simple configuration in the application read properties we can actually really connect to a SQL database or an Oracle database the only problem with using an in-memory database is the fact that the data is not persistent between restarts so as soon as you terminate the application the entire schema and the data is lost in this course at the start we would start using an in-memory database because of all the flexibilities it provides in the last few steps we create an entity called user and we started managing it with user dau service let's say I want to create another entity what I would need to do in that kind of a situation is to manage it I would need to again go and create another dau service so let's say I would want to create another entity so some entity dau service and to insert here I would say some entity and let's just call this entity where you are writing a user dau service is very similar to some other entity dau service so here we are just inserting the data but consider the scenario when I am inserting I am retrieving data I'm deleting updating updating and all that kind of stuff so if I have a lot of methods here then those kind of methods are repeated again and again for all the different entities if I have 15 entities I would have 15 doubt services which would be having very similar logic so irrespective of the entity you have to interact with the entity manager to manage it so you have to either call a persist method or you would have to call something like a merge method or you would need to call a remove method or you have to call one of the variations of define methods bring data wants to solve that problem what string data says is you just define your interfaces you define your repository interfaces and I will take care of implementing them so if I want to just do a user Dao service instead of that I can create a simple repository with a small method in the interface and spring data says I will provide the implementation for you I'll be able to talk to the entity manager and do what you would want the specific implementation or the specific module for JP a spring data JP it let's now view spring data JP to create a simple repository the way we do that is very simple all that we need to say is file new interface the most important thing is we are creating just a simple interface we are not going to provide the implementation the implementation would be provided by spring data with this interface we need to implement or extend actually another interface which is present inside the spring data JPA which is JPA respository so input the JPA repository when we are extending the JPA repository we need to provide it what is the entity that you would want to manage the entity we would want to manage is a user I would want manage user and the other thing I would need to provide is the primary key the primary key of user is long this is all you would need to be able to create a repository now I would want to use this posit ori from our command line runner so what I'll do is I'll go ahead and create another command line runner I'm copying copying the user service user Dao service I would actually call this now user repository a man line learner because it uses the user repository I'll open up the user repository command line runner I want to change this I would not want to use user Dao service I would want to use user repository enough input user repository in shove Jack I would want let's say insert Jill from here I'll use the user repository dot save and say user one important thing about the user repository is the fact that whether you want to update or insert you would use the same method which is save this would actually return a user back I would not need to worry about it I'll say user repository dot save user let's now run the application and see what happens I'll stop this and start the application you would see that the insert queries are fired twice because we have two runners we have one runner which is making use of the Dao service the other runner which is making use of the user repository and you would see that new user is created would be printed twice you can see that Jill is also now created what we did in this step is actually we used a simple user repository instead of a user Dao service the user repository kind of acts as a shortcut to manage your entities instead of writing a lot of Dao services with very similar logic so you would have the same insert his logic merge logic find and all that kind of stuff instead of using that kind of logic spring data JPA provides a common abstraction called JPA repository if you extend the JPA repository and provide the entity you'd want to manage you'd get all the different methods that are provided a varied range of methods that are provided for doing all kind of operations with your entities in this step we look at one of the operations that was present what we did from the user repository command line Runner is we made use of this save method what we'll do in the next step is make use of more methods that are defined in spring data JPA until next step spring data JPA makes it easy to manage your entities once you have defined your entities and define the mapping to the database that's it spring data repository would provide a lot of useful methods to manage them in the previous step we made use of this save method let's start with using a few more methods one of the important methods which is present in the user repository user repository dot find if I want to find by ID I can use the method find by ID and you can see that defined by ID uses a long so I'll say I'd want to find the user who has an ID one and assign it to a local variable this actually returns an optional so I'll say user with ID one and I would say user is not created but if this is actually retrieved so I have got the user who has the ID one retrieved from the database the other options user repository provides is to query all users so let's say dot find all and I'll assign this to a list and let's call it users and let's also log all users plus we are using a couple of methods from the user repository actually user depository has a lot of other methods so you'd see that user repository has a count method or delete method you can actually delete in branch and you can check whether something exists or not you can do wide variety of searches using find and also you have methods to save so save method is used to insert and also to update and entity they're wide variety of methods that are there in the user repository I would recommend you to try and see what are the methods that are there and try to play around with them for enough let's restrict ourselves for these two things and let's start running the application I'll stop this and start it again the application will take it take awhile to launch up because we have put it in debug mode so now it's completed execution if you look at the log you'd see a few things that are printed so one of the things which is printed is user is retrieved so we are able to retrieve the user with ID 1 the name is Jack and we see their oldest admin and also we see all users printed in the log so all users user with ID 1 and ID 2 so we are able to retrieve all the users back we saw how user repository is very useful in simplifying interactions with the entities in managing entities so now with spring data JPA all that we need to do is define the entity so once you have defined entities spring data JPA makes it really really easy to manage those entities until next step by in 28 minutes is providing awesome learning experiences to 300-thousand learners across platforms like udemy Safari online and pact we have clocked million hours of learning in the last few months the question is what do you want to learn next we are building solutions to help programmers at all levels you can learn programming with our awesome courses on Java Python and JavaScript you can learn full stack development with REST API and micro services with a wide range of frameworks like Springwood no J's react angular and spring cloud we have 200 plus videos to help you start your journey from a programmer to a Software Architect we have videos to help you learn frameworks industry trends including things like micro-services learn the best practices in architecture design and code quality thanks for watching keep learning in 28 minutes you
Info
Channel: in28minutes Cloud, DevOps and Microservices
Views: 133,713
Rating: undefined out of 5
Keywords: JPA Tutorial for beginners, hibernate tutorial, in28minutes, java hibernate, in28minutes tutorial, hibernate (software), java interview questions and answers, in28Minutes Course, hibernate framework, design patterns, Hibernate Tutorial for beginners, java interview questions and answers for experienced, spring interview questions and answers for experienced, JPA, in28Minutes, maven tutorial, Hibernate, spring data jpa
Id: MaI0_XdpdP8
Channel Id: undefined
Length: 57min 15sec (3435 seconds)
Published: Mon Aug 06 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.