Связь с другой таблицей не реализуется. OneToOne

Рейтинг: 0Ответов: 1Опубликовано: 14.06.2023

Проблема в том, что объект size не добавлен в список products и соответственно не выводится thymeleaf. То есть, двусторонняя связь не работает. Подскажите, пожалуйста, что можно исправить.

@Entity
@Getter
@Setter
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @Column
    private String name;
    @Column
    private String img;
    @Column
    private String color;
    @Column
    private int price;
    @Column
    private int quantity;

    @Column
    @Version
    private int in_stock;


    public Product() {
    }

    public Product(int id, String name, int price, int quantity, String img, String color, int in_stock) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.quantity = quantity;
        this.img = img;
        this.color = color;
        this.in_stock = in_stock;
    }
}
@Entity
@Getter
@Setter
public class Sizes {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "product_id")
    private int id;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    @JoinColumn(name = "product_id")
    private Product product;

    @Column
    private String size;
@GetMapping("/scarf")
    public String scarf(Model model) {
        Optional<Product> products = productRepository.findById(1);
        ArrayList<Product> res = new ArrayList<>();
        products.ifPresent(res::add);
        model.addAttribute("products", res);
        return "scarf";
    }

Ответы

▲ 1Принят

Если используется MapsId в классе Sizes, то не нужно использовать генератор для идентификатора, он должен браться из класса Product.

// class Sizes 
@Id
@Column(name = "product_id")
private int id;

@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JoinColumn(name = "product_id")
private Product product;

Но в случае такой односторонней связи информация о размерах при обращении к товарам не будет доступна, и придётся вычитывать объекты Sizes, а уже через них доступаться к Product.