Establishing relation in mysql entities using spring boot

Viewed 48

I have to establish some relation in my ecomm backend. I was wondering what are the best practice or more so "correct way" to draw up some relationship between different entities

User class:

class User{
  private Long Id;
  ....
  @OneToMany(fetch = fetchType.EAGER)
  List<Order> orders;
}

One user can have multiple orders right?

Order class:

class Order{
  private Long id;
  private Long userId;
  @OneToMany(fetch = fetchType.EAGER)
  List<Product> products;
}

Same here one order can consist of multiple products. But should user id be foreign key considering we are already storing order data in user?

Another relation I created is:

Product class:

class Product{
  private Long id;
  .....
}

Category class:

class Categories{
  private Long id;
  ...
  @OneToMany(fetch = FetchType.EAGER)
  private Collection<Product> products = new ArrayList<>();
}

I have successfully created the product-category relationship, but in my own way:

Repository is simple:

public interface ProductRepository extends JpaRepository<Product, Long> {}

Service and ServiceImp

public interface ProductService {
    Product getProduct(Long productId);
    Product saveProduct(Product product, Long categoryId);
    List<Product> getAllProducts();
    List<Product> getProductsById(List<Long> productIds);
}

and the save product method inside ServiceImp:

@Override
public Product saveProduct(Product product, Long categoryId) {
    log.info("Saving product: {}", product);
    Product newProduct = productRepository.save(product);
    Category category = categoryRepository.findById(categoryId).orElse(null);
    category.getProducts().add(newProduct);
    categoryRepository.save(category);
    return newProduct;
}

Now I have two questions to be exact:

  1. For an app that'll be in production is this a good way to make establish relations?
  2. I've seen people use join column to establish relation along with annotations like OneToMany/ManyToMany. But so far I have not faced any issues whatsoever. So what's the difference?
0 Answers
Related