Skip to main content

Spring Data JPA One-To-Many Explained Simply

 One-to-many relationships are used when a single entity is associated with many other entities.

For example, a Blog can have many associated Posts, BUT each Post is only associated with one Blog.

This simply means you map child entities (Posts) as a collection in the parent object (Blogs).

Spring Data JPA then provides the @OneToMany annotation for this case. @OneToMany is the parent-side of the relationship. We call this a unidirectional @OneToMany association.

When the child-side manages a relationship, we have a unidirectional @ManyToOne association. In this association, the child entity (Post) has an object reference to its parent (Blog).

This child/parent relationship is created by the use of mapping child foreign keys mapping to the parent.

In order to get the most fully functional mapping, it is best to use a unidirectional many-to-one association,

JPA Unidirectional One To Many Example

First, let’s create a model for our Blog model:

@Entity
@Table(name = "blogs")
public class Blog {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  @Column(name = "title")
  private String title;

  @Column(name = "description")
  private String description;

  @Column(name = "published")
  private boolean published;

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
  @JoinColumn(name = "blog_id")
  private Set<Comment> comments = new HashSet<>();

}

The above example includes Comments in our OneToMany mapping. We use this annotation in conjunction with @JoinColumn that will create a column in the child table (Comments) storing the parent’s Id (Blog).

The orphanRemoval helps us remove children (Comments) from the database if we delete the parent (Blog)

Bidirectional vs Unidirectional Relationships

In our example, we are using a unidirectional relationship. It is important to understand the difference between a unidirectional relationship and bidirectional relationship.

This biggest difference is that bidirectional relationships provide “navigation” access in both directions.

“Navigation” in this sense is a fancy term for, you can access these model properties thru the property.

Navigational access is not always good especially if you have MANY children properties.

Unless you have hundreds or thousands of children, unidirectional is *usually* the best choice. According to Hibernate documentation, bidirectional is the best choice in most cases.

@Entity
@Table(name = "comments")
public class Comment {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(name = "title"
  private String title;

  @Lob
  private String content;
}

Notice in this class we do not need to add any extra annotations because this is a unidirectional relationship.

Comments

Popular posts from this blog

Hoisting In JavaScript Explained Simply

  JavaScript is a weird language. We are all aware of this. But one of the biggest peculiarities is the concept of hoisting. Because hoisting is centered around variable declaration, it confuses beginners to no end. In this blog, I am going to give practical, real-world explanations of hoisting! Hoisting Introduction Hoisting is a default behavior which variables and function are moved to the top of the scope before JS executes.   Even more simply put, it allows you to use variables and functions before declaring them. x = 1; console.log(x); //This is valid and will execute. var x; Essentially, JavaScript is taking “var x;” variable  declaration  and placing it above x = 1. The biggest caveat to hoisting is that it only works with declaration BUT not initialization of variables. console.log(x) //This will be undefined because it is being initialized. var x = 1; Hoisting Functions in Javascript JavaScript engine moves function declarations to the top similar to varia...

Spring Data JPA Many-To-Many Explained Simply

  At a certain point in your Java career, it is inevitable to arrive at a point where you have models that are related to each other but cannot be solved with foreign keys. A good example of a many-to-many relationships is the relationship between rice and sauces. I love ALL types of different rice with different types of sauces. Sometimes I like Jasmine rice with spicy curry, while other times I like sticky rice with soy sauce. In a pinch, I’ve even ate Jasmine rice with soy sauce! *crowd gasps* Overall, many-to-many is a relationship that has infinite amounts of different combinations. Try to apply the rice analogy to a  one-to-many relationship  and it will not work. Many-To-Many Relationships To maintain a many-to-many relationship between two tables in a database, the only way is to have a third table which has a reference to both sides of the table. This table is called a “join” table and each entry in this table will connect the source table and target table. Many-...

CSS ‘>’, ‘+’, ‘~’ Selectors Explained Simply

  Knowing CSS selectors is easily one of the most important aspects of web development. As a former backend developer, it makes me cringe how bad I was at CSS selectors. Not knowing selectors is known to cause mangled front ends and ugly Bootstrap UI’s! Element selectors Descendant selectors Class selectors Id Selectors Child Selectors Adjacent Selectors Pseudo Selectors Element Type Selectors The most basic CSS selectors are Element Type Selectors.  With elements selectors all you are doing is selecting the element. Element selectors are most common when you first setup your CSS and assign very broad actions like fonts, colors, line heights, etc. Very rarely will you use CSS selectors for things like positioning. body { font-family : var ( --body-font ) ; color : var ( --text-dark ) ; } Descendant Selectors The descendant selector is used to match elements that are descended from another matched selector. This selector is easy to spot because it is just a space....