测试休眠OneToMany映射

时间:2020-03-25 11:11:26

标签: java json spring hibernate spring-boot

我正在使用JUnit 4.12在Spring Boot 2.1.4项目上运行完整性测试,当我使用@OneToOne-@ManyToOne类型的双向关系时,在运行保存(注释)端点测试时遇到了问题@JsonManagedReference和@JsonBackReference注释可避免递归。

问题是,当我运行测试时,它没有将关系的父级(Author类)转换为JSON,仅子级(Comment类)被转换,而没有对父级的引用。

已收到注释类的对象,将其转换为JSON enter image description here

将Comment类的对象转换为JSON的结果,父级在哪里? enter image description here

H2数据库中表的DDL

CREATE TABLE IF NOT EXISTS `author` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(255) NOT NULL,
  `created` TIMESTAMP NULL,
  `modified` TIMESTAMP NULL,
  PRIMARY KEY (`id`)
) ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `comment` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `review` VARCHAR(255) NOT NULL,
  `author_id` INT NOT NULL,
  `created` TIMESTAMP NULL,
  `modified` TIMESTAMP NULL,
  PRIMARY KEY (`id`),
  INDEX `fk_comment_author_idx` (`author_id` ASC),
  CONSTRAINT `fk_comment_author` FOREIGN KEY (`author_id`) REFERENCES `author` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE = InnoDB;

父实体

@JsonManagedReference("author_comment")
@OneToMany(mappedBy = "author", cascade = {CascadeType.ALL}, orphanRemoval = true)
private List<Comment> comments = new ArrayList<>();

子实体

@JsonBackReference("author_comment")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "author_id")
private Author author;

0 个答案:

没有答案