¿Создать функцию продукта? В JPA Hibernate Spring-boot с внешним ключом - PullRequest
0 голосов
/ 02 мая 2018

У меня есть эти объекты:

Продукт

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

    private static final long serialVersionUID = -7412065294436325640L;

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

    @NotNull
    @Size(max = 250)
    private String name;

    @NotNull
    private String price;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "categoryId", referencedColumnName = "supermarketId", insertable = false, updatable = false)
    @JsonIgnore
    private Category category;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "supermarketId", referencedColumnName = "supermarketId", insertable = false, updatable = false)
    @JsonIgnore
    private Supermarket supermarket;

    @NotNull
    @Size(max = 250)
    private String about;

    // Getters and Setters
}

Категория

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

    private static final long serialVersionUID = 3730363675931805709L;

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

    @NotNull
    @Size(max = 250)
    private String name;

    // Getters and Setters
}

Супермаркет

@Entity
@Table(name = "supermarket")
public class Supermarket extends AuditModel {

    private static final long serialVersionUID = -1693473118599875940L;

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

    @NotNull
    @Size(max = 250)
    private String name;

    // Getters and Setters
}

И я не знаю, с моим Контроллером все в порядке или нет, и в функции Создать, как можно настроить супермаркет, связанный с моим продуктом? Это мой контроллер:

ProductController

@RestController
@RequestMapping("/api")
public class ProductController {

    @Autowired
    ProductRepository productRepository;

    @Autowired
    CategoryRepository categoryRepository;

    @Autowired
    SupermarketRepository supermarketRepository;

    @GetMapping("/productes")
    public Page<Product> getAllProducts(Pageable pageable) {
        return productRepository.findAll(pageable);
    }

    @PostMapping("/productes")
    public Product createProduct(@PathVariable (value = "categoryId") Long categoryId,
            @PathVariable (value = "supermarketId") Long supermarketId, @Valid @RequestBody Product product) {
        return categoryRepository.findById(categoryId).map(category -> {
            product.setCategory(category);
  // SUPERMARKET SET ??? <<------
            return productRepository.save(product);
        }).orElseThrow(() -> new ResourceNotFoundException("Category id: " + categoryId + " not found"));
    }

    @GetMapping("/productes/{productId}")
    public Product getProductById(@PathVariable Long productId, @Valid @RequestBody Product productRequest) {
        return productRepository.findById(productId)
                .orElseThrow(() -> new ResourceNotFoundException("Product id: " + productId + " not found"));
    }

    @PutMapping("/productes/{productId}")
    public Product updateProduct(@PathVariable (value = "categoryId") Long categoryId,
            @PathVariable (value = "supermarketId") Long supermarketId,
            @PathVariable (value = "productId") Long productId, @Valid @RequestBody Product productRequest) {
        if(!categoryRepository.existsById(categoryId)) {
            throw new ResourceNotFoundException("Category id " + categoryId + " not found");
        }

        if(!supermarketRepository.existsById(supermarketId)) {
            throw new ResourceNotFoundException("Supermarket id " + supermarketId + " not found");
        }

        return productRepository.findById(productId).map(product -> {
            product.setCategory(categoryRepository.findById(categoryId)
                    .orElseThrow(() -> new ResourceNotFoundException("Category id: " + categoryId + " not found")));
            product.setSupermarket(supermarketRepository.findById(supermarketId)
                    .orElseThrow(() -> new ResourceNotFoundException("Supermarket id: " + supermarketId + " not found")));
            product.setName(productRequest.getName());
            product.setPrice(productRequest.getPrice());
            return productRepository.save(product);
        }).orElseThrow(() -> new ResourceNotFoundException("Product id: " + productId + "not found"));
    }

    @DeleteMapping("/productes/{productId}")
    public ResponseEntity<?> deleteProduct(@PathVariable (value = "categoryId") Long categoryId,
            @PathVariable (value = "supermarketId") Long supermarketId, @PathVariable (value = "productId") Long productId) {
        if(!categoryRepository.existsById(categoryId)) {
            throw new ResourceNotFoundException("Category id " + categoryId + " not found");
        }

        if(!supermarketRepository.existsById(supermarketId)) {
            throw new ResourceNotFoundException("Supermarket id " + supermarketId + " not found");
        }

        return productRepository.findById(productId).map(product -> {
            productRepository.delete(product);
             return ResponseEntity.ok().build();
        }).orElseThrow(() -> new ResourceNotFoundException("Product id: " + productId + " not found"));
    }
}

Это мой репозиторий для продуктов:

ProductRepository

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
    Page<Product> findByCategoryId(Long categoryId, Pageable pageable);
    Page<Product> findBySupermarketIdd(Long supermarketId, Pageable pageable);
}

Не могли бы вы сказать мне, если мой контроллер в порядке, и как можно завершить функцию создания? Заранее спасибо!

1 Ответ

0 голосов
/ 02 мая 2018

Попробуйте с этим кодом:

    @PostMapping("/productes")
    public Product createProduct(@PathVariable(value = "categoryId") Long categoryId,
            @PathVariable(value = "supermarketId") Long supermarketId, @Valid @RequestBody Product product) {
        product.setCategory(categoryRepository.findById(categoryId)
                .orElseThrow(() -> new ResourceNotFoundException("Category not found with id " + categoryId)));
        product.setSupermarket(supermarketRepository.findById(supermarketId)
                .orElseThrow(() -> new ResourceNotFoundException("Supermarket not found with id " + supermarketId)));
        return productRepository.save(product);
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...