Skip to main content

JPA : One to Many Mapping using Hibernate Spring Boot

STEP 1 :: Add the dependencies

You need to add the following dependencies in your build.gradle file.
    
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-jdbc')
runtime('mysql:mysql-connector-java')

STEP 2 :: Make Entity classes

You need to create two entity QUESTION and TOPIC.

Here the Topic Entity will have an annotation @OneToMany , this indicates the following
  • This one topic can have many questions.
  • All the questions will be deleted or updated when topic is deleted/updated.
  • Its mapping is defined by Entity Question by the mapping of topic variable.
  • It will give a list of all question of a topic when it is fetched
  • If you do not need questions when topic is fetched then make fetch type as LAZY



@OneToMany(cascade = CascadeType.ALL,mappedBy = "topic",fetch = FetchType.EAGER)
private List questions;


Here the Question entity will have the annotation @ManyToOne, this will indicate the following,
  • One question can belong to only one topic.
  • When you fetch question, it will not fetch the topic because the fetch mode is LAZY
  • It will join make the foreign key column as topic_id. If you want any other name, then you can define using @JoinColumn annotation


@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "topic_id")
private Topic topic;


Full class code is shown below

Comments