【问题标题】:Json Structure for compound keys复合键的 Json 结构
【发布时间】:2018-06-15 21:09:16
【问题描述】:

I'm trying to implements this solution: BookPublisher 有一个复合键,所以我构建了可嵌入类:

    @Embeddable
    public class BookPublisherID implements Serializable{

        private int bookID;
        private int publisherID;
//getters and constructor

这是 bookPublisher 类:

@Entity
    @Table(name = "book_publisher")
    public class BookPublisher implements Serializable{

        @EmbeddedId
        private BookPublisherID id;
        private Date publishedDate;

        @MapsId("bookID")
        @ManyToOne
        @JoinColumn(name = "book_id")
        private Book book;
        @MapsId("publisherID")
        @ManyToOne
        @JoinColumn(name = "publisher_id")
        private Publisher publisher;
//getters and setters

这是图书课:

 @Entity
    public class Book{
        private int id;
        private String name;
    @OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
        private Set<BookPublisher> bookPublishers;
 //getters and setters

发布者类:

    @Entity
        public class Publisher{
            private int id;
            private String name;
        @OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
            private Set<BookPublisher> bookPublishers;
 //getters and setters

BookPublisher 存储库:

public interface BookPublisherRepository extends JpaRepository<BookPublisher, BookPublisherID>{}

这是实现:

@Service
public class BookPublisherImpl implements BookPublisherMetier{


    @Autowired
    private BookPublisherRepository bookPublisherRepository;

    @Override
    public BookPublisher savePublication(BookPublisher bookPublisher) {
                bookPublisher.setPublishedDate(new Date());
        return bookPublisherRepository.save(bookPublisher);
    }

}

问题是在复合键的情况下如何在 Json 中添加 bookPublisher(我与邮递员合作)。我尝试了下面的解决方案和其他可能性,但我遇到了同样的问题: 试图从空的一对一属性 [com.example.entities.BookPublisher.book] 分配 id

{  
        "id": {
            "bookID":1,
            "publisherID":1
        },
        "book":{
            "id":1
        },
        "publisher":{
            "id":1
      } 
}

非常感谢。

【问题讨论】:

    标签: json hibernate jpa spring-boot


    【解决方案1】:

    我在这里看到了几个关键项目。

    1. 如果您对对象所做的只是基本的 getter 和 setter,那么您应该只使用默认属性而不是定义私有字段。我发现即使不必自己实现可序列化,它也会始终序列化。此外,请注意私有变量不会序列化,因为它们不可访问。
    2. 您需要使用自定义持有者对象,而不是使用实体对象。您需要为关系选择一个基础对象和方向。实体对象包含与您来自的相关对象的关系,从而产生无法序列化的循环引用。它会在他们之间无限传播。您需要使用不这样做的对象结构。

    【讨论】:

    • 谢谢 Verito,但我很抱歉我没听懂你的意思!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    相关资源
    最近更新 更多