×
DocsConsole

DocsConsole

Hibernate ManyToOne Association Example

By | | Updated : 2020-01-22 | Viewed : 69 times

Hibernate ManyToOne Association  Example

In this post, we will learn how to map ManyToOne Association between two Hibernate entities by using a foreign key constraint. We will see both annotation and XML based example in the current post.

ManyToOne Association

ManyToOne Association means many rows of one table should be referred to only one row of another table. For example, take the scenario of author and books. Many numbers of books can be written by only one author. So Many books can be mapped to the same author by using the ManyToOne Association.

Database Setup

Here Database Setup means creating the required table for executing the ManyToOne Association Example. Please see below-given tables are required.

Create table for Author
CREATE TABLE `author` (
    `AUTHOR_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `AUTHOR_NAME` VARCHAR(50) NOT NULL,
     PRIMARY KEY (`AUTHOR_ID`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=13;
Create table for Book
CREATE TABLE `book` (
    `BOOK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `AUTHOR_ID` INT(10) UNSIGNED NOT NULL,
    `BOOK_NAME` VARCHAR(50) NOT NULL,
    `BOOK_PRICE` DOUBLE NOT NULL,
    PRIMARY KEY (`BOOK_ID`),
    INDEX `AUTHOR_ID` (`AUTHOR_ID`),
    CONSTRAINT `BOOKS_FK` FOREIGN KEY (`AUTHOR_ID`) REFERENCES  `author` (`author_id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=34;

Required Dependencies

In the created maven project we need to add the below given required dependency jars in the pom.xml.

	<!-- Hibernate 5.4.3.Final -->
	 <dependency>
		 <groupId>org.hibernate</groupId>
	 	<artifactId>hibernate-core</artifactId>
	 	<version>${hibernate-core-version}</version>
	 </dependency>
	 
	 <!-- MySql Driver -->
	 <dependency>
		 <groupId>mysql</groupId>
		 <artifactId>mysql-connector-java</artifactId>
	 	<version>${mysql.connector.version}</version>
	 </dependency>

ManyToOne with Foreign Key

Annotation Example

In this ManyToOne association example, one Author entity will be mapped with Books. First, we will write the entity classes with annotations.

Entity class for Book
@Entity
@Table(name = "BOOK")
public class Book {

	

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "BOOK_ID")
	private Long bookId;

	@Column(name = "BOOK_NAME")
	private String bookName;

	@Column(name = "BOOK_PRICE")
	private Double bookPrice;

	@ManyToOne
	@JoinColumn(name = "AUTHOR_ID", nullable = false,foreignKey = @ForeignKey(name = "BOOKS_FK"))
	private Author author;

	//Setters and getters
	

}
Entity Class for Author
@Entity
@Table(name = "AUTHOR")
public class Author {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "AUTHOR_ID")
	private long prodDetailsId;

	@Column(name = "AUTHOR_NAME")
	private String authorName;

	//setters and getters
}

Here we have to write the @ManyToOne with @JoinColumn in Book class. Please notice that in Book entity class. These are most important annotations for ManyToOne. But in the Author class, no extra annotation is not required for ManyToOne. We will see now the same equivalent XML configuration for the same.

XML Example

book.hbm.xml
	<class name="Book" table="book">
	
		<id name="bookId" column="BOOK_ID">
			<generator class="identity" />
		</id>
		<property name="bookName" column="BOOK_NAME"></property>
		<property name="bookPrice" column="BOOK_PRICE"></property>
		<many-to-one name="author" class="com.docsconsole.tutorials.hibernate5.entity.Author" fetch="select" foreign-key="BOOKS_FK">
			<column name="AUTHOR_ID" not-null="true" />
		</many-to-one>
	</class>
author.hbm.xml
	<class name="Author" table="AUTHOR">

		<id name="authorId" column="AUTHOR_ID">
			<generator class="identity" />
		</id>
		<property name="authorName" column="AUTHOR_NAME"></property>

	</class>

Here also we have added xml tag many-to-one in book.hbm.xml. No extra tag is added in author.hbm.xml.

Saving/Retrieving Entities

Need to create author and book entity objects as given below.

Create author and book entity objects
	Author author1 = new Author();
	 author1.setAuthorName("Author1");
	 
	 Book book1 = new Book("Book1", 100.0, author1);
	 Book book2 = new Book("Book2", 200.0, author1);
	 Book book3 = new Book("Book3", 300.0, author1);

Save the objects as given below by using the session.

Save the Entity objects
// Save the Model objects
			session.save(author1);
			session.save(book1);
			session.save(book2);
			session.save(book3);

To check code base please look github.com/Docsconsole

Leave A Reply