{"id":1942,"date":"2019-09-01T12:00:00","date_gmt":"2019-09-01T10:00:00","guid":{"rendered":"https:\/\/kindsonthegenius.com\/blog\/hibernate-relationship-tutorial-onetomany-and-manytoone\/"},"modified":"2026-07-05T03:24:17","modified_gmt":"2026-07-05T01:24:17","slug":"hibernate-relationship-tutorial-onetomany-and-manytoone","status":"publish","type":"post","link":"https:\/\/kindsonthegenius.com\/blog\/hibernate-relationship-tutorial-onetomany-and-manytoone\/","title":{"rendered":"Hibernate Relationship Tutorial \u2013 @OneToMany and @ManyToOne (Part 1 to 7)"},"content":{"rendered":"<p>I&#8217;m happy, that finally we have a complete tutorial that addresses the challenges faced by many programmers. Entity relationships(@OneToMany and @ManyToOne). So everything about relationships in covered here. Use the links to quickly jump to any section you want.<br \/>\nWe explain the concept, then we implement it.<\/p>\n<ul>\n<li><a href=\"#t1\">Part 1 \u2013 Introduction<\/a><\/li>\n<li><a href=\"#t2\">Part 2 \u2013 Setting Up<\/a><\/li>\n<li><a href=\"#t3\">Part 3 \u2013 @ManyToOne<\/a><\/li>\n<li><a href=\"#t4\">Part\u00a0 4 \u2013 Configuring H2 Database<\/a><\/li>\n<li><a href=\"#t5\">Part 5 \u2013 Database Initialization(data.sql)<\/a><\/li>\n<li><a href=\"#t6\">Part 6 \u2013 @OneToMany<\/a><\/li>\n<li><a href=\"#t7\">Part 7 &#8211;\u00a0mappedBy Attribute<\/a><\/li>\n<li><a href=\"https:\/\/kindsonthegenius.com\/tempsite\/hibernate-relationship-tutorial-onetomany-and-manytoone-part-8-to\/\">Part 8 to 12 &#8211; Infinite Recursion, @JoinColumn, JsonManagedReference etc<\/a><\/li>\n<li><a href=\"https:\/\/kindsonthegenius.com\/tempsite\/hibernate-relationship-tutorial-onetomany-and-manytoone-part-13-to-16\/\">Part 13 to 16 &#8211; Retrieving Child Records<\/a><\/li>\n<li><a href=\"https:\/\/kindsonthegenius.com\/tempsite\/hibernate-relationship-tutorial-onetomany-and-manytoone-part-17-to\/\">Part 17 to 20 &#8211; Inserting New Records. Using REST Client<\/a><\/li>\n<li><a href=\"https:\/\/kindsonthegenius.com\/tempsite\/hibernate-relationship-tutorial-onetomany-and-manytoone-part-21-to-8\/\">Part 21 to 28 &#8211; Deleting, CascadeTypes and FetchTypes<\/a><\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p><strong id=\"t1\">Part 1 \u2013 Introduction<\/strong><\/p>\n<p>In this comprehensive tutorial, we&#8217;ll build an application made up of three entities: Location, User and Post.<\/p>\n<p>How they relate is that: Location contains users and User has posts. This is illustrated in the figure below<\/p>\n<figure id=\"attachment_1150\" aria-describedby=\"caption-attachment-1150\" style=\"width: 735px\" class=\"wp-caption aligncenter\"><a href=\"https:\/\/www.kindsonthegenius.com\/wp-content\/uploads\/2020\/09\/Relationship-Diagram.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-1150 size-large\" src=\"https:\/\/www.kindsonthegenius.com\/wp-content\/uploads\/2020\/09\/Relationship-Diagram-1024x428.jpg\" alt=\"Relationship Diagram\" width=\"735\" height=\"307\" \/><\/a><figcaption id=\"caption-attachment-1150\" class=\"wp-caption-text\">Relationship Diagram<\/figcaption><\/figure>\n<p>&nbsp;<\/p>\n<p><strong id=\"t2\">Part 2 \u2013 Setting Up the Application<\/strong><\/p>\n<p>In this part, we would set up a Spring Boot Starter application. Follow the steps below:<\/p>\n<p><strong>Step 1:<\/strong> Create a Spring application (you should be able to do this by now). Add the starter web dependency. Also add the starter-jpa dependency.<\/p>\n<p><strong>Step 2:<\/strong> Create three classes corresponding to Post, User and Location. Put them in the models package<\/p>\n<p><strong>Step 3:<\/strong> Also create all the repositories in the repositories package<\/p>\n<p><strong>Step 4:<\/strong> Create the services in the Services package<\/p>\n<p><strong>Step 5:<\/strong> Finally, create the RestControllers in the controllers package<\/p>\n<p>&nbsp;<\/p>\n<p><strong id=\"t3\">Part 3 &#8211; @ManyToOne Relationship<\/strong><\/p>\n<p>We would now configure Many-to-one relationship between the User and the Location entities.\u00a0Similarly, we do the same between the Post and User entities.<\/p>\n<p>Follow the steps below:<\/p>\n<p><strong>Step 1:<\/strong> Annotate the Location field of the User entity with @ManyToOne annotation.<\/p>\n<p><strong>Step 2:<\/strong> Annotate the User field of the Post entity with @ManyToOne annotation<\/p>\n<p>When you use these annotation, the entity decides to handle the relationship. In the first case, the <strong>User entity<\/strong> does this by creating a column called location_id in the User table. Similarly, the <strong>Post entity<\/strong> does this by creating a column called user_id<\/p>\n<p>&nbsp;<\/p>\n<p><strong id=\"t4\">Part 4 &#8211; Configure the H2 Database<\/strong><\/p>\n<p>H2 Database is an in-memory database that is normally used during development. Now we configure the H2 database following the steps below:<\/p>\n<p><strong>Step 1:<\/strong> Open the application.properties file. It is in the src\/main\/resources folder<\/p>\n<p><strong>Step 2:<\/strong> Add the following code in the application.properties file<\/p>\n<p>&nbsp;<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">spring<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">h2<\/span><span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">console<\/span><span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">enabled<\/span><span style=\"color: #333333;\">=<\/span><span style=\"color: #008800; font-weight: bold;\">true<\/span>\nspring<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">datasource<\/span><span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">platform<\/span><span style=\"color: #333333;\">=<\/span>h2\nspring<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">datasource<\/span><span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">url<\/span><span style=\"color: #333333;\">=<\/span><span style=\"color: #997700; font-weight: bold;\">jdbc:h2:mem:<\/span>socialdb\nspring<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">datasource<\/span><span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">driverClassName<\/span><span style=\"color: #333333;\">=<\/span>org<span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">h2<\/span><span style=\"color: #333333;\">.<\/span><span style=\"color: #0000cc;\">Driver<\/span>\n<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>Step 3:<\/strong> Run the the application and access the H2 Console<\/p>\n<p>&nbsp;<\/p>\n<p><strong id=\"t5\">Part 5 &#8211; Database Initialization (data.sql)<\/strong><\/p>\n<p>We would write a script to insert some initial data into the database. Follow the steps below:<\/p>\n<p><strong>Step 1:<\/strong> Create a file inside the <em>src\/main\/resource<\/em>s folder. Name it data.sql<\/p>\n<p><strong>Step 2:<\/strong> Open the file and add the following code<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">insert into Location(id, name) values(1, 'Budapest, Hungary');\ninsert into Location(id, name) values(2, 'Owerri, Nigeria');\ninsert into Location(id, name) values(3, 'Califonia, USA');\n\ninsert into User(id, firstname, lastname, email, location_id) values(1, 'Kindson', 'Munonye', 'kany@gmail.com', 1);\ninsert into User(id, firstname, lastname, email, location_id) values(2, 'Jeffrey', 'Yuba', 'yuba@gmail.com', 2);\ninsert into User(id, firstname, lastname, email, location_id) values(3, 'Solace', 'Okeke', 'solace@gmail.com', 3);\n\ninsert into Post(id, post_date, details, user_id) values(1, CURRENT_TIMESTAMP(), 'Very good post', 1);\ninsert into Post(id, post_date, details, user_id) values(2, CURRENT_TIMESTAMP(), 'A rainy day', 2);\ninsert into Post(id, post_date, details, user_id) values(3, CURRENT_TIMESTAMP(), 'nice tutorials', 3);\n<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>Step 3:<\/strong> Run the application. Access h2-console and verify that the data is inserted. The H2-Console window is shown below<\/p>\n<figure id=\"attachment_1152\" aria-describedby=\"caption-attachment-1152\" style=\"width: 839px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-1152 \" src=\"https:\/\/www.kindsonthegenius.com\/wp-content\/uploads\/2020\/09\/H2-Console.jpg\" alt=\"H2 Console\" width=\"839\" height=\"518\" \/><figcaption id=\"caption-attachment-1152\" class=\"wp-caption-text\">H2 Console<\/figcaption><\/figure>\n<p>&nbsp;<\/p>\n<p><strong id=\"t6\">Part 6 &#8211; @OneToMany Relationship<\/strong><\/p>\n<p>This relationship allows us to get list of child entities under a parent entity. For examples, we could get the list of posts for a user. Or we could get list of users in a location. Follow the steps below:<\/p>\n<p><strong>Step 1:<\/strong>\u00a0 In the Location class, add a private field of List&lt;User&gt; type. (This means list of all users under that location)<\/p>\n<p><strong>Step 2:\u00a0<\/strong> Annotate this field with the @OneToMany annotation<\/p>\n<p><strong>Step 3:\u00a0<\/strong> In the User class, add a private field of List&lt;Post&gt; type. (This means list of all posts for that user)<\/p>\n<p><strong>Step 4:<\/strong> Annotate this field with the @OneToMany annotation<\/p>\n<p><strong>Step 5:<\/strong> Run the application and access the H2 Console<\/p>\n<p>Now, you will notice in the H2 console that there are additional tables that have been created.<\/p>\n<p>What happens here is this:<\/p>\n<p>for the User-Location relationship, the <strong>Location\u00a0entity<\/strong> decides to handle the relationship mapping by creating an additional table called LOCATION_USERS.<\/p>\n<p>Again, for the Post-User relationship, the User entify decides the handle the relationship by creating an additional table called POST_USERS.<\/p>\n<p>But remember that the relationship mapping has already been handled using by the @ManyToOne using the location_id and the user_id columns.<\/p>\n<p>This duplicate mapping can be resolved using the mappedBy attibute<\/p>\n<p>&nbsp;<\/p>\n<p><strong id=\"t7\">Part 7 &#8211; The mappedBy Attribute<\/strong><\/p>\n<p>The mappedBy is an attribute of the @OneToMany relationship. You use the mappedBy to tell the @OneToMany annotation that the relationship has already been handled using a foreign key in the corresponding entity. In this way, an additional table is not created.<\/p>\n<p>To do this:<\/p>\n<p><strong>Step 1:<\/strong> In the @OneToMany annotation in the Location entity, add mappedBy=&#8221;location&#8221;<\/p>\n<p><strong>Step 2:<\/strong> In the @OneToMany annotation in the User entity, add mappedBy=&#8221;user&#8221;<\/p>\n<p><strong>Step 3:<\/strong> Launch the application, access H2-Console and check that there are no more duplicate tables;<\/p>\n<p>Let&#8217;s now move on the the next section&#8230;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I&#8217;m happy, that finally we have a complete tutorial that addresses the challenges faced by many programmers. Entity relationships(@OneToMany and @ManyToOne). So everything about relationships &hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"pagelayer_contact_templates":[],"_pagelayer_content":"","footnotes":""},"categories":[414],"tags":[],"class_list":["post-1942","post","type-post","status-publish","format-standard","hentry","category-programming"],"_links":{"self":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts\/1942","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/comments?post=1942"}],"version-history":[{"count":1,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts\/1942\/revisions"}],"predecessor-version":[{"id":2110,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts\/1942\/revisions\/2110"}],"wp:attachment":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/media?parent=1942"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/categories?post=1942"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/tags?post=1942"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}