复合键的Json结构

时间:2018-01-06 03:38:02

标签: json hibernate jpa spring-boot

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

    @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(我使用postman)。我尝试了下面的解决方案和其他可能性,但我遇到了同样的问题: 尝试从null一对一属性中分配id [com.example.entities.BookPublisher.book]

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

非常感谢。

1 个答案:

答案 0 :(得分:0)

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

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