Spring Boot - Hibernate - OneToMany - foreign key

隐身守侯 提交于 2021-01-29 07:34:15

问题


I would like to ask a theoretical question. So let's assume I'm using spring boot and hibernate and I would like to persist the following data structure.

@Entity
@Table(name = "shoppingbasket")
@NoArgsConstructor
@AllArgsConstructor
public class ShoppingBasket {

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

    @Getter
    @Setter
    @Column(name = "userId", unique = true)
    private String userId;

    @Getter
    @Setter
    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<Product> products;

and

@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "product")
public class Product {

    @Getter
    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Getter
    @Setter
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "shoppig_basket_id")
    private ShoppingBasket shoppigBasket;

The data is coming from a ResController:

    @PostMapping(value = "add")
    @ResponseBody
    public ResponseEntity<String> addItemToBasket(@RequestBody ShoppingBasket basket) {
        shoppingBasketRepositroy.saveOrUpdateShoppingBasket(basket);

        return new ResponseEntity<>("New items has been added to the shopping basket", HttpStatus.OK);
    }

And the foreign key not being inserted into DB, if the controller is called with the following chunk of data:

{
    "userId": "user_1",
    "products": [
        {
            "name": "Product name 1",
            "description": "Some description",
            "brand": "Some brand",
            "quantity": "5",
            "price": "1111"
        }
    ]
}

What is the best solution for filling the foreign key. I know this modification in the controller could solve the issue, but it's looks like dirty hack, at least for me.

basket.getProducts().forEach(product -> {
            product.setShoppigBasket(basket);
        }); 

So for example what are the best practices for persisting data, coming from the frontend?


回答1:


Keep orthogonality in your system by avoid coupling your data access layer with the web one. Use a dto between your web and domain layer to keep things well decoupled. And yes for bidirectional oneToMany you have to set the two side of the relation to make it work. The best way is to set the ManyToOne side into the OneToMany side setter or constructor.

And so when add a product you set the product.basket(this);.



来源:https://stackoverflow.com/questions/61293079/spring-boot-hibernate-onetomany-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!