使用JPA更新外键

时间:2019-11-25 08:50:48

标签: spring jpa

我创建了2个实体:

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

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

    @Column(nullable = false)
    private String productKeyId;

    // many to one relationship with category
    @ManyToOne
    @JoinColumn(name = "category_id")
    private CategoryEntity category;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private double price;

    @Column(nullable = false)
    private int qty;

    private String imgPath;

    // getters & setters
}

然后:

@Entity
@Table(name="categories")
public class CategoryEntity {

    @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)
    @JoinColumn(name="parent_id", nullable=true)
    private CategoryEntity parentCategory;

    // allow to delete also subcategories
    @OneToMany(mappedBy="parentCategory", cascade = CascadeType.ALL)
    private List<CategoryEntity> subCategories;

    //Here mappedBy indicates that the owner is in the other side
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "category", cascade = CascadeType.REMOVE)
    private List<ProductEntity> products;
}

我在数据库中生成了数据:

这是我的产品表

enter image description here

和类别表

enter image description here

我的问题如下。我使用REST API更新产品和类别(如果需要)。

{
    "name": "Pizza12",
    "price": 25.0,
    "qty": 15,
    "imgPath": "anotherpathImage",
    "category": {
        "categoryKeyId": "VMz7EM6tNfoOAQtO1SHPYcH14jj0Cy",
        "name": "Fish"
    }
}

在我的服务中,我尝试分别更新两个部分:

@Override
public ProductDto updateProduct(String productKeyId, ProductDto productDto) {
    // create a return object of type Product

    ProductDto returnValue = new ProductDto();

    // create Entity objects to request on the database
    ProductEntity productEntity = productRepository.findByProductKeyId(productKeyId);
    CategoryEntity categoryEntity = categoryRepository.findCategoryEntityByProductKeyId(productKeyId);

    ModelMapper modelMapper = new ModelMapper();

    if (productEntity == null)
        throw new ApplicationServiceException(ErrorMessages.NO_RECORD_FOUND.getErrorMessage());

    productEntity.setProductKeyId(productKeyId);
    productEntity.setName(productDto.getName());
    productEntity.setPrice(productDto.getPrice());
    productEntity.setQty(productDto.getQty());
    productEntity.setImgPath(productDto.getImgPath());

    // update the category
    CategoryEntity updatedCategory = categoryRepository.save(categoryEntity);
    productEntity.setCategory(updatedCategory);

    // productEntity.setCategory(categoryEntity);

    System.out.println("product entity : " + productEntity.toString());

    ProductEntity updatedProduct = productRepository.save(productEntity);

    updatedProduct.setCategory(updatedCategory);

    returnValue = modelMapper.map(updatedProduct, ProductDto.class);

    return returnValue;
}

不幸的是,它似乎没有按预期工作。产品已更新,类别保持不变。

1 个答案:

答案 0 :(得分:0)

由于Janar和Repoker,我终于解决了问题。

@Override
public ProductDto updateProduct(String productKeyId, ProductDto productDto) {
    // create a return object of type Product
    ProductDto returnValue = new ProductDto();

    // create Entity objects to request on the database
    ProductEntity productEntity = productRepository.findByProductKeyId(productKeyId);
    CategoryEntity categoryEntity = categoryRepository.findByCategoryKeyId(productDto.getCategory().getCategoryKeyId());
    //CategoryEntity categoryEntity = categoryRepository.findCategoryEntityByProductKeyId(productKeyId);

    ModelMapper modelMapper = new ModelMapper();

    if (productEntity == null)
        throw new ApplicationServiceException(ErrorMessages.NO_RECORD_FOUND.getErrorMessage());

    productEntity.setProductKeyId(productKeyId);
    productEntity.setName(productDto.getName());
    productEntity.setPrice(productDto.getPrice());
    productEntity.setQty(productDto.getQty());
    productEntity.setImgPath(productDto.getImgPath());

    // update the category
    CategoryEntity updatedCategory = categoryRepository.save(categoryEntity);
    productEntity.setCategory(productEntity.getCategory());

    // productEntity.setCategory(categoryEntity);

    System.out.println("product entity : " + productEntity.toString());

    ProductEntity updatedProduct = productRepository.save(productEntity);

    updatedProduct.setCategory(updatedCategory);

    returnValue = modelMapper.map(updatedProduct, ProductDto.class);

    return returnValue;
}

我没有保留输入的新值,而是最初设置的值...