在Spring Data中映射OneToMany递归关系

时间:2018-07-15 18:36:15

标签: java spring hibernate h2

我想使用Spring Data映射类别和子类别之间的递归关系。我有以下代码:

Boolean upScrolling;  
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            LinearLayoutManager mgr = (LinearLayoutManager) recyclerView.getLayoutManager();
            int topPosition = mgr.findFirstVisibleItemPosition();

            /// your code

        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
                    if (dy < 0) {
                        upScrolling = true;
                    } else if (dy > 0) {
                        upScrolling = false;
                    } 
        }
    });

}

出于测试目的,我在扩展JpaRepository的存储库中创建了一个命名查询:

@Entity
public class Category {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @Column(nullable=false)
    private String name;

    @ManyToOne(cascade={CascadeType.ALL})
    @JoinColumn(name="parent_id")
    private Category parentId;

    @OneToMany(mappedBy="parentId", cascade=CascadeType.ALL)
    private Set<Category>subcategories = new HashSet<Category>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Category getParentId() {
        return parentId;
    }

    public void setParentId(Category parentId) {
        this.parentId = parentId;
    }

    public Set<Category> getSubcategories() {
        return subcategories;
    }

    public void setSubcategories(Set<Category> subcategories) {
        this.subcategories = subcategories;
    }

我有一个spring boot端点,该端点调用一个服务,在该服务中我自动连接了我的存储库。调用时,发生以下错误:

  

org.springframework.dao.InvalidDataAccessResourceUsageException:无法执行查询; SQL [从类别中选择category.id,category.name];嵌套的异常是org.hibernate.exception.SQLGrammarException:无法执行查询

     

原因:org.h2.jdbc.JdbcSQLException:找不到列“ parent_id” [42122-197]

sql表如下:

    @Query(value="select category.id, category.name from category ", nativeQuery=true)
    List<Category> test();

如何映射递归关系?

0 个答案:

没有答案