Spring Boot | Spring Data JPA Many To Many Bidirectional Relationship Example | JavaTechie
HTML-код
- Опубликовано: 14 авг 2022
- In this tutorial, you'll learn how to map a many-to-many bidirectional relationship using Spring Data JPA and MySQL in a Spring Boot application. Many-to-many relationships are one of the most commonly used association mappings. They require an additional database table to hold the primary keys of both relationship tables.
Spring boot microservice Live course Just started
Hurry-up & Register today itself!
COURSE LINK : javatechie5246.ongraphy.com/
PROMO CODE : Java40
GitHub:
github.com/Java-Techie-jt/JPA...
Blogs:
/ javatechie
Facebook:
/ javatechie
guys if you like this video please do subscribe now and press the bell icon to not miss any update from Java Techie
Disclaimer/Policy:
--------------------------------
Note : All uploaded content in this channel is mine and its not copied from any community ,
you are free to use source code from above mentioned GitHub account - Наука
I've been stuck for hours not being able to create the bidirectional relationship, it was always caught from only the one end and I was going mad as to why... and it turned out it is the thing you mention at 6:28, because I was using @Data in both places. Thank you so much man, appreciate the tutorial!
Thank you so much ur comment helped me to fix my issue. 😊
@@rslakshmilifestyle glad it helped 🙏
Exactly what i needed. Great job. Thanks !
Thank you for helping me understand how to use JPA and Many-to-Many relationships clearly..
Excellent video in terms of keeping it simple throughout focussing on the core basic of many to many!! One of the best out there.Thank you.
Great tutorial! Many-to-many relationships are so common in most applications. Yet I often see people struggle with setting up the relationships in the entities - they assume there has to be ONE right way of doing it, not realizing that EACH entity can own the relationship.
Agree with you
@@Javatechie Great video! But if you add another student with same courses will duplicate courses. Can you solve this problem?
Amazing as always !
Useful video, thank you
Great Tutorial, Thank you sir♥
Thank u so much....its very helpful vedio....to understand many to many relationships.....please bring more vedios like as....also request bring the vedio on online shopping in springboot with react js...
Thank you for the video.
This tutorial is a successful in explaining explain ManyToMany Relationships in Java! ✔️You made it easy to follow! ✔️Thanks alot Java Techie 💙
I agree with you 💯.
Excellence work.thx a lot
Its really a good aproach , Thanks Techie
Great explanation 🥰🥰
thanks ! excellent
Such a quite nice content as always. Thank you, Java Techie
Hii in my project I am facing one problem, user having usercart that usercart contains products , if i add product it mapped to cart of a particular user , if add another product for same user cart it overrides the previous one how to overcome this situation .
Nice sir It works.
In many to many directional, there are challenges in add & delete please discuss on that
Good video.
when u fire find all couse student not include but we have bidrectional mapping ? so whats is the point to use @JsonBackRefrence Any Other Solution
Thank you 🙌🙌sir.Then I have one question am confuse.the annotations @JsonManagedReference and this called MapStruct/Mapper .They do the same thing or ? am confused please help.Thank you
Hi thank you for your effort please could you do a crud operation with many to many thank you
Thank you! I have question for 33:46: basically I'm confused that you used FetchType LAZY but yet findById method is still populating the list of courses eagerly. I have the same behavior, but I question why
good presentation but you should give all type of operations from both sides
Could make a video on jersy rest integration with swagger ui with spring boot sir.
Thanks for the informative video, one request - if you give quick summary at the end of the video i.e. what we did from start to end with the code, it will be very easy to remember the things.
Good suggestion Subham . going forward will do same
@@Javatechie Thank you.
Hello, this tutorial is really good, i like it so much. But i have one question, how can i include some additional field in student-course table, for example to track the head of the group of students? Is there the way i can do this only with these annotations or i have to create entity for this?
No it's not possible to achieve using annotation you need to create your own entity to maintain this
How can I add same course for 2 different students?
can u tell me about put mapping
thank you, I have a question, how can I add the course and assign the students of this course
I got issues like this: when i insert new value in the table student_course_table its not update .It is just update data on table course_tbl and student_tbl. Can u help me =(((
Hi Basant, I have one small Doubt.
In this Example fetch type is Lazy but while fetching student details, Course Details is getting Populated.
I am getting Confused.
Can you Please Clarify this. Thanks
any enterprise application will have atleast 15-20 entities and relationships between them. In such cases what is best design - defining the relationships in entity classes or other ways ?
Yes
Please do all mapping CRUD operation since I am facing issues with update and delete
Thanks for sharing the valuable knowledge, but I request you to please use mice as audio of your videos is very less.
Also it will be so great help if you explain few of the concepts. I mean, why we are doing this way like.
Hi Sumit i didn't get you. Is my voice is very loud 📢 or less in video?
I have picked up the final version from repository, and run the code as is - without any modifications. It is not working. I am getting this error when trying to add Student: Failed to evaluate Jackson deserialization for type [[simple type, class com.javatechie.entity.Student]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (`java.util.Set`) not compatible with managed type (com.javatechie.entity.Student). What could be the issue?
Its bcz of using @JsonManagedReference and @JsonBackReference.... Did u get the solution?
Hey Basanta,
Great Explanation. I have one doubt.
From student api we are able to fetch both student and course data.
Can we fetch course and enrolled student data from course api i.e. search/{price}??
Hi Sandeep yes we can do that
@@Javatechie Can you please guide, how to do?
Maybe I'm wrong, but it seems to be bad. There's no many to many relationship if CRUD is controlled by Student entity, because there's not going to occur the same course for another student. If you delete a student, then all Courses that this Student owns will be deleted from Course entity too
Can u please do update and delete operation also
What if we want to create course separately and then want to assign them to student ?
May I know where is your OneToMany tutorial?
@JSONBACKREFEENCE create problem because at a time of serialization jsonback refrence data not came in api
It shouldn't give any issue can you please share error
you are right, we cannot use @JSONBACKREFEENCE with collections, need to use @JsonIdentityInfo
@@kshitijbansal3672 thanks bro
Java techie please help me I am getting error 415 in postman while inserting the payload.....it says the message type is not supported I tried using header as content type application json yet it doesn't work
Are you trying with http post method from postman
@@Javatechie yes sir I am using http post method on postman for sending the data, I tried various things like using Json ignore , adding application/json in content type yet it gives error 415 and in console it gives deserialization error
Hello, thanks for the video, but when I do that it gives me a LAZY error, I switch to EAGER and it gives me a serialization error. Why does that happen? Thank you
I have shared GitHub source code in video description please compare with your code and fix
@@Javatechie , yes, you used spring.jpa.open-in-view (by default) and because of that, you didn't get a LazyInitializationException. This is an anti-pattern, btw
Getting stackoverlfow error how to solve this
Can u create same crud operation with Hibernate
We can do it easily. Instead of use EntityManager just use the hibernate session factory that's it .
Sir here in interface we had created findByName+(Containing) but i don't know the purpose of containing key could you please let me know...
Do you know CONTAIN OR LIKE operator in SQL?
CONTAINS is a predicate used in the WHERE clause of a Transact-SQL SELECT statement to perform SQL Server full-text search on full-text indexed columns containing character-based data types.
@@Javatechie got it sir thanks a bunch
I have downloaded your project from github and pasted your payloads but I am getting unsupported media type error in postman .
I tried writing manually also, bt same error i got.
I am using sts ide, is there any problem with that?
I think i should learn more about serialisation and deserialisation 😂😂😂.
I used @JsonIgnore and it worked.
@@pranabkumarnath3818 Heyo, where did u use JsonIgnore
🙏🙏🙏
Hi Basant sir, I have one interview question, how do we maintain @transactions between 2 micro services with 2 different dbs.
One interviewer asked me, please suggest any video in our channel
You need to use saga design patterns
Thank you very much basant sir, for your quick reply.
Please check the tutorial below 👇
1. ruclips.net/video/aOen1-pQLZg/видео.html
2. ruclips.net/video/6O5iJ7PKUhs/видео.html
There will be an issue if u use mappedby in the child entity , if u delete the student, all the cource associated to students will also be deleted .
Is it let me check
Hello sir If we want to map previously saved courses to a new student then what should we do?
Yes simply pass student with list of existing courses
@@Javatechie Hello Basant Sir.. When I am trying to create new student record with existing course details, duplicate records are inserting in course table..
Do save and update instead of direct doing save
Following the same code setup but getting this error when running: Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: Can anyone help me on this?
Bro I want to tell you something
Today's days even If we are using Spring boot and JPA they are not using that they are using database queries only they are not allowing us to use jpa features like onetomany manytomany I didn't understand these 🤔 y they are doing like these
Usually people follow a microservice pattern where you should have a single database per service that is the reason they avoid using association mapping
Will this code works if other student buys the same courses , it is throwing me 'detached entity passed to persist'
Please change the cascade value to persist
@@Javatechie it doesn't works
Sir once hit the get button i got response only student elements I'm unable to see course elements but course elements stored in course database table pls let me know.. 😊
What is the FetchType you have set , make it EAGER
@@Javatechie lazy sir
@@Javatechie sir after changed also getting same error only able to see student elements..
@@Javatechie as well posting elements while getting error like unsupported media type but i had added only json media type
Please check the code that I have shared and try to find out the difference
please make video on how to create exokicit join(custom join query )with native and jpql query with and withut projection PLEASE JAVA TECHIE
Already uploaded please check ruclips.net/video/8qhaDBCJh6I/видео.html
Already uploaded please check ruclips.net/video/8qhaDBCJh6I/видео.html
can we still enroll to your ongoing course or it would be too late?
Hi Raj you can enroll in the course now. Theory classes are only completed and you can also see the recording session of completed classes
Everything works perfectly, But there is a problem While I am trying to save only students not courses It is not able to save. Is there a work around for those scenario.
Can you change the cascade type and try once
No Luck@@Javatechie ,
Failed to evaluate Jackson deserialization for type [[simple type, class com.example.fts.erp.entity.Student]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (`java.util.Set`) not compatible with managed type (com.gradlic.fts.erp.entity.Student)
"status": 415, I am getting unsupported media type error in postman
how did you solve it, i have the same problem
thanks in advance!
Did u fix it?
How can we fetch Courses that student is enrolled in ?
You need to trigger join query
26:30 is it mandatory or neccesary that we create a new 3rd table with @ManyToMany mapping? Can we not use @ManyToMany without a 3rd table?
Also can you tell how the methods findStudentsContainingByName & findCourseLessThanPrice fetching the data with out any JPA query written in Repository classes ?
Yes it is mandatory, Many to Many relationship demands a intermediary table.
I am very much confused with mappedBy
can you please give coupon for spring data jpa course
Didn't get you @Meet
@@Javatechie discount coupon for your udemy course of spring data jpa
I don't have any udemy course buddy. I am giving live class on unacademy and yes coupon is available. Please reach me on javatechie4u@gmail.com for any queries
How is this many to many?
This is rather one to many (or many to one). For one student you are saving many courses but haven't demonstrated that for one new course added to table, many students are enrolled.
Also, you haven't demonstrated what happens when both santosh and basant have the same course in their enrollment list. (I tried it out and observed that two copies of the same course are getting stored instead of just one)
First of all this is one to many unidirectional and whatever you caught is a good point will check and update here
{
"productsdetails": [
{
"id": "1",
"pname": "Product 1",
"pquantity": "10",
"punitcost": "100"
},
{
"id": "2",
"pname": "Product 2",
"pquantity": "20",
"punitcost": "150"
}
],
"productscategory": [
{
"cid": "1",
"Pcategory": "Category A"
},
{
"cid": "2",
"Pcategory": "Category B"
}
],
"productscolour": [
{
"rid": "1",
"Pcolour": "Red"
},
{
"rid": "2",
"Pcolour": "Blue"
}
]
}
i need to post values in json can you give me code
Here One thing I tried is that ,after giving @JsonManagedReference and @JsonBackReference I am unable to save the data now it is saying Media type not supported, why so?
when I used The @JsonManagedReference and @JsonBackReference annotations the data fetching success but did not save data. but without those annotations data saving success but not fetch
data
With this annotations Post is not working? Do you mean the same
@@Javatechie yes
Hi, did you find the answer
Are you also facing same issue?
@@Javatechie yes