Using @OneToMany annotation in JPA

Suppose, you are working on a project where the database has two tables, such as student and clazz, structured like below:

As you can see, the clazz table has columns id and name with the primary key id. Student table has columns id, name and clazz_id with primary key id. In this student table, we have also defined a foreign key from it to the clazz table, meaning that a class can have more than one student, and many students can be classed. In JPA, to express the relationship of many students with the same class, we will use the @ManyToOne annotation, and to express a class relationship with many students, we will use the @OneToMany annotation.

We have learned about annotation @ManyToOne in the previous tutorial. This tutorial I will be with you to learn about annotation @OneToMany.

First, I will create a Maven project to illustrate for the above example:

Using @OneToMany annotation in JPA

I will add Hibernate dependency to use JPA as follows:

In this example, I am working with MySQL so I will also add the MySQL Driver dependency as follows:

Next, I will create the Clazz and Student entities to display their information.

Using @OneToMany annotation in JPA

The content of the Clazz entity is as follows:

and entity Student:

Now, we will use the @OneToMany annotation to show the relationship of the clazz table to the student table in JPA.

Because, this is a one-to-many relationship seen from the Clazz object so I’ll put the @OneToMany annotation in the Clazz object as follows:

As you can see, in this annotation, I have declared an attribute mappedBy with a value is clazz. The “clazz” value here is the variable name defined with the @ManyToOne annotation in the Student entity.

Here, we have completed using the @OneToMany annotation to define the Clazz entity. I will try to see how it works.

I will add a configuration file, persistence.xml:

Using @OneToMany annotation in JPA

with the following content:

Suppose, now in the database, I have the following data:

Using @OneToMany annotation in JPA

With this code:

The results will look like below:




Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
Facebook
4Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.