Spring boot / JPA: установить и сохранить родительский идентификатор - PullRequest
0 голосов
/ 28 октября 2019

Я создал сущность с именем категории.

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 = 1 name = "mainCategory" parent_id = null id = 2 name = "subCategory" parent_id = 1

Я использую API остальных, чтобы сохранить данные для этого. Я создал запрос и ответ. модель

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;
}

Я называю здесь слой DTO со слоем обслуживания:

@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:

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

, я сохраняю значение «sub» в базе данных, но вообще не получаю parent_id.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...