如何在Springboot中创建一对多关系

时间:2018-11-15 09:46:56

标签: java postgresql hibernate spring-boot

我正在尝试为用户创建一个api,使其能够将产品添加到特定类别,以便在调用id的getCategory时产生如下结果:

 {
  "product": [
   {
       "productId": 1,
       "productName": "TestProdut1"
   },{
       "productId": 2,
       "productName": "TestProdut2"
   }
  ],
  "categoryId": 1,
  "categoryName": "Test1",
  "parentCategoryId": 123
}
  

请注意,我正在使用 postgres数据库

     

这是我到目前为止所做的,但是当我尝试在那里找到一个类别时   没有回音。当使用摇摇欲坠时,响应返回为否   内容

类别实体:

@Entity
@Table(name = "category")
public class Category {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "category_id", unique = true, nullable = false)
    private Long id;

    @Column(nullable = false)
    private String categoryName;

    @JsonIgnore
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "categories", cascade = CascadeType.REMOVE, orphanRemoval = true)
    private List<Product> products = new ArrayList<Product>();

    @ManyToOne
    @JoinColumn(name = "parent_id")
    @JsonIgnore
    private Category parentId;

    @OneToMany(mappedBy = "parentId")
    private List<Category> subCategories = new ArrayList<>();

}

产品实体:

@Entity
@Table(name = "products")
public class Product {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "product_id")
    private Long id;

    private String name;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "category_id")
    private Category categories;

}

类别存储库:

public interface CategoryRepository extends CrudRepository<Category, Long>{
    public List<Category> findByCategoryName(String categoryName);
}

类别服务:

@Service
public class CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    public void addCategory(Category category) {
        categoryRepository.save(category);
    }

    public List<Category> getAllCategories() {
        List<Category> categoryList = new ArrayList<>();
        categoryRepository.findAll().forEach(categoryList::add);
        return categoryList;
    }

    public List<Category> getAllCategoriesByName(String categoryName) {
        List<Category> categoryList = new ArrayList<>();
        categoryList = categoryRepository.findByCategoryName(categoryName);
        return categoryList;
    }

    public Optional<Category> getCategoryById(Long categoryId) {
        Optional<Category> category = categoryRepository.findById(categoryId);
        return category;
    }

    public void deleteCategory(Long id) {
        categoryRepository.deleteById(id);
    }
}

类别控制器:

@RestController
@Api(value = "CategoryAPI", produces = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping("/ss")
public class CategoryController {
        @Autowired
    private CategoryService categoryService;

    @RequestMapping(method=RequestMethod.POST , value="/category/add", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Boolean> addCategory(@RequestBody Category category) {
        categoryService.addCategory(category);
        return new ResponseEntity<Boolean>(true, HttpStatus.CREATED);
    }

        @RequestMapping(method= RequestMethod.GET, value="/category/get/by/id/{categoryId}")
    public void getCategoryById(@PathVariable Long categoryId) {
        categoryService.getCategoryById(categoryId);
    }

        @RequestMapping(method= RequestMethod.GET, value="/category/get/by/name/{categoryName}")
    public void getCategoryByName(@PathVariable String categoryName) {
        categoryService.getAllCategoriesByName(categoryName);
    }

        @RequestMapping(method= RequestMethod.GET, value="/all/category")
    public void getCategories() {
        categoryService.getAllCategories();
    }
}

1 个答案:

答案 0 :(得分:2)

这是因为检索类别列表时返回类型无效,这就是为什么您没有得到任何答复的原因。

 @RequestMapping(method= RequestMethod.GET, value="/category/get/by/name/{categoryName}")
public ResponseEntity<List<Category>> getCategoryByName(@PathVariable String categoryName) {
    return new ResponseEntity<>(categoryService.getAllCategoriesByName(categoryName),HttpStatus.OK);
}