Spring Boot为相关实体获取空_embedded数组

时间:2018-01-22 13:42:38

标签: spring hibernate spring-hateoas

使用Spring Boot I' m具有以下实体的缩写结构:

@Entity
@Table(name = "item")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Item implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", updatable = false)
    protected Long id;
...
}
@Entity
@Table(name = "book")
public class Book extends Item implements Serializable {
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "item_author", joinColumns = @JoinColumn(name = "item_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "author_id", referencedColumnName = "id"))
    private Set<Author> authors;
}
@Entity
@Table(name = "author")
public class Author implements Serializable {
    @Id
    @GeneratedValue
    private Long id;

    @ManyToMany(mappedBy="authors")
    private List<Book> books = new ArrayList<Book>();

    private String name;
}

我的DAO只是简单的RestResource接口,适用于所有实体,例如:

@RestResource(path="items", rel="items")
  public interface ItemDao extends CrudRepository<Item, Long> {
}

当我通过id查询实体时,它是好的

GET > http://localhost:8080/shelfventory/authors/1
{
  "name" : "Jhonny Cash",
  "used" : true,
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/shelfventory/authors/1"
    },
    "author" : {
      "href" : "http://localhost:8080/shelfventory/authors/1"
    },
    "books" : {
      "href" : "http://localhost:8080/shelfventory/authors/1/books"
    }
  }
}

但是当我尝试按照相关对象的链接时,我只是得到一个空的嵌入式:

GET > http://localhost:8080/shelfventory/authors/1/books
{
  "_embedded" : {
    "books" : [ ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/shelfventory/authors/1/books"
    }
  }
}

我做错了什么,怎么解决?

1 个答案:

答案 0 :(得分:0)

考虑将这两个属性添加到application.properties以保持@Entity和架构同步:

spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=true