We will learn how to implement unidirectional relationships in
One-To-Many associations in this tutorial.
1. What is a One-To-Many association
Consider the following example: John is the owner of a popular blogging site
with a large number of Blogs on a variety of topics. So, in this case,
One Owner is the author of Many Blogs. As an example,
one publishing house may have published books by many authors,
or one blog may have many reviews.
One entity has a relationship with a list/set of entities in a One-To-Many
relationship.
Consider the following example of the Owner's association with the
Blogs:
// Blog class
public class Blog {
private Int id;
…
private String title;
…
}
// Owner class
public class Owner {
private Int id;
…
private List<Blog> blogs;
…
}
The key point is to pay attention to the declaration of the
blogs variable in the Owner class. Because Owner has
several blogs, the Owner class should contain a List of blogs.
As a result, Many (List) Blog is associated with One Owner -
this is a One-To-Many relationship.
In the One-To-Many association, we will first implement a
unidirectional relationship, and then we will investigate the
bidirectional relationship.
2. Spring Boot project creation
We will use Spring Initializr to create a new Spring Boot project, which will generate a basic
structure for our Spring Boot project. The following dependencies have
been added:
- Spring Boot DevTools - necessary development tools
- Spring Web - for Spring MVC and embedded Tomcat that will run the Spring Boot application
- Spring Data JPA - Java Persistence API
- MySQL Driver - JDBC driver for MySQL (for other DB you have to choose that dependency for that DB)
Then, to download the project zip file, click GENERATE. Unzip the
zip archive. Import the project as a Maven project into Eclipse/STS.
...
...
You can download the
source code.
Happy coding!!! 😊

No comments:
Post a Comment