简体   繁体   English

Spring 不在数据库中保存多对多映射

[英]Spring not saving many-to-many mapping in DB

I have 2 entities.我有 2 个实体。 An Appointment and an Item.约会和项目。 They are both independent and we can have multiple items, in multiple appointments.它们都是独立的,我们可以在多个约会中拥有多个项目。

The Appointment class:预约class:

@Entity(name = "Appointment")
@Table(name = "appointment")
public class Appointment
{
    @Id
    @JsonProperty("appointment_id")
    @Column(name = "appointment_id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @JsonProperty("date")
    private Date startingTimestamp;

    @ManyToMany(mappedBy = "appointment",
        cascade = CascadeType.ALL)
    private List<Item> collectionOfItems;

    @JsonProperty("duration")
    private int duration;

    @JsonProperty("state")
    private AppoitmentState state;

    @ManyToOne
    @JsonBackReference
    @JoinColumn(name="user_appointment_owner_id", nullable = false)
    @JsonProperty("user_owner")
    private User user;

and the Item class:和项目 class:

@Entity
@Table(name = "item")
public class Item
{
    @Id
    @Column(name = "item_id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long Id;

    @JsonProperty("name")
    private String name;

    @JsonProperty("duration")
    private int duration;

    @ManyToMany(targetEntity = Appointment.class,
        cascade = CascadeType.ALL)
    @JoinTable(name = "appointment_item", joinColumns = { @JoinColumn(name = "item_id") },
        inverseJoinColumns = { @JoinColumn(name = "appointment_id") })
    private List<Appointment> appointment;

    @ManyToMany
    @JsonProperty("set_of_professionals")
    @JsonIgnore
    private Set<Professional> professional;

    @JsonProperty("business_owning")
    private Long business_id;

Constructors, getters and setters are omitted here.这里省略了构造函数、getter 和 setter。

There is also a patch method inside the Appointment controller. Appointment controller里面还有一个补丁方法。

@RequestMapping(value = "appointment/{itemID}", method = RequestMethod.PATCH,  consumes = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<Appointment> addItem(@PathVariable Long itemID, @RequestBody ObjectNode appointment_id_str)
{
    Long appointment_id = appointment_id_str.get("appoitment_id").asLong();
    Optional<Appointment> targetAppoitment = appointmentService.findById(appointment_id);
    Optional<Item> addedItem = itemService.findById(itemID);
    if (targetAppoitment.isPresent() && addedItem.isPresent())
    {
        Appointment appoitmentInDB = targetAppoitment.get();
        appoitmentInDB.addItem(addedItem.get());
        Appointment savedAppointment = appointmentService.save(appoitmentInDB);
        return new ResponseEntity<>(savedAppointment, HttpStatus.CREATED);
    }
    return new ResponseEntity("", HttpStatus.INTERNAL_SERVER_ERROR);
}

Now although as seen in the debugger, an item has been added in appoitment's list, save will not flash the change into the database.现在,尽管在调试器中看到,已在 appoitment 的列表中添加了一项,但保存不会 flash 将更改保存到数据库中。

在此处输入图像描述

This is the database:这是数据库:

数据库

Any idea what I am missing?知道我缺少什么吗? Thanks a lot, madams and gentlemen.非常感谢,女士们,先生们。

It is because the Item class own's the relationship.这是因为Item class 自己的关系。

If you have described the relationship inside the Appointment class and used mappedBy inside the Item class you wouldn't have this issue.如果您已经在Appointment class 中描述了关系,并在Item class 中使用了mappedBy ,则不会遇到此问题。 This happens because Hibernate uses the class in which the relationship was defined in order to maintain it's associations.发生这种情况是因为 Hibernate 使用 class 来定义关系以维护其关联。

To fix this problem you should adjust you entities in the following way:要解决此问题,您应该通过以下方式调整实体:

class Appointment {

...
    
@ManyToMany(targetEntity = Item.class,
        cascade = CascadeType.ALL)
    @JoinTable(name = "appointment_item", joinColumns = { @JoinColumn(name = "appointment_id") },
        inverseJoinColumns = { @JoinColumn(name = "item_id") })
    List<Item> collectionOfItems;

...

}

and

class Item {

...

    @ManyToMany(mappedBy = "collectionOfItems",
        cascade = CascadeType.ALL)
    private List<Appointment> appoitment;

...

}

This question has already been answered on stackoverflow, link这个问题已经在stackoverflow上得到了回答, 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM