У меня есть база данных и 3 таблицы: ProductEntity, OrderEntity и ProductInOrder
@Entity
public class ProductEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private long price;
@OneToMany(mappedBy = "productEntity")
private List<ProductInOrder> productInOrder;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public List<ProductInOrder> getProductInOrder() {
return productInOrder;
}
public void setProductInOrder(List<ProductInOrder> productInOrder) {
this.productInOrder = productInOrder;
}
@Entity
public class OrderEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@OneToMany(mappedBy="orderEntity")
private List<ProductInOrder> productInOrder;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public List<ProductInOrder> getProductInOrder() {
return productInOrder;
}
public void setProductInOrder(List<ProductInOrder> productInOrder) {
this.productInOrder = productInOrder;
}
}
@Entity
public class ProductInOrder {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@ManyToOne
private OrderEntity orderEntity;
@ManyToOne
private ProductEntity productEntity;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public OrderEntity getOrderEntity() {
return orderEntity;
}
public void setOrderEntity(OrderEntity orderEntity) {
this.orderEntity = orderEntity;
}
public ProductEntity getProductEntity() {
return productEntity;
}
public void setProductEntity(ProductEntity productEntity) {
this.productEntity = productEntity;
}
}
И собственно вопрос. Как с помощью hibernate мне отобразить в базе данных, что у одного заказа может быть несколько товаров. Как это отобразить в базе данных для сущности ProductInOrder? В ней хранится только id той той сущности, которая была последней добавлена через persist.
Я хочу понять, как лучше сделать. Что бы в поле productentity_id хранились id всех товаров, которые я добавил в так называемую корзину или что бы для каждого товара была отдельная строка в таблице ProductInOrder? А вот метод в ejb, которым я пытаюсь добавить товары в заказ:
public void createOrder(List<Product> list) {
OrderEntity orderEntity = new OrderEntity();
entityManager.persist(orderEntity);
ProductInOrder productInOrder = new ProductInOrder();
productInOrder.setOrderEntity(orderEntity);
for (int i = 0; i < list.size(); i++) {
ProductEntity productEntity = entityManager.find(ProductEntity.class, list.get(i).getId());
if (productEntity == null) {
continue;
}
productInOrder.setProductEntity(productEntity);
}
entityManager.persist(productInOrder);
}
Я недавно начал изучать javaee и пытаюсь разобраться.
Вот решение вашей задачи:
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(nullable = false, length = 100)
private String name;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "orders_products",
joinColumns = {@JoinColumn(name = "id_order")},
inverseJoinColumns = {@JoinColumn(name = "id_product")}
)
private Set<Product> products = new HashSet<>();
public Order() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Product> getProducts() {
return products;
}
public void setProducts(Set<Product> products) {
this.products = products;
}
public void addProduct(Product product) {
products.add(product);
product.getOrders().add(this);
}
public void removeProduct(Product product) {
products.add(product);
product.getOrders().add(this);
}
}
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(nullable = false, length = 100)
private String name;
@ManyToMany(mappedBy = "products", fetch = FetchType.EAGER)
private Set<Order> orders = new HashSet<>();
public Product() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
}
@Repository
public interface OrderRepository extends CrudRepository<Order, Integer> {
}
@Repository
public interface ProductRepository extends CrudRepository<Product, Integer> {
}
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
private OrderRepository orderRepository;
@Autowired
private ProductRepository productRepository;
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@Override
public void run(String... args) throws Exception {
Product product1 = new Product();
product1.setName("product1");
product1 = productRepository.save(product1);
Order order1 = new Order();
order1.setName("order1");
order1.addProduct(product1);
orderRepository.save(order1);
System.out.println(orderRepository.findAll());
System.out.println(productRepository.findAll());
}
}
Кофе для программистов: как напиток влияет на продуктивность кодеров?
Рекламные вывески: как привлечь внимание и увеличить продажи
Стратегії та тренди в SMM - Технології, що формують майбутнє сьогодні
Выделенный сервер, что это, для чего нужен и какие характеристики важны?
Друзья, здравствуйте, Подскажите как настроить вproperties log4j путь к логам внутри проекта? То есть что бы после пула с гита путь был всегда октуален
Я использую библиотеку JMusic для редактора MIDI (и AU) файлов:http://explodingartcom/jmusic/index
Как исправить ошибку? До этого была ошибка "Setup SDK", вроде разобрался, а теперь вот это: