JPA/Hibernate Fundamentals 2023 - Lesson 7 - Many-to-many relationships

Ғылым және технология

In this stream, we discuss the JPA specification and learn to implement the persistence layer of a Java app using a JPA implementation such as Hibernate.
KEY POINTS:
Creating Many-to-Many Relationships
In this part of the tutorial, the author discusses the concept of many-to-many relationships in the context of JPA and Hibernate. These relationships involve entities being connected to multiple other entities, and the author emphasizes that there is no direct physical representation of many-to-many relationships in database tables. Instead, a join table is used behind the scenes to establish these connections. The author also explains that while it's possible to use one-to-many and many-to-one relationships to represent a many-to-many relationship, it's not recommended, and it's better to keep the join table as a separate entity for clarity and maintainability.
Creating Entity Classes Based on Tables
In this part of the tutorial, the author explains the real-world approach to creating entity classes based on existing database tables. The author emphasizes that in practical applications, tables are usually created in advance using tools like Flyway or Liquibase for version management. Entity classes are then written to match the structure of these pre-existing tables. The author clarifies that in most cases, you won't generate tables directly from entity classes in real-world scenarios, as it's mainly done in tutorials to save time. This distinction is important to avoid confusion and understand the typical workflow for building database-backed applications.
Creating a Bidirectional Relationship
In this part of the tutorial, the author explains how to create a bidirectional many-to-many relationship using JPA and Hibernate. The author starts by demonstrating a one-directional relationship where only one entity knows about the relationship. Then, the author transitions to a bidirectional relationship by making the second entity aware of the relationship as well. Bidirectional relationships allow both entities to reference each other, providing flexibility in querying and managing relationships. The author also discusses how to use the @JoinTable annotation to specify the details of the join table, such as table names and column names.
Demonstrating Data Insertion in a Many-to-Many Relationship
In this part of the tutorial, the author demonstrates the insertion of data into a many-to-many relationship created between the 'User' and 'Group' entities. The author shows that when using a bidirectional relationship, both entities can be specified as owners, and data can be inserted into the join table representing the relationship. The author provides code examples for creating and persisting instances of 'User' and 'Group,' ensuring that both sides of the relationship are correctly maintained. The resulting database records are inspected to confirm that the many-to-many relationship is working as expected, with users belonging to multiple groups and groups having multiple users.
Understanding Lazy Loading in ORM
In this section of the tutorial, the author explains the concept of lazy loading in Object-Relational Mapping (ORM). By default, collections in ORM are set to fetch data lazily. The author provides a clear rationale for this default behavior, emphasizing the importance of minimizing memory consumption when dealing with large datasets. Lazy loading ensures that data is retrieved from the database only when it is actually needed, improving application performance and reducing the risk of running into memory issues. The author advises against using eager fetching for collections unless it is absolutely necessary, as it can lead to inefficient data retrieval and potential memory problems.
Upcoming Topics in Entity Modeling
In this concluding part of the tutorial, the author outlines the topics that will be covered in future lessons related to entity modeling. The author mentions that upcoming topics will include discussions on enumerations, embedded objects, inheritance, and mapping superclasses. These topics will provide a more comprehensive understanding of how to structure entities in ORM. Additionally, the author hints at the next major phase of the tutorial, which will focus on queries and how to manipulate data using JPA Query Language (JPQL). The author encourages viewers to stay tuned for these upcoming lessons, which will delve deeper into the practical aspects of ORM development.

