JPA不会将关联对象保存在@RequestBody注释获得的对象中

时间:2019-05-14 05:13:01

标签: java spring-data-jpa thymeleaf

以下是Developer实体。

  • Developer
@Entity
@Getter
@Setter
public class Developer {
    @Id
    @GeneratedValue
    @Column(name="DEVELOPER_ID")
    private Long id;

    private String nickname;
    private String name;
    private String imageURI;

    @OneToMany(mappedBy = "developer", cascade={CascadeType.PERSIST})
    private List<Article> articleList = new ArrayList<>();

    public void addArticle(Article article) {
        this.articleList.add(article);

        if ( article.getDeveloper() != this )
            article.setDeveloper(this);
    }

}

其次是Article实体。

  • Article
@Entity
@Getter
@Setter
public class Article {
    @Id
    @GeneratedValue
    @Column(name="ARTICLE_ID")
    private Long id;

    private String subject;

    @ElementCollection
    private List<String> contents = new ArrayList<>();

    public void addContent(String content) {
        this.contents.add(content);
    }

    @ManyToOne
    @JoinColumn(name="DEVELOPER_ID")
    private Developer developer;

    public void setDeveloper(Developer developer) {
        this.developer = developer;

        if ( !developer.getArticleList().contains(this) )
            developer.getArticleList().add(this);
    }

}

通过ajax查看对RestController(/ about / developers / rest / add)的请求。 接下来是请求正文的json。

  • 请求正文json
    [
    {"articleList":[
        {"contents":["article line","article line"],
        "subject":"article subject"},
        {"contents":["article line","article line","article line"],
        "subject":"article subject"}
     ],
    "nickname":"dev nickname",
    "name":"(dev name)",
    "imageURI":"default.png"
    },

    {"articleList":[
        {"contents":["article line","article line"],
        "subject":"article subject"},
        {"contents":["article line"],
        "subject":"article subject"}
     ],
    "nickname":"dev nickname",
    "name":"(dev name)",
    "imageURI":"default.png"}
    ]

包括@RequestBody

的RestController
  • RestController
@RestController
@RequestMapping("/about")
public class AboutRestController {

    @Autowired
    private DeveloperService developerService;

    @PostMapping("/developers/rest/add")
    public void developersRegisterAPI(@RequestBody List<Developer> developerList) {

        /** Not Working **/
        // Saving Developer only (except Associated Articles)
        for (Developer developer : developerList) {
            developerService.save(developer);
        }


        /** Working **/
        // Saving Developers and Associated Articles
        for (Developer developer : developerList) {

            Developer newDeveloper = new Developer();
            newDeveloper.setName(developer.getName());
            newDeveloper.setImageURI(developer.getImageURI());
            newDeveloper.setNickname(developer.getNickname());

            for (Article article : developer.getArticleList()) {

                Article newArticle = new Article();
                newArticle.setSubject(article.getSubject());
                newArticle.setContents(article.getContents());
                newDeveloper.addArticle(newArticle);

            }

            developerService.save(newDeveloper);
        }
    }

}

当我打印@RequestBody List<Developer> developerList时,每个Developer对象都有关联的Article对象。

在第一种情况下(developerService.save(developer);无法正常工作),developerService.findAll()的结果仅包含Developer个对象。检索到的Article对象中没有Developer个对象。

在第二种情况下(developerService.save(newDeveloper);正常工作),developerService.findAll()的结果同时包含Developer个对象和关联的Article个对象。

实际上,这两种情况都在RestController的方法中保存了关联的Article。 但是在Web控制器的方法中,当我使用developerService.findAll()时,没有文章。因此,如果我通过Developer传递了检索到的Model对象,则没有关联的Article,并且视图无法打印这些对象。

以下是DeveloperService

  • DeveloperServiceDeveloperRepository
@Service
public class DeveloperService {
    @Autowired
    DeveloperRepository developerRepository;

    public void save(Developer developer) {
        developerRepository.save(developer);
    }

    public void delete(Developer developer) {
        developerRepository.delete(developer);
    }

    public List<Developer> findAll() {
        return developerRepository.findAll();
    }
}
@Repository
@Transactional
public interface DeveloperRepository extends JpaRepository<Developer, Long> {
}

以下是ARTICLE中的h2-console

ARTICLE Table in h2-console (click me for image)

如您所见,DEVELOPER_ID为空。

我只能使用

修复此问题吗
        for (Developer developer : developerList) {
            developerService.save(developer);
        }

1 个答案:

答案 0 :(得分:1)

first将不起作用,因为json中的Articles列表中未绑定Developer Object。第二种情况由于该行而起作用

    newDeveloper.addArticle(newArticle);
要添加的

        如果(article.getDeveloper()!= this)             article.setDeveloper(this); 尝试在第一个循环中将开发人员对象绑定到您的文章列表中,您的代码将起作用。我的意思是尝试将开发人员对象绑定到列表中的每个文章对象中