Partho
Partho

Reputation: 2715

Spring boot hibernate bidirectional mapping many to one can not established relationship

I have two entity table one category and other is subject

My category entity

@Entity
public class Category extends AuditableEntity {

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

@Column(unique = true)
private String name;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "description_id")
private CategoryDescription description;

@OneToMany( mappedBy = "category", cascade = CascadeType.ALL, 
orphanRemoval = true)
private List<Subject> subjects;

//getter and setter
}

And my Subject entity

@Entity
public class Subject extends AuditableEntity {

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

@Column(unique = true)
private String name;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "description_id")
private SubjectDescription description;

@ManyToOne(fetch = FetchType.EAGER)
private Category category;

//Getter and Setter
}

Category Repository

@Repository
@Transactional
public interface CategoryRepository extends 
JpaRepository<Category, Integer> {
}

Subject Repository

@Repository
@Transactional
public interface SubjectRepository extends JpaRepository<Subject, 
Integer> {
}

Category Controller

@RestController
@RequestMapping("/category/api/")
public class CategoryResource {

private final CategoryService categoryService;
private final SubjectService subjectService;
private final TopicService topicService;

public CategoryResource(CategoryService categoryService, 
SubjectService subjectService, TopicService topicService) {
    this.categoryService = categoryService;
    this.subjectService = subjectService;
    this.topicService = topicService;
}

@PostMapping("save")
public void saveCategory(@RequestBody Category category) {

    categoryService.save(category);

}

I am using postman to save data. Problem is that after saving data to the category and subject table my subject table column category_id is null i can not established a relationship between them my sql structure and data is after saving data it shows like

Category table

enter image description here

Subject Table

enter image description here

category_id is NULL how to set category id i am trying many ways but couldn't find a solution.Please help me to solve this issue

Upvotes: 1

Views: 408

Answers (1)

thechaoticpanda
thechaoticpanda

Reputation: 416

It's great that you are learning spring boot!

To answer your question since the answer is pretty simple, your code is missing category in subject.

subject.setCategory(category);

Now this might cause you an exception, so make sure you save category before you persist subject.

Cheers!

Upvotes: 2

Related Questions