Пікірлер: 42

  • @laurspilca
    @laurspilca9 ай бұрын

    Code on GitHub: github.com/lspil/youtubechannel/tree/master/jpa_2023_c7_e1

  • @lazarsjojic
    @lazarsjojic27 күн бұрын

    Great video

  • @dragomirdalin
    @dragomirdalin9 ай бұрын

    I love your series, It would be interesting if this series will also contains topics such as liquibase, indexing, performance testing, best practices when it comes with large databases, optimistic and pessimistic locking, versioning, testing with JPA and Hibernate

  • @laurspilca

    @laurspilca

    9 ай бұрын

    Hi. Thanks. I will keep out what is not JPA specific. I want this to be a playlist clean only on JPA/Hibernate. But yes, I'll also make videos on all the subjects you mention :)

  • @momedalhouma14
    @momedalhouma1410 ай бұрын

    best jpa playlist so far. thanks

  • @helloworld5810
    @helloworld58105 ай бұрын

    Thank you so much it took me almost two weeks to search for the right content. Eventually i find yours and got the concept. I love your style of teaching. Thank you so much again

  • @laurspilca

    @laurspilca

    5 ай бұрын

    Happy to hear! Enjoy!

  • @miggeld.1537
    @miggeld.15374 ай бұрын

    Thank you, Laurentiu for such a detailed and nice explanation of Hibernate features . Could you make please series about migrations, that you mentioned and also how to work with No SQL databases in Spring?

  • @tenchopapazov2431
    @tenchopapazov24313 ай бұрын

    Hi Laur, thank you very much for the content! In this topic for many-to-many relationship you said that ORM should not cover join tables but if there is a case where in the join tables we want additional columns to have additional data for specific realtion. For example we have a player and a server tables and we want additional colums for score of the player in the respective server. How do we design it in the database and in the ORM?

  • @laurspilca

    @laurspilca

    3 ай бұрын

    Hi. In the case the join table has other columns it is no longer a join table. It is an entity.

  • @trishulcurtis1810
    @trishulcurtis18108 ай бұрын

    great tutorial!

  • @rohitgupta025
    @rohitgupta0255 ай бұрын

    You can put a comment above that hibernate code, // not to be used in production

  • @laurspilca

    @laurspilca

    5 ай бұрын

    Good idea!

  • @86Saurabh1
    @86Saurabh13 ай бұрын

    Do you plan to make a tutorial on Flyway or Liquidbase? Apologies if you have already done that.

  • @laurspilca

    @laurspilca

    3 ай бұрын

    Hello. Yes. I plan to do something about this in the near future :)

  • @BravePro
    @BravePro9 ай бұрын

    For people wondering what the answer to Flavor's questions is. I'm assuming it's the most usual cause for "failed to lazily fecth". Imagine you have two entites which have a relationship User and Roles. User has many Roles. The fetch is set to lazy. Do you see how laur opens a transaction does something inside and commits it? So imagine in that transaction we just fetch one user. Nothing more, nothing less. That user ofc has roles but since the fetch is set to lazy we won't get the roles in the context. Then after we commit the transaction we try to access the roles. And since that is not in a transaction and not in the context hibernate will throw that error. Solution is either opening a new transaction or making the fetch eager. (And maybe doing unproxy but I don't know it well enough to suggest it)

  • @laurspilca

    @laurspilca

    9 ай бұрын

    Yeap. This is totally true. Once you closed the transaction you can't get the lazily fetched data.

  • @andriikorniienko
    @andriikorniienko2 ай бұрын

    thanks again for the great content! tbh though, i don't understand the purpose of using jointables, is there a short and concise answer to this, or maybe are there resources that could provide relevant knowledge or examples?

  • @josuegarcia3355
    @josuegarcia33553 ай бұрын

    Another Question in this example for specially for Bidirectional but not necessary we need to link the entities instances but remember to connect them, it could be something that people will miss is there a way we can avoid this issue, The same applies for the other types of like @OneToOne and @OneToMany, I might forget to link the entities like users to groups, post to comments, user to address etc. etc... Do you know if there is a pattern to avoid this, what would be good practice? ex. Group g1 = new Group() Group g2 = new Group() User u1 = new User() User u2 = new User() g1.setUsers(List.of(u1, u2)) g2.setUsers(List.of(u1)) u1.setGroup(List.of(g1,g2)) u2.setGroup(List.of(g1));

  • @laurspilca

    @laurspilca

    3 ай бұрын

    Well, we do need bi-directional relationship. You cannot avoid this. I don't know a way to enforce the link. So, the best is to test your implementations properly. Usually you'll observe inconsistencies in the data if you miss something :)

  • @nipunkataria4588
    @nipunkataria45889 ай бұрын

    Those who are getting sql error when SQL Error: 1064, SQLState: 42000 while trying to insert data in groups table when running the application. I am at 27:40 sec mark. I found that it is due to the fact that "groups" is a reserved word in mysql database. Hence getting the error. To get around this error please add backticks (`) character around the @Table annotation in Group entity. @Table(name = "`groups`"). New query generated will look like insert into `groups` (name) values (?) I am wondering why its not happening in the video. Can someone explain ?

  • @nipunkataria4588

    @nipunkataria4588

    9 ай бұрын

    I am using mySQL version 8.0.33-0ubuntu0.22.04.2 for Linux on x86_64 ((Ubuntu))

  • @laurspilca

    @laurspilca

    9 ай бұрын

    Hi. It can be related to the MySQL version you use.

  • @grigorypiskunov418

    @grigorypiskunov418

    6 ай бұрын

    you can rename table to ugroups e.g. and update class. It will works for you.

  • @josuegarcia3355
    @josuegarcia33553 ай бұрын

    Thanks a lot, Laur, question in the beginning of the video, what do you mean is better have multiple OneToMany that a ManyToMany I understand about performance and simplicity would be easier, but I don't get how you can replace it with multiple OneToMany, can you show an example to be more clear? Thanks

  • @laurspilca

    @laurspilca

    3 ай бұрын

    There is no right answer to that since it really depends on the case. Both are good if used properly.

  • @ilorvi
    @ilorvi10 ай бұрын

    will there be lesson about HQL queries? i.e JOIN FETCH?

  • @laurspilca

    @laurspilca

    10 ай бұрын

    Yep. But I'll actually refer to them as JPQLs since we discuss broadly about JPA.

  • @fipabrate
    @fipabrate10 ай бұрын

    What if users_groups table has its own values. For example if we want to have date when user joined the group?

  • @laurspilca

    @laurspilca

    10 ай бұрын

    Hi. Thanks for the question. If that table has its own values it means it's no longer a join table but a real entity with attributes.

  • @fipabrate

    @fipabrate

    10 ай бұрын

    @@laurspilca and then we use one to many to that entity

  • @AhmedZahranDEV
    @AhmedZahranDEV3 ай бұрын

    What if we need to add custom columns in the join table ?

  • @laurspilca

    @laurspilca

    3 ай бұрын

    Hello. Good question. Then it's not a join table anymore -> it becomes an entity.

  • @OsteenOmega
    @OsteenOmega9 ай бұрын

    if the join table has an attribute such as date, can it be considered as an entity or it remains to be a join table?

  • @laurspilca

    @laurspilca

    9 ай бұрын

    Yes. In that case it's not a simple join table anymore. But that doesn't mean it's also a good design. One who design the data model should ask themselves, what does that entity represent? Is that a good way to model the data? This depends on the case of course.

  • @BravePro
    @BravePro9 ай бұрын

    Hey Laur! Quick question. Since you said having a join table as an entity is an anti-pattern and shouldn't be done. And also never modeling the relatioship as ManyToOne and OneToMany instead of ManyToMany. I'm currently making a project which has a 3-way join table. User, Company, Role. Basically trying to achieve the same thing as discord. Having different roles for each company for each user. I have an entity for that join table which has unidirectional @ManyToOne relationships with all 3 other entities. What would suggest I change or do you think what I've done is fine?

  • @laurspilca

    @laurspilca

    9 ай бұрын

    Hi. I don't understand. In your case you really have three entities and not a many-to-many. What I was saying it's an antipattern is to force a join table being an entity. That doesn't mean you won't have situations where you really have an entity between two other entities. I hope this helps.

  • @BravePro

    @BravePro

    9 ай бұрын

    @@laurspilca Fair enough haha. Didn't think of it that way. Thanks!

  • @mostafasaleh2806
    @mostafasaleh280610 ай бұрын

    Could you make E-commerce project, please?

  • @laurspilca

    @laurspilca

    10 ай бұрын

    As an example you mean? Yes. Let's take this however outside the series since it would cover multiple technologies.

  • @mostafasaleh2806

    @mostafasaleh2806

    10 ай бұрын

    @@laurspilca Thank you Sir.

Келесі