代码之家  ›  专栏  ›  技术社区  ›  davidvera

springboot/JPA:设置并持久化父id

  •  0
  • davidvera  · 技术社区  · 6 年前

    package com.app.ws.io.entity;
    
    import lombok.AccessLevel;
    import lombok.Getter;
    import lombok.Setter;
    
    import javax.persistence.*;
    import java.util.List;
    
    @Entity
    @Table(name="categories")
    @Getter @Setter
    public class CategoryEntity {
        @Getter(AccessLevel.NONE)
        @Setter(AccessLevel.NONE)
        private static final long serialVersionUID = 1L;
    
        @Id
        @GeneratedValue(strategy= GenerationType.IDENTITY)
        private Long id;
    
        @Column(length = 30, nullable = false)
        private String categoryKeyId;
    
        @Column(nullable = false)
        private String name;
    
        @ManyToOne(optional = true, fetch = FetchType.LAZY)
        private CategoryEntity parentCategory;
    
        // allow to delete also subcategories
        @OneToMany(mappedBy="parentCategory", cascade = CascadeType.ALL)
        private List<CategoryEntity> subCategories;
    
    }
    

    生成的表包含所需的4个字段。parent_id字段是指数据库的现有id。

    我使用restapi来保存数据,为此我创建了一个请求和响应模型

    我发送的JSON使用此模型:

    @Getter @Setter
    public class CategoryRequestModel {
        private String name;
        private String parentCategoryKeyId;
    }
    

    作为回报,我使用第二个模型:

    @Getter @Setter
    public class CategoryRest {
        private String categoryKeyId;
        private String name;
    }
    

    我的控制器中有一个方法:

    @PostMapping(
            consumes = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE },
            produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }
    )
    public CategoryRest createCategory(@RequestBody CategoryRequestModel categoryRequestModel) throws Exception {
        CategoryRest returnValue = new CategoryRest();
    
        if( categoryRequestModel.getName().isEmpty())
            throw new NullPointerException(ErrorMessages.MISSING_REQUIRED_FIELDS.getErrorMessage());
    
        ModelMapper modelMapper = new ModelMapper();
        CategoryDto categoryDto = modelMapper.map(categoryRequestModel, CategoryDto.class);
    
        CategoryDto createdCategory = categoryService.createCategory(categoryDto);
        System.out.println(createdCategory);
        returnValue = modelMapper.map(createdCategory, CategoryRest.class);
    
        return returnValue;
    }
    

    @Getter @Setter
    public class CategoryDto implements Serializable {
        @Getter(AccessLevel.NONE)
        @Setter(AccessLevel.NONE)
        private static final long serialVersionUID = 1L;
    
        private long id;
        private Integer parentCategoryId;
        private String name;
        private String categoryKeyId;
        private String parentCategoryKeyId;
    
        private List<CategoryDto> subCategories;
        private CategoryDto parentCategory;
    
    }
    

    我的服务:

    @Override
    public CategoryDto createCategory(CategoryDto categoryDto) {
        // check if category exists
        if (categoryRepository.findByName(categoryDto.getName()) != null)
            throw new ApplicationServiceException("Record already in Database");
    
        ModelMapper modelMapper = new ModelMapper();
        CategoryEntity categoryEntity = modelMapper.map(categoryDto, CategoryEntity.class);
    
        // generate categoryKeyId
        String categoryKeyId = utils.generateCategoryKeyId(30);
        categoryEntity.setCategoryKeyId(categoryKeyId);
        System.out.println(categoryDto);
        System.out.println("# " + categoryDto.getCategoryKeyId());
        // int can't be null - Integer is nullable
        if (categoryDto.getParentCategoryId() != null) {
            CategoryEntity parentCategory = categoryRepository.findByCategoryKeyId(categoryDto.getCategoryKeyId());
            categoryEntity.setParentCategory(parentCategory);
            System.out.println(categoryEntity);
        }
    
        CategoryEntity storedCategory = categoryRepository.save(categoryEntity);
        CategoryDto returnValue = modelMapper.map(storedCategory, CategoryDto.class);
    
        return returnValue;
    }
    

    我的问题是,我可以保存一个类别,但我无法在数据库中设置父类别。 如果我用这个Json发送post请求:

    {
      "name": "sub",
      "parentCategoryId": "6jWswxKNADi9iDPNvs00r7mCd0BxH0"
    }
    

    0 回复  |  直到 6 年前