Spring Boot Tutorial - Build a Rest Api with MongoDB

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's going on guys assalamualaikum welcome to amigos code in this course i'm going to teach you about spring boot and mongodb if you've missed my course on mongodb where i teach you the essentials of mongodb queries documents collections so on and so forth setting up with docker go ahead and check the course you can find the link somewhere here or here and to get up to speed with but in this course is more about building a rock solid back end using spring boot and for the database right towards the end of this course you're going to learn how to build a fully fledged restful api using spring boot and so we're going to consume data from our mongodb and then return a json payload to our client and you'll see how easy it is for you to build get requests post requests put requests delete requests where the mongodb is your database if you're new to my channel go ahead and subscribe give me a thumbs up so i can keep on recording these courses comment down below and let me know what you want to see next also if you're not part of the amigos code community go ahead and join over 20 000 people combined and the community is awesome and i would love to have you there without further ado let's kick off this course sponsor time honor thanks jetbrains academy for sponsoring this course jetbrains academy provides a project-based approach learning where you learn how to code by creating fully functional applications with project based learning you can study programming theory and apply your knowledge by creating real working applications one step at a time whether you want to become a java software engineer python whether you want to learn about back-end front-end and even more there is a track for you there are over 110 projects to pick from that will strengthen your gear profile what i really like about the jetbrains academy is that they provide the knowledge map and this is where you get an overall picture of everything that you need to learn so you don't get overwhelmed and start googling around you know what you need to learn for example to become a java engineer so the knowledge map gives you the precise map for everything that you need to learn another thing that i love is you guys know that intellij is my favorite ide so what you can do with jetbrains academy is that you can code your exercises with intellij and this is really good because you can complete the projects using your ide so it feels like you're building and completing a project for real which is really nice and one thing that i want to mention is the study plan so the study plan is divided into stages so you'll start from the basics and then it ranks up right the complexity ranks up so that you don't become overwhelmed and enjoy coding so to get started jetbrains academy is offering you three months for free yes three months and the way to get three months for free is as follows first you need to sign up with my link which i'm going to leave in the description of this video second you need to complete the first stage of your project and third you need to complete your first project to get three months for free so link will be in the description of this video and i'm really excited about jetbrains academy because to be honest they have awesome products and i feel like this academy is the right academy for people like you learning how to code and wanting to become a professional software engineer for this course for this course what i'm going to do is to practice as i teach so that's the best way of you learning any new framework technology that you come across also if you're not part of the amigo squad community go ahead and join because if you have any questions you can post them on a group and someone will help you including myself and if you want to gain a certificate go ahead and enroll on my website if you're not taking this course from my website so you can get a certificate and show that to employers also if you missed the first part of this course which is the essentials of mongodb i'm going to leave a link where you can find the course and get up to speed without further ado let's kick off this course let's go ahead and bootstrap the springboo application with spring initializer so navigate to start.spring.io and here we can bootstrap the application so we can pick whether it's a maven project gradle the language the version for springboot some metadata so on and so forth so in here i'm going to leave everything as default so maven java and then pick whatever version in here so i'm just going to leave the default because this should work with whatever version is selected now for the project metadata you can customize this and then the packaging we're going to leave as jar and then the java version here it doesn't really matter so i'm going to change this in a second because i've got 15 installed so then what i'm going to do is so i'm going to select dependencies and in here what we need is we're going to pick lombok so here i'm going to press command and then click so you can see press command for multiple ads so i'm going to need lombok so this is for annotations and removing boilerplate code and if you want to learn about lombok go ahead and check my youtube channel where i've got video on lombok then what we need is so here spring web so this allows us to build web including restful applications using spring mvc also i've got a complete course on spring mvc and building apis with spring web so here let's just press command and then click on it and finally what we need is so here we can even search for it so let's search for so here spring data so store data in flexible json-like documents meaning fields can vary from document to document and data structure can be changed over time so this is what we need so here you can see we can also have an embedded database but we don't need this because we're going to use docker and you'll see this in a second how everything will be connected and storing documents so this is mainly for testing purposes so here i'm just going to select this and if i come out of this so escape there you go so we have lombok spring web and spring data mongodb so here i can click on explore and you can see that this is what it gives us and i want to leave this link where you can basically just grab the exact same configuration that i have and follow along so if i click on share you can get this link where you can access this exact same configuration so now what i'm going to do is generate and then i'm going to save this and there we go that was quick now if i navigate to desktop you can see that i do have this demo zip so i'm going to extract it just like that and i have this folder called demo and i'm going to delete this zip file in here and there we go next let's go ahead and open up this demo folder with intellij so now let's go ahead and open up this project with intellij which is my favorite ide so in here i've got toolbox installed and you can see that i do have intellij ultimate for apple silicon in here right so you can basically use either intellij ultimate or the community edition but i'm going to show you why the ultimate is by far the best ide because it has lots of integration and also we can connect from our database using the ultimate so it has database support for this course i actually have a coupon code for intellij ultimate which will last you for three months for free so go ahead and basically install ultimate edition and grab the coupon code which will last you for three months so you can follow along and everything works beautifully so here i'm just going to open up intellij ultimate so i've got the m1 chip for my mac so here i'm going to open up this version in here but if you don't have the m1 chip you can just open the ultimate so this will be for both regular windows and mac users on intel so here i'm going to open up intellij there we go and so that you know we could actually um basically bootstrap the springboard application through intellij here if i go to new project you can see i do have this window and have a look so spring initializer in here so we can actually customize it right so the same settings that we had before we can do it through here but we already done it through the website so let me just cancel out of this and then i'm going to click on open and then inside of my desktop i've got a bunch of files so here demo which is this folder in here and then open and then i want to trust this project just give it a second and let me just put this full screen and it's resolving the dependencies and that's it that's done so that was really quick now what i'm going to do is so let me just open up the demo folder in here and then go to source main java demo application so let me actually increase the font so you can see everything crystal clear so i'm going to press command and then comma and you can actually go to basically in here preferences and you can see command comma so here for the font let me just put something bigger so you can see exactly so let's try 36 apply okay i think this is good and also let's go to let me just type font in here and an appearance and here let's try let's say 34 maybe there we go that's bigger and i think it's good for you so now you can see everything properly now what i'm going to do is so this is the file structure for a springboard application and basically under demo you have a source so this is where all of your code resides and then you have main so main this is the actual code and then test this is all the code that tests your application so inside of main we have java and then we also have the folder for resources so this is for example all the configuration files which we're going to touch in a second so here inside of java you have the ma the default package so in my case is com example.demo uh but basically this should be for example your own company for example right but in here we have the demo application class and this is what you see here now remember i said that i do have java 15 installed so let me open up the palm.xml and this is where all of the configuration is so this is maven so here you can see properties java and then 16. so i'm going to change this to java 15 and if i scroll down and here you can see that the dependencies that we've picked so this one was for so spring boot starter data and then we have spring boot style of web in here and then we have lombok and by default we get this one which is for testing so spring will start a test and then we have some plugins in here so now let me just close the palm.xml and let me try and run this application so basically you can right click run or you can run from here from here or from here so let me just run it so this is the main class run them application and if you get this error so by default the java language level is set to 5 which is not supported so basically what we need to do is let's go back to the settings so i'm going to press command and then comma in here or you can go to intellij and then preferences and here let me just put the font a little bit smaller so let's just say 30 and then apply and then in here go to build and then compiler java compiler and i actually need to make this smaller so let's just say 26 apply and then java compiler and still small but you can see here for example here right so target byte code version this is 16 but i'm using 15 right so let's change this from 15 or actually from 16 to 15 apply let me increase my font size there to 34 as it was before apply okay now let me close this form the xml and then if i run this again this should work and there we go so you see that it worked but the application in here failed to start so here have a look exception opening socket and in here mongodb driver core and you can see that the connection was refused so basically it's trying to connect to the mongol database but the connection was refused next let's go ahead and get the mongodb up and running and then run the application again and it should connect successfully so this is all for now catch me on the next one for this course we're going to use docker to spin up a container that will run our database if you want to learn more about docker i've got a course on my website where you can learn everything about docker basically docker makes it easy for you to test and deploy applications by simply packaging up into images and then run containers of images now in here on this website so docker.com i'm gonna click on get started and here go ahead and download docker desktop for your operating system so in here if i show you i do have docker installed and you can see that docker is running so the installation process it's really really simple so once you have docker installed next what i'm going to do is under the description of this video you'll find the content so the so this content right here so this is a yaml file and basically what this will gives us is the mongodb so here the database and then express so express is just a graphical user interface client that allows us to interact with the database and then we have some volumes here so this is for storing the data and then the network so that these two containers so express container and mongodb container can talk to each other so go ahead and basically grab the contents of it so i'm going to press command c now i'm going to go back to intellij and in here under the root of this project i'm going to create a new file there we go and i'm going to call it docker dash and then compose dot and then yammo just like that and then i'm going to paste the contents there and we are good to go so now you can see that i do have in here so check this out i do have um intellij kicked in and he knows that this is a docker compose and now i can just run it from here so here what i'm going to do is i'm just going to run this and you can see that it's actually doing a few things it's creating mongodb and then express and you can see right here so you can see it's done and to be honest there we go and you can see here the command that he actually did use right so a used docker compose so if you want you can open the terminal and you can say docker compose dash f and then you pass the file and then up and then dash and then d for detached and to be honest this is it so obviously i can go and basically i can stop things but i'm going to keep things running so let me actually show you so here so if i open up the terminal and in here if i do ls you see that or you can say dir if you want windows so if you want to run from the terminal you just say docker compose and then dash f docker compose yamo d4 detached and there we go right it's the same thing so i've done it through the ui so here i'm going to hide this and then go back to my web browser and in here i'm going to basically navigate to localhost 8081 and check this out so we have express this is really cool so this is this container right here and you can see that it's listening on 8081 right here and it's connecting to our database using the admin username and password which is defined in here so root user root pass which means that we have a database pin running next let's go ahead and create the actual database that the application will connect to now let's go ahead and connect from our springboo application to our database so let's go ahead and open up src and then inside we have main and then resources and then inside we have application.properties so here we need to define the following properties so we're going to say spring dot and then data dot and then and then here we're going to say authentication database this is equal to admin and i'm going to show you this in a second why it's admin and then here we need the same so i'm going to press command d there and then here is going to be username so username there we go and this will be root and then user let's also define the password so password and then this was root and then pass and let's define the database so database this will be amigos code and we need to define the port so spring and then and then port just like that and then the default port is 27017 and finally db and then host oops db and then host just like that and this is local host now we have root user in root pass so this comes from here so from our docker compose we specify these two environment variables right here so user or actually root user and root pass and then if i go back in here the authentication database is admin so here if i go back to express you can see that we have this database here and if i click on view so basically this is the database called admin basically now if i click on view and then you can see that we have users inside of users we have a root user in here and you can see the db admin so this is why we're doing that then the database is called amigos code so let's just go back in here for a second and i'm going to create a new database so amigos and then code create and there we go so we have a database called amigos code and the port is the default right here and then we're connecting to localhost because it's running on localhost and to be honest this is it now the reason why i'm using express is because some of you might not have the intellij ultimate but if you have the ultimate you can connect to the database through here so database and then new and then data source select and then in here localhost 27017 the default we can specify the user so this is root and then user the password is root and then pass and here test connection and there we go so apply okay and now we have a console now if i say show and then dbs run it you see that we have for database admin amigos code the one we just created config and local so there you have it so let me just click here so introspect and now remember before we started the application and it wasn't working right because it couldn't connect to the database so let's just open demo application so this is where we have the main class the main method run and there it goes you can see that so in the logs in here so all of this is stuff so cluster created with settings and then open connection and there we go so tomcat started on 480 and we are good to go if you have any questions drop me a message otherwise let's move on now let's learn about collections and documents so stores documents i.e rows in collections so basically if you've done any relational database then this should be familiar so documents they are the same as rows and collections are what it's known as tables in the relational database world so we have in here a bunch of documents these are similar to json objects and basically these are the documents and then the collection is what holds all of these documents stores data records as base on documents and these are like a binary representation of json documents so in this example here we have a person document right so it's just a json object with some properties and values so name age status and then groups so you could have strings you can have numbers enums arrays so and so forth so in terms of data types you can have all of these data types so doubles strings objects arrays binary data object id so this is how you uniquely identify a document boolean for true or false dates no values using the null keyword regular expressions javascript you could have 32-bit integer and then 64-bit integer using long decimal and then min and max keys next let me go ahead and show you how to create class and represent that as a collection and then insert documents now that you know about collections and documents let's go ahead and take this document right here and then create a collection called student and then basically store this document right here and basically this represents a student so first name last name email gender here we have address this is a nested object created at so we're going to have some date in here and then favorite subjects list and then total spending books and you can see this is a double or um it could be a big decimal so you can see that we have various different data types so let's define this in java code so let's open up intellij and in here i'm going to collapse this and for now let me just stop the application there we go and then i'm going to collapse resources so we managed to connect to the database open up java and then inside in here i'm going to create a new class and this will be student just like that and we said that we wanted to have a couple fields in here but what i'm going to do is i want to have a bigger font so command and then comma and here let me just say font and then font and here let's just say something like 44 so okay and this is much bigger and better for you so now let's go ahead and define the first name so private and then this will be string first name we also need last name email and then for the gender let me create a new class in here and then this will be an enum and i want to call it gender and this for now we'll just have male and then female just like that and if i go back so this now will be private and then gender gender we also need to define address so let's create a new class in here and this will be address and for now let's just keep it simple so private and then string country we also need postcode and finally uh let's also say city and then swap this around just like that and if i go back to student so here we're going to have private and then address and then address then we're going to have the favorite subjects so private list of string and the subjects would actually be an enum but it's fine so favorite and then subjects we also need private big decimal total spent in books and finally private and then this will be zone date time and then create it at so this is when this student was um created in the system now i'm going to annotate this class using long box i'm going to say at and then data so this will give us getters setters constructors and all of that good stuff and i've got a video on lombok if you want to learn about lombok so instead of us defining for example the constructor like this oh actually uh yeah so the constructor with all of these fields and then the getters so then you have all the getters and setters so you can see that all of this is boilerplate code and also equals hashcode tostring basically this does it all so let me just revert everything and we're good to go so also if i go back to address in here let's do the same for address so data and there we go now that we have all of the models for our application next let's go ahead and basically annotate the student class with the correct annotations and also have the id which resembles the primary key in order for us to tell that this class will be a collection and then we can also store documents inside of that collection we have to annotate with add and then document so this comes from springframework.data.mongodb.cor enter and there we go so it's as simple as this now if i press if i press parentheses here and command p or actually you can see what it takes so basically you can pass the value the collection language so on and so forth but i'm going to leave the defaults in here just like that then i also need to have an id so we cannot have a document without an id right because it should be unique the same way with sql and relational databases each row has to have an unique identifier the same with documents so private and here this will be a string and then id and what we need to do is annotate this with add and then id and there we go so now that we have uh everything that we need let's go ahead and basically try and run this application and see what happens so here let's go ahead and basically run so we're going to run the application and there we go no errors now let's go back to express and let's view the amigos code database and fair enough we don't have a collection called student and this is because we haven't inserted any documents so in order for us to do that we need to use a repository and that's we're going to do next if you've taken my spring data jpa masterclass course then you probably will be familiar with this step basically this course is the most comprehensive course on spring data jpa and it teaches you everything about spring daily jpa repositories relationships uh one-to-one one-to-many transactions life cycles how to map classes to tables so on and so forth so if you know about spring data jpa then this step will be very familiar to you and if you want to further learn about how to basically build all of this using spring data jpa then i highly recommend you to enroll to this course where lots of students have benefited including camilla from brazil which recently managed to secure a job just because of this course so if i open up intellij and remember i said that we didn't see any collections because we didn't insert any document so let's go ahead and do that so here let me just collapse this and in here let's create a new class and this will be an interface and we're going to call it student and then repo z3 just like that and here if i put this full screen we're going to say extends and then and then repository now here so this is using generics i'm going to say that first type is a student and then the second type is the data type for the student id which is string and there we go so let me just put this on a new line just like that so you see everything now this interface now extends repository so if i open up repository you'll see that it has all of these methods which are given to you so find all find all with a sort insert also save all and basically this actually in here extends paging and sorting and if i click on paging and sorting you can see that it has the final and find but more important here if i go back you can see all the implementations right so this is repository and repository has the single repository in here and you can see all of the methods so this this is the actual implementation right so save save all find by these exists by the count so we get all of this for free so let me just close this and then close this as well and what i'm going to do for now is so let's just open the demo application where we have the main class and here i'm going to say at and then bean so we want to create bin from this and this will be a command line runner and i'm going to say runner and here we're going to take the student repository so we're going to inject student repository just like that and let's just call the repository and now this returns so this returns a lambda in here and inside we can do a bunch of things but what i want to do first is so let's create a new student so here i'm going to say student and then student equals to and then new and then student now here i could say student.set student.blah blah right so if i press command p you can see that we have no parameters for this student so what i want to do is let's go back to student and in here let's create a constructor without the id so here without the id just like that and if i put this on a new line and there we go so now um we have a constructor without the id because this id right here is auto generated for us if i go back in here so this will now complain and now in here check this out we need to pass the first name so here let's say jamila ahmed for the last name and then some random email so jay ahmed gmail.com and then the gender she is female and then the address so let's just have an address in here so address equals to and then new and then address and in here we're gonna do is so basically we can't really pass anything inside of this constructor so let's go back to address and here let's just say at and then all our constructor and in here you can see that now we have all our constructor so here we have to pass the country so let's say england for example and then here this will be london and then the postcode will be nw9 for example just like that so we have the address and we now can find the address in here just like that and next we need to pass favorite subjects so let's say list dot and then off and then here i'm just going to say computer science comma and then we need to pass the total spending books so let's say big decimal and then 10. and finally we need to pass the created at so here this will be zone daytime and then now and there we go so now we have the address we have the student now if i say repository so repository dot and then check this out so we have all these methods so count delete delete all delete by id and then insert save save all and now we can use these methods for free right so we didn't implement none of this so here let's just say insert so we're going to insert and then a student and there we go now let's go ahead and run this so let me just rerun the application stop and rerun and so you can see that demos they never go as expected so we have an error and the error is can't find codec for class zone day time so i think this was what was my mistake so let's go back to student in here and this should be so in here this should be local and then daytime so local date time in here and there we go so let's go back and this will be local date time instead of zone day time so local and then daytime and let's import that and there we go so let's try again and there we go so you can see that this time it worked so everything up and running so if i go back to express and in here express now remember before inside of the database amigos code we only had one collection and this was delete me so we can actually delete this in a second but now if i reload check this out we have student and you can see that was so easy to implement now let's delete this one here so delete me so let's just say delete underscore me and let's view the student and in here check this out so what we have is one document and you can see jamila ahmed email female the address which is a an object in here computer science and then total spending books um this is 10 so let's go back for a second here and let's just add one more here so let's just say maths for example and then reload and this will actually create a second student so there we go go back reload and there we go so now you can see that this is a list of computer science and maths so this is actually looking very good so you can see we have the date as well uh yeah so it was my mistake you can't really use zone date time with so you have to use local date and in here we can actually even click on the object itself and you can see that this right here represents the initial json object that i've showed you earlier in this course so you can see all of the fields the address is a nested object in here and we also get the created in here with an iso date and also the class in here so there you have it if you have any questions go ahead and drop me a message otherwise let's move on let's go ahead and add an index to speed up the queries when searching by email but also to guarantee uniqueness on the email field if i go back and we have two documents and in here we have this first one right here and you can see the email is the same so both on this one here and on the second one so let's actually change our collection and enforce a unique index on the email and this will also speed up the queries when searching by this field so here if i go back to intellij and in here you saw that we use the document our id but here on the email we can say at and then indexed so this comes from core just like that now inside i can basically specify a few things you can see there boolean unique and then the default is false we can specify the direction and you can see the default is ascending we can have the sparse name background so on and so forth right so even expire after seconds but what i want to do here is i want to say unique and then this will be equal to true and now let me go back to express and in here let me just delete this document so let's just have one document there we go and in order to enable the creation of indexes we need to open up the resources folder application.properties and then here i'm going to say auto and then we should have index so here so this one auto index creation there we go and then i'm going to say true so now let me open up the demo application and remember we have this command line runner and basically it inserts a student so now if i right click and then run so this time it should fail because the email so this email right here is already taken so you can see that it did fail and have a look duplicate key error and then collection so this is really cool and you can see here so that's the duplication right so this email is taken now what we can do is so basically let's change the logic in here for a second so we can say so here we can say repository dot and then here there is no method that allows me to find by email right so we can only find by id in here and we can't really find by email next let's go ahead and learn how to create custom queries let me show you two ways that you can use print data mongodb to perform queries the first way is to use the query object so here let's go ahead and say query and this comes from core and remember we said that we want to check that if the email exists right if it does exist then we don't have to insert so here let's just say query equals to new and then query now with the query what we can do we can say query dot and then check this out so here we can say add criteria comment fields so on and so forth but what i going to do is i'm going to say add criteria and then the criteria that i want is criteria and then dot and then i can say where so where the key in our case is email and then check this out from this point onwards i can actually chain so here i've got a bunch of methods so is and like in exists greater greater or equal intersex in less than less than equal not equal near not in not regex and you can see size type all and basically a bunch of methods right so what i want to do is say is so is and then the email so this email right here so let's just extract this to a variable and that's the email there and now here i'm gonna say email just like that so if you want you can also chain right so here i can say dot and right so i can say and and then i can say another key so on and so forth right we get a gist so here what i'm going to do now is i want to take the query and then use template so template allows us to basically use queries and you'll see how we're going to change this later with repositories but in here let's just inject so in here on this line i'm going to say at watch the comma and then and then template so now we injected mango template and now i can say mongol template dot and then find and you can see that we can pass the query so the query will be the query and then comma and then student dot and then class and there we go so this find method in here you can see that it returns a list so let's just extract this to a variable i'm gonna say students now here we technically should just have one so i'm gonna say if and then students dot and then size is bigger than one then we have a problem right so i'm say throw new illegal state exception found many students with email and then plus and then email so technically this shouldn't happen because we have the index but it's always good to code against it so now we have two options we can say if students dot and then is and then empty so if it's empty we just add it right so we can even say else but it doesn't really matter at this point right because we just really care whether we haven't got a student right so if we don't have a student then we insert now let's just test this logic so here i'm going to basically add a system.out so here's south and then inserting and then student and then plus and then student and here i'm going to say else and then south and then student and then plus already exists and there you go so now let's actually test this so we already know that we have jamil ahmed with this email right here so if we try to run this code it should basically print this line so let's just start the application fingers cross and check this out so here you can see that this is actually a long uh log line where you see already exists so this is working beautifully so if i now basically delete so let's just delete the student again and now let's just restart the application and you can change the log line if you want but you can see here inserting student and then basically if i go back in here go back to amigos code and then let's delete this collection here so we don't need it delete me delete view and you can see that it works beautifully so there you have it so this is how you use the template now obviously this is one way of doing things uh but you should really be using this when you're not using the repository in here so student repository so next let me go ahead and show you yet another and much more simple way that we can write custom queries we wanted to have a custom query where we wanted to check basically whether a student existed by email and we wrote this query right here and then we had to use template in here and then this gave us a list and you can see that we had a bunch of logic in here just to check whether um it's there or not right so how can we improve this so if i go back to student repository so in here we can have queries from method names we can have an optional so optional so optional and this will be student and in here check this out i can say find and auto completion is kicking in right so here i can say find and then i can say basically student by all by distinct top by and you can see that we have a bunch of methods so here i'm going to say student and then buy so i want to have one student because i'm returning an optional if you're using this second method then you have to return an array or a list right so here i'm going to say buy and then if i press ctrl space you can see that it's picking all the fields from our student class so address and if i scroll down created and then here if i keep on going email right here if i keep on going favorite subjects and first name so on and so forth so you get the idea so here i want to say email and we even have further methods right so it's really simple you can see that basically we're just expressing in plain english the actual query and then under the hood it will gives us the raw query without us having to create the queries ourselves so here you can say after before between containing equals false greater than in before containing and you can see that there is a bunch of methods so not like uh is null is true regex not containing and basically you can see that it's really powerful so really what i want to do is say find students by email and then the email is a string so email so this is what we pass right so this is the value that we're going to pass in a second and to be honest this is it so now if i go back to the demoapplication.java in here so now you can see that we had a bunch of logic in here so here um basically let me just take all of this right here and then i want to say extract to a method and then using and then template and query so let me just now comment this out so you can have for reference and i've got a mistake so template and i can even use auto completion there there we go so now instead of having all of this logic and this sort this also should be like this so there we go so now instead of using all of this logic with the query i can just say in here so i'm just going to say the repository that we already have and then because that was an interface that gave us a bunch of other methods we created yet another method and you see here our own method so find student by email let me pass the email then this returns an optional i want to say dot and then you can see that we have a bunch of other methods so if present or else and you can see uh or else or else throw stream so on and so forth so here i'm just going to say if present or else so if present i do have the student right here so there we go and then or else this is a lambda or a runnable and this is like this so now i'm going to take this system.out.line so if it's empty right here basically everything so i'm going to take everything here and this is the empty part and if it exists i just want to print so is this part right here and then paste that and this will be let's just call it student or i think we just have to call it s so here s and there we go so you can see that it's much easier and we basically cut down a lot of code and also the query so if i go back to the interface so here student repository you can see that from this point onwards we can actually have a bunch of other queries so if you want to list for example you say list and then of type student find and you can see that you can basically construct your queries so i'm not going to do this now and let me just remove that import and also if i for example type int and then press control and then space you can see all of the queries that we can have find children by id count all delete exists so on and so forth and let me just say void for example and oops and then press ctrl space and you can see basically the same thing here right and more important if i just say for example testing here uh actually i just went to say test right so in here i can actually say so i can say at and then query and then in here i can actually use mongodb queries right so these are like raw queries that you can use with mongodb and if you want to learn more about uh create update delete so all the cred operations with raw queries check my free course on mongodb where i teach you all of this so you see that you have a couple ways of doing things here so let me just delete everything here and then remove the import and if i go back now and then let's rerun the application so just like that and reload and i can even put this in one line so just like that there we go you can see that student and an effects school all the way to the right already exists see that it's exact same behavior so if i now so let's actually um in here let's delete this document so we already have jamila so let's remove her for some reason i think it deleted the database as well and i think if we basically let's just i think by default with if the database that if the database doesn't exist it should create the database so let's just see i'm quite sure that this is the case with shell so it should be using uh springview as well and there we go of course this is the exact same thing and you can see that insert student and right here if i reload we can see that we have the database and then here if i open up amigos code collections and you can see that it's working beautifully so there you have it you now know how to use the query as well as implementing your own methods right here inside of this repository so i'm going to leave some documentation where you can go and explore other ways that you can basically have your own queries but as i said i cover all of this in this course right here so spring data jpa so if you know spring data jpa which is way more popular than then all of this should be really straightforward so now that we have the necessary skills let's build an api that clients can consume now let's go ahead and build an api that will talk to our database so what we're going to do is have basically clients right here and the clients that can send requests so these are http requests and basically we'll have the api layer which is responsible for handling these requests then the request will flow through the service layer so this is mainly for business logic through the data access layer so this is responsible for talking to our database and then send the request back to the client and the client will get a response right here so depending whether you are building an angle application or a react application or you just have some clients really that want to consume your application where the backend is a mongodb so this is the perfect scenario now if you want to learn more about how to build this entire thing using springboo and basically the basics of springbook so on my website i do have this course in here so if i go to courses and in here there is d so right here getting started with springboo so this course is absolutely for free and here you basically learn this entire thing using also spring data jpa so you can see you know um the difference and also connecting to a relational database so this will teach you the core of spring boot if you're not familiar with this step and also if you want to grab this diagram right here you can find a link under the description of this video next let's go ahead and start building all of this right let's learn how to build all of this so back to intellij and in here the first thing i want to do is i'm going to start from the api layer so here i'm going to create a new class new and then class and this will be student and then controller and then here i'm going to say at and then the rest controller and then add request mapping and this will be api v1 and then students then in here i'm going to have a method so let me put this full screen i'm going to have a method that will return all the students so public this will be a list of and then student and then i'm going to say fetch or and then students now this will be really simple so in here we're going to have private and then final and here i want to say student and then service and we're going to create this in a second and what i'm going to do here is i want to say at and then all our constructor so now i'm going to say student service or actually return student service dot and then get all n and students just like that and then we need to annotate this class or this method in fact so this method here with add and then get and then mapping now let's create this class right here so student service so in here i'm going to open a project and in here i'm going to create a new class just like that and then call it student and then service there we go and this guy right here needs to have this method so get all students and there we go so right now we're going to return now but what we need really is to have the uh repository in here so what we're going to do is we're going to say private and then final and then student and then repository and there we go so put this full screen for a second and then here i'm going to say at and then all are constructor and then i want to say at and then service so that spring initializes this class as i've been now instead of returning no you guessed it right so i'm going to say student repository dot and then find all and you can see that was really easy so if i basically go back to the controller and that's done so if i show you the diagram for a second in here we actually have the api layer with one method which is this guy right here and then we have the service layer which is the student service so here student and then service which is this guy there isn't much business logic going on but it just basically uses the student repository which is this guy right here and this is responsible for talking to our database in here now let's go ahead and start the application there we go i've been running now what i'm going to do is i'm going to open up my web browser and in here i'm going to say localhost and then 8080 forward slash api forward slash v1 forward slash students enter and check this out so you can see that we are getting back the data from our mongodb so this is really awesome so you can see jamila ahmed in here so female address favorite subjects total spending books and the created ad so basically it's everything within our database so here if i just zoom out a little bit so you can see that in our database she lives here but basically now we are exposing all of that data through an api which is really really awesome so let me go ahead and quickly explain again what we've done here so in here uh what we have is so i think this is the most important thing here so student controller so in here if i put this full screen so this rest controller basically makes this class as a class to serve http requests from clients right so we can have basically methods and then annotate them with http semantics either get post pull delete so here you see that we have get mapping if you're on post mapping so you if you want to basically insert a new student you say post mapping so on and so forth delete to delete a student and put to update and then basically that's it to be honest and then all our constructor so in here so this is lombok instead of us doing this so here let me just show you quickly so if i do this constructor you see that it's the exact same thing but i'm just reducing boilerplate code so let me just delete that and the request mapping so this is localhost api v1 for slash students and this is what you saw in here if you have any questions go ahead and drop me a message otherwise catch me in the next video where i'm going to give you an exercise right i want to thank you so much for sticking around with me throughout this course so if you want to take the full course on mongodb go ahead and enroll i'm going to leave a link under the description of this video where you can basically master mongodb as uh your backend right so mongodb it's super simple to use yet powerful and scalable so in the course you'll learn pretty much how to set up your mongodb how to fine-tune database administration queries including crud operations you will also learn about indexes so how to speed up your queries and more important i'm going to show you how to use atlas which is a database as a service and we're going to deploy a mongodb database running somewhere on the cloud and more specific on aws and then we're going to write some javascript code that will connect to our database i'm going to show you pretty much everything that you need to know in order to be rock solid with mongodb and build applications fast i had pleasure teaching you and i'll see you on the next one you
Info
Channel: Amigoscode
Views: 32,263
Rating: 4.9047618 out of 5
Keywords: amigoscode, learn spring, learn spring boot, spring boot tutorial for begineers, java spring boot, java spring tutorial, spring mvc tutorial, spring mvc, spring security tutorial, netflix and spring boot, spring boot 2, how to use spring boot, what is dependecy injection, spring boot initializr, java tutorial, learn java, java, how to code, spring data mongodb, spring boot and mongodb crud example, spring boot and mongodb example, spring boot and mongo tutorial
Id: ssj0CGxv60k
Channel Id: undefined
Length: 72min 29sec (4349 seconds)
Published: Tue Jun 01 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.