Spring Boot | Spring Data JPA Many To Many Bidirectional Relationship Example | JavaTechie

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone welcome to java techy in this tutorial we'll understand how to map a many to many bi-directional relationship using spring data gpa and mysql okay all right this many-to-many relationships are one of the most commonly used association mapping in real time because in real time while working with entity we always need to maintain their mappings to not lose any information okay so to make it more simple let me walk you through one happy scenario which is the perfect example to demonstrate many to many association mapping so if you can see these two entity we have something called students and we have course so if you think from the real time perspective a student can purchase many course okay similarly if you think in the reverse direction a single course can be purchased by multiple students so if you observe carefully from student to course it is one to many one student can purchase multiple course similarly a single course can be purchased by multiple students so here if i use one too many in both the sides then it's difficult for me to maintain the primary and foreign key mapping so to overcome this kind of conflict rather than use one-to-many in both the place we can directly use many-to-many association mapping where if you are using many-to-many association mapping behind the scene it will create an additional database table to hold the primary key of both the relationship table like student and course which makes schema mapping quite easy and understandable i will show you this once we start the implementation okay so without any further delay let's create a new project from scratch and understand this many-to-many mapping so let's get started [Music] let me go to my intellij idea then create a new project click on file new click on project then click on next i'll give the group id com.javatekey then i'll give the project name jpa may mini too many okay i'll give the same as my project name then i'll change the jdk version to it and i will also give the package name com.javateki that's it click next you can give any valid name here i am just giving jpa many to many okay now click on next let's add all the required dependency i will add lumbo then i will add web dependency then since i want to interact with database to use this many too many i'll use the spring that has api dependency also i will use the mysql connector okay lombok web jp and mysql that's enough i guess let me click on next finish the project so project imported successfully now next what i need to do i will just create couple of packets okay let me minimize this i will quickly create couple of package i will just create a package called entity then i will just create a package called repository you can give any name okay you can give dao as well i am just giving repo now next i don't want to create the service but i will directly inject the repo but it's good practice to create a service layer since i am just demonstrating about the association mapping i will focus on the mapping part okay so i am not going to create service so i'll just create another package called controller that's fine now if you observe the flow diagram we need to create two entity right student and course so let me create these two entity inside entity package create a java class call student then i'll create another class called course okay fine let me zoom this now from the student i need to write association mapping so that student can map to multiple course similarly from course i need to write the mapping a single course can map to multiple student so to make this entity first i need to annotate at the right entity annotation then i need to annotate table you can give the table name let me give the name as student tbl now you can define couple of field okay so i can define the field like id name age and department of student okay now i just need this id to be auto generated so i will just use id and i just want it to be generate value this will auto generate my id now the next from the student i need to map list of course or set of course right so what i'll do i will just define private set of course courses okay since i used lumbo i don't need to write the getter setter manually i can use the annotation setter you can use getter then i just want all argument constructor and just one no argument constructor instead of writing or that setter and greater i can directly use other data but there is some issue if i will write other data in case of multiple mapping json or jackson is unable to bind those information okay there is keep looping the stack overflow error i faced so it's good practice to keep getter and setter if you are working with entity mapping now this course i need to tell to the gpa this is the student i want to inject multiple cores so as for the flow diagram you just create another table and map the primary key of student and course so that is what i need to define using annotation so just use the annotation at the rate many to many okay then i will specify the fetch fetch type i can specify legi then you can also need to define the cascade gasket type all you can make it persist but let us keep it all okay now the main important thing here you need to define the join table you need to tell to the jpa to create one additional table with the information i am giving in this annotation so you need to define the annotation called join table okay instead of many too many in other association mapping you can directly use join columns but in case of many too many you want hibernate or jpa to create a new additional table for you so you need to define the table information so i will tell hibernate or jpa create a table with name student course okay now next what you need to do you also need to define the join column information so i tell to the gpa this is what the table create at runtime and just use below mappings okay when i say below mappings you can say join columns and then you can define the join columns what need to be keep inside this particular table so in this join columns what i need to do i will use annotation called join column this is a single column i am defining the name of the column is student id okay and then reference the column name is the id of my student see if you observe the student entity when this table will create by jpa i am telling him to keep this particular id of the student with a column name student.id so that is what we just specify here right student.id should be the column name and it will point to the or it will refer to the id of my student fine similar way i also need to tell about the course details right so what i will do here i will define another join column for course so i will just add enter inverse join columns then i will define annotation at the red join column then i will tell to the gpa use the column name which is course id and refer to the column name id okay this id is the primary key of course table the way this id is primary key of student table similarly we need to create another primary key in core schedule so what this table will contains it will keep the information about your primary key of student primary key of course okay that's it all about many to many association mapping that we did from the one in from the student side right similarly we need to do in the course entity as well so anything else that's fine because we don't need to add anything we added get resetter yeah that's fine now let's go to the course entity and since okay let me copy directly from here these are the annotation we need to define in course i'll just change the table name to course table okay now here also i need to add couple of field first i will define id right right here then i can define ink but let me keep as a long id then i need to annotate add rate id then other rate generated value then next i'll add couple of field title abbreviation modules and fees of the course now the next the way we define a student can use set of course similarly from the course i need to define a course can be purchased by multiple student or set of student right so here also i need to define private set of student students ok let me input this now here also you need to define the annotation now here also i will define many to many but i will not define the joint tables information in this particular course because student is my parent or the owner table is student with the help of student i am going to map the multiple course okay so you no need to define all the information in the second entity which is the child entity or you can consider not the owner okay so to tell to the gpa that the owner is students what i'll use there is there is attribute called mapped by and i need to tell to the spring or jpa that this is not the owner entity the owner entity something different which is student that is what we defined here okay then i will also specify the fetch not here fetch you can define fetch type legend okay hope this mapped by is clear for you if not let me repeat it mapped by attribute indicate the entity that owns the bi-directional relationship in a bi-directional relationship we use many too many annotation defined in both the entity right but only one entity can own the relationship and you have picked that student okay that is why from the course entity i define mapped by so we are good with the entity and then next what we need to do we need to create a repository i mean since we have two entity we need to create two different repo so i will just create a java class it should be interface i'll give the name as student repository okay then i'll create another one called course repo java class i'll just change the class name to course repo now this should also interface now the next step what you need to do we need to extend this from jpa repository because we are using spring data jpa and define the data type of your primary key which is long and then the next attribute should be your entity which is course okay similarly go to the student repo let me zoom this extends it from jpa repo define okay i reverse it right this should be course like the second argument should be data type and this should be long similarly for student this should be student the first attribute in the type january should be always your entity and the second attribute you can see here right t extends object id extends object so second attribute should be data type of your primary key so we are good we created entity we created its corresponding repository now the next step to make the connection from my java application to the mysql i need to define the data source properties inside this application.properties file right so i have those key and value handy with me let me add it let's paste it command be fine now if you observe i just define the driver class name url username and password and this is ddl auto i keep as update so that ivernet will create the table for me if it is already exist it will update okay and then we just define the dialect and we define the server port which is 919. that is fine now what we can do let's add few method in our repo ok so in student repository i just want to write one method to find a student if that input contains the specific field so i will write something like this there is a if you know spring data gpa there is a method find by then give the name and then defining containings next just give the input which is nothing string name and it will return me the list of student object right list of fine so this is pretty simple guys if you know spring data gpa find by should be the prefix and the next field name is the part of my entity if you will go and check in student i have the field called name if that field is not exist then this particular method won't work so always find by is the free fix and the field based on what you want to do the operation i am just this kind of contains check okay if the input i will give if that is exist then it will give me the list of student object that's it fine similarly we'll write some method in course repo so here i will write some method who will return me the list of course based on the amount what i will give if that is less than the price okay so i'll write something like find by fee then less than that is the aggregate method or aggregate attribute defined in spring data gpu less than give the fees double fee okay it will also return me the list of course so i will just write list of course so we are good we have all the data source configuration we created entity we created repository now the next step we need to access the or we need to save the student along with the course so for that i could use the command line runner and i can hard code the object but rather than doing that i will create a endpoint who will do that okay i'll create a java class let's say what i will give the name any name student course controller okay let me zoom this now since this is my controller i need to annotate at the retraced controller then i need to define one root url request mapping so i'll just give something like students you can give any since we are dealing with the two entity i am just giving students but you can define the course schedule or better let me do student course okay this is the root url now the first thing i need to inject both the repository here again i'm repeat this is not a good practice to inject directly your repository to the controller you should have write one separate layer which is service layer since this is a demo video i avoiding writing the service layer okay that is the reason i am injecting the repo directly in the controller so i'll just use private student repository student repo similarly i'll just inject private course repo now i can directly inject using auto add but i would like to use the constructor injection here okay i will just define both this is fine okay now let me enter it now let's define our endpoint so i will write one endpoint we'll take the student object from the postman along with course and will save in the student repo so i will write something like this public after save it it will return me the student object save student with course okay now here i need to give the input as a student because student contains set of course so while building the student object you need to pass the set of course from the postman i need to define other request body then i need to define this as a post mapping ok if you want you can give any url but it is fine i do not want to give any url since i define the root url so now we injected the student repo i can directly student report dot save the student object and i will directly return that okay now next i will write a method who will return me the list of student once i will fetch list of student it should display me the list of course purchased by that particular student okay simple guys if i will face the student object i can get the set of course as well right because the cascade type and faith i said to the lady ok so i will just write the method public will return me the list of students find all students something like that then i'll simply return student repo dot find all i need to define this as a get mapping i will write another endpoint will return me the student particular student object based on the student id what i will give public will return me the student object find student i will give id as input okay now i can directly use written student repo dot find by id it will take student id which is long actually i should not give as a string okay i just need to define post mapping sorry this need to be gate mapping because i am i'm going to fetch the info right and i need to define this as a path variable so that as part of url i can pass the student id now if you observe this will return as the optional so i will just use get or i can directly use get the object if not just return with the null fine now let's call these two method this is what we define from the student repo and course repo so i'll just use these two method one will give me the student list of student by name okay public will determine the list of student find students containing by name give the input string name i can define the path variable again then i can define gate mapping then next what i need to do i need to call that method right return student repo dot find by name containing give the input as a name so this is simple what i'll do i'll just modify the url it's not required but let's keep it simple fine then give the name as a input now the next method to fetch list of course based on the price i will give public will again return me the list of course find course less than price the price which i'll give it should be double again i can use the request param but let us use the path variable okay because without this information i cannot perform that particular operation so i'll just use get mapping course search then give the price fine then i just need to call course repo dot find fee less than the price we are good now we define all the endpoint one will save student along with the course one will fetch all the students along with course and one will face single student based on the student id and then find student containing by name and then course less than the price but i will give the input so we are good now let me start the application go to the main class this is the main method i will directly run this so there is some exception mapped by reference as unknown target entity just give me a second let me check it so map by reference as unknown target entity property entity student dot course okay if you go on student and check okay this is what the mistake we did the attribute name courses not course so go to the course and change the map by to this particular name okay fine let me start it again so if you observe it created the table student table and then you can observe your right it create a table called student underscore course underscore table this is what the additional table we created and that's the reason we annotated many to many with join tables and student course table all the course table okay all the four four table i guess right two for entity one for hive net sequence one for the mapping table now let's verify that let's go to the database let's open this then i'll just refresh this you can see here table name course table student table and student underscore course underscore table this is what the mapping table and we have the hyphenate sequence now let's go to the postman and we'll try to hit the end point this one to add a student along with course okay so the first end point is slash students last course let me go to the postman then i'll create a new request type post because you want to add the student object right http localhost 9191 then the url let me check the url slash student slash course slash student slash course then i just need to give the payload right so i'll just use json i have the payload i created this so if you observe just give me a second what is the error let me paste it again fine so the name of the student is this is 33 department is ui and he use or he purchased these are the cores course one is angular and two is the react now let me send the request you can see here the id is auto generated and the core side is 2 3 this should not be happen actually i just used at the right generated value that is the reason it is getting changed actually so we should use identity generator rather than other generated value but that is fine the student id begin with one so that is the reason in the sequence table the id one is already exist so for the course the id got start from the two it should start from the one you can give a try guys this is not something complex rather than use this generated value you can use generator type or something you need to define identity or something like that or i guess you can directly use the strategy and you can define your generator um something like generation type or generator type dot something you can see here generation type auto identity sequence so it's good to use the identity okay if you use then the sequence will be generated or decided by hibernate rather than if you observe here we have something called hibernate sequence table so in our case already id 1 is created and stored in the hypernet sequence so when we are adding the course it is taking from the next sequence which is 2 that is fine that you can look into the generator type now let me add one more object just replace with the new payload so the name is bassan is 30 and department is dev he is purchasing these are course machine learning spring boot database system now let me send the request you can see here id started from four for the student the id should be start from two this is because of our then default generator we added that is fine now let's verify in the database now what i'll do i will just create a sql editor new i'll directly check in the student table select start from student table okay i will run this you can see here there are two student id one and four okay now let me check the course table there should be five course okay select start from course table you can see here there are five cores two two and three ng and react js added by santos and five six seven added by basant okay that you can view in the student course table now select start from student course table okay so make sure to remember the id so that i can tell you the id is one santos four is person so under this particular id one santos you can see two course id map to this particular table similarly for course id student id 4 which is basan for him there should be three course id mapped to this table okay i'll show you directly you can see here student id 1 which samtos purchase these are the two cores and those course id is 2 3 but for user person he purchased the 3 course 5 6 7 and if you observe the course id of 567 you can understand 567 which is a spring boot database system and machine learning that is what we pass as part of payload right machine learning spring boot database system for person and his id is four fine we are good with the post mapping and we are able to see that jpa is generating the additional table and keeping the all primary key mapping information this is what right now let's fetch the all the student so what i'll do the url let me check go to the entity or go to the controller find all there is no url so i will directly change it to the get i'll remove the payload i'll send the request there is some error if i will open the console stack overflow yeah this is what i was talking about so if you remember in beginning i used a getter and setter rather than use data since core student having list of course and again core serving list of student that is bit conflicting for jackson data binding to what i can say to map that to the object okay so there are two annotation let me use that just go to the entity then i will directly use here there is annotation jackson okay there is something called jackson managed reference or something like that or something json managed reference and then go to the other one course json back reference okay this is what using the json we are telling to the or we are just defining the jackson bind use these two annotation to bind the json to the object let me restart it it will take few seconds so it started now go to the postman hit the endpoint we are seeing the response error now okay there are two objects we added student object student id one santos obtained for these two course id4 student person these are the cores okay now let me fetch a student by its id so that is what that if another endpoint we define student id right let's say student id i will search for for me the id is 4. i'll fetch it for 4. you can see here if i will face for 1 i'll get the response for santos now what next we have find by name containing ok so i will do something like this i will directly go to the postman and i will do fine i will give b a okay now send the request you can see here the name starts with or containing this character i am getting that response if i will add something s i can see santos even boston is there because s contents in this particular name similarly let's try the another endpoint to find out the course based on the price or based on the price comparison so the url is search and price right so i'll just change it to search and price is let's say i am giving 2 000 all the cores which is less than 2 000 give me as a response there are only two cores react.js and database system you can get in the 2000 now let me increase it to the 3000 there are one more course you can obtain using the 3000 means this is just aggregate function to use the less than in spring data gpa but our intention to understand the many to many association mapping how we can do in the spring data gpa and how gpa will generate the additional table which is this particular table course student course table will map the primary cube both both other relationship okay so this is what all about spring data gpa we can use and as per my experience i believe maximum scenario is being developed by many too many in real time so just focus on this annotation and try to play with this particular annotation create one more scenario instead of course and student you can take something like customer and list of product such kind of scenario and you can give a try okay that's all about this particular video guys thanks for watching this video meet you soon with a new concept
Info
Channel: Java Techie
Views: 20,257
Rating: undefined out of 5
Keywords: many-to-many relationship jpa spring boot, spring boot crud example using many to many mapping, many-to-many without join table, how to fetch data in many-to-many relationship in jpa, many-to-many relationship hibernate, jpa many-to-many bidirectional example, many-to-many spring boot rest api, Spring data jpa many to many example, javatechie, spring boot, spring data jpa, many to many
Id: jCYonZey5dY
Channel Id: undefined
Length: 37min 50sec (2270 seconds)
Published: Mon Aug 15 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.