【问题标题】:Spring boot hibernate bidirectional mapping many to one can not established relationshipspring boot hibernate双向映射多对一无法建立关系
【发布时间】:2021-07-16 07:47:38
【问题描述】:

我有两个实体表,一个是类别,另一个是主题

我的类别实体

@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
}

还有我的主题实体

@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
}

类别存储库

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

主题库

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

类别控制器

@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);

}

我正在使用邮递员来保存数据。问题是在将数据保存到类别和主题表后,我的主题表列 category_id 为空,我无法在它们之间建立关系,我的 sql 结构和数据在保存数据后显示如下

分类表

主题表

category_id 为 NULL 如何设置类别 id 我尝试了很多方法但找不到解决方案。请帮我解决这个问题

【问题讨论】:

    标签: java spring-boot hibernate jpa


    【解决方案1】:

    你在学习spring boot真是太好了!

    回答您的问题,因为答案很简单,您的代码缺少主题中的类别。

    subject.setCategory(category);
    

    现在这可能会导致您出现异常,因此请确保在保留主题之前保存类别。

    干杯!

    【讨论】:

    • 与@thechaoticpanda 之前的工作方式不同
    • 你确定你的类别在你这样做之前已经保存了吗?
    • 啊,这就是您的代码可能无法正常工作的原因,正如我在答案中所说,请先保存类别,然后再将其设置为主题并保存
    • @thechaoticpanda 因为cascade = CascadeType.ALL,他不需要另外保存类别或主题。 Hibernate 足够聪明,可以先保存类别并获取它的 id。
    • @Partho 它应该可以工作。使用此答案中提供的更改扩展您的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 2022-01-20
    相关资源
    最近更新 更多