【问题标题】:Spring Boot repository does not persist one-to-many relationSpring Boot 存储库不保留一对多关系
【发布时间】:2017-03-25 19:55:51
【问题描述】:

我有一个带有 JPA 和 H2 的 Spring Boot 应用程序,其中包含两个实体:

@Entity
@Table(name = "people")
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "person_id")
    private long id;

    private String name;

    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
    private Set<Skill> skills = new HashSet<Skill>();
}

@Entity
@Table(name = "skills")
public class Skill {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "skill_id")
    private long id;

    private String name;

    @ManyToOne
    @JoinColumn (name="person_id")
    @JsonBackReference
    private Person person;
}

我有个人实体的 JPA 存储库:

@Repository
public interface PersonRepository extends CrudRepository<Person, Long> {
}

当我尝试保存以下对象时,它会立即返回包含技能的正确实体,但是当我调用repository.find(&lt;id-of-saved-entity&gt;) 时,技能是空的(因此它们没有被持久化):

{ "name": "Test", "skills": [ { "name": "Skill1" }, { "name": "Skill2"} ] }

有人可以帮我看看我的映射和配置有什么问题吗?

【问题讨论】:

  • 如果你做 person.getSkills().size().. 集合加载了吗?
  • @Smajl 你试过@ElementCollection
  • skills 是否保存在数据库中?
  • 您指定列名是否有原因?
  • @javaguy 不,他们没有。如果我尝试访问person.getSkills(),它会说集合是空的。

标签: java hibernate spring-boot spring-repositories


【解决方案1】:

这里是 spring data REST (HATEOAS) 存储库的答案。他们说,您必须向包含 [父] 资源 URI 的关联资源发送 PUT 请求

curl -i -X PUT -H "Content-Type:text/uri-list" -d "http://localhost:8080/libraries/1" http://localhost:8080/books/1/library

http://www.baeldung.com/spring-data-rest-relationships

希望链接对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-13
    • 2020-08-02
    • 2020-11-28
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    相关资源
    最近更新 更多