2015-11-05 61 views
5

目前我正在为Spring Data Rest进行POC工作。尝试获取可用的JSONout的存储库。春季数据休息(SDR)错误?持久性实体不能为空

我有一个实体类(NewTask)

@Entity 
@Table(name="newtable") 
public class NewTask { 

    @Id 
    @Column(name="newid") 
    private int id; 


    @Column(name="newage") 
    private int age; 

    @Column(name="newaddress") 
    private String address; 



    public String getAddress() { 
     return address; 
    } 
    public void setAddress(String address) { 
     this.address = address; 
    } 
    public int getId() { 
     return id; 
    } 
    public void setId(int id) { 
     this.id = id; 
    } 
    public int getAge() { 
     return age; 
    } 
    public void setAge(int age) { 
     this.age = age; 
    } 

} 

和相应的库..

@RepositoryRestResource 
    @PreAuthorize("hasRole('ROLE_ADMIN')") 
    public interface NewTaskRepository extends CrudRepository<NewTask, Serializable>{ 


     @Query("SELECT t.address FROM NewTask t where t.id = :id") 
     String findByMyId(@Param("id") int id); 

     }   

每当我打

http://localhost:8080/POCDB/newTasks/search/findByMyId?id=1 

我得到以下错误: { “cause”:null,“message”:“PersistentEntity不能为空!”}

现在,这里是我的仓库的外观:请阅读注释上的每个方法

//Gives- PersistentEntity must not be null!!! 
    @Query("SELECT t.address FROM NewTask t where t.id = :id") 
    String findByMyId(@Param("id") int id); 


    //WORKS FINE 
    @Query("SELECT t.id FROM NewTask t where t.id = :id") 
    int findId(@Param("id") int id); 


    //WORKS FINE 
    @Query("SELECT t.id FROM NewTask t where t.id = :id") 
    Integer findIdTwo(@Param("id") int id); 

    //Gives- PersistentEntity must not be null!!! 
    @Query("SELECT t.id FROM NewTask t") 
    List<Integer> findIds(); 

我不知道什么是有回报types.I以下简称一些解决方案的链接的问题:

How does one create a custom query in jparepository but return an object other than the entity?

,并添加2种方法,我的仓库,这不适合我

// returns in some weird format 
    @Query("SELECT t.address FROM NewTask t where t.id = :id") 
    PString findByMyId(@Param("id") int id); 

    //Gives- PersistentEntity must not be null!!! 
    @Query("SELECT t.address FROM NewTask t") 
    List<PString> findAddress(); 
工作0

我有预感,这是SDR中的错误,还是我错过了什么?

+0

重复的问题。 http://stackoverflow.com/a/30403914/621686 – bvulaj

+0

嗨布兰登, 您发布的答案不适用于我的情况。 此外,这不是一个继承问题,没有基类,但错误消息是相同的。 如果您有任何想法,您可以帮助解决方案吗?或者你可以介绍一个谁可以? –

回答

6

Spring Data REST只能返回存储库注册的数据。在您引用的另一个问题中,您会注意到他们专门为他们需要的类型创建了一个定制存储库。这不是SDR中的一个错误,它只是它的功能。它也保持了RESTful。

所以在你的情况下,SDR只能返回NewTask或NewTask的集合。

+1

是的,我想到了这一点,但正如你在上面的问题中看到的那样,为什么当我返回一个Integer时不会抛出同样的错误? –

+0

当我返回一个实体的枚举属性时,我遇到了一个非常类似的问题:'@Query(“从交易中选择d.status作为d,其中d.id =:id”) Deal.Status findStatusById(@Param(“id” )长ID);'我明白,spring-data-rest不应该返回任何资源,但为什么int可以吗?另一方面,如果我想排除这个查询被暴露给spring-data-rest,那么这将如何实现呢? – Gregor

+0

int是可接受的,因为它被假定为资源的id(int字段上的@Id注释)。 – afaulconbridge

0

在Spring Boot中,如果Spring主应用程序未能扫描您的域(POJO)类,那么除非您将所有类放在同一个包中,否则将抛出此错误。然后,您在Spring主应用程序类别顶部添加组件扫描注释

@ComponentScan(basePackages = "com.aaa.bbbb.ccccc")