【问题标题】:Set value on additional attribute in @ManyToMany relationship table spring boot在@ManyToMany关系表spring boot中设置附加属性的值
【发布时间】:2022-01-11 22:34:28
【问题描述】:

我在 User 和 Diet 类之间有一个 @ManyToMany 关系表。表 (UserIsOnADiet) 有 2 个附加列:fromDate(开始节食)和 toDate(结束)。当用户注册节食时,我想在 fromDate 属性上设置一个值,因为它有一个非空约束。我怎样才能做到这一点?这是我的代码:

类用户

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer username_id;
    private String username;
   
    @ManyToMany
    @JoinTable(
            name = "is_on",
            joinColumns = @JoinColumn(name = "username_id"),
            inverseJoinColumns = @JoinColumn(name = "diet_id"))
    private Set<Diet> userIsOnADiet;

班级饮食

@Entity
public class Diet {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer diet_id;
    private String diet_name;

    @ManyToMany(mappedBy = "userIsOnADiet")
    public List<User> users;

用户服务:

@Override
    public User updateDiets(Integer id, Diet d) {
        User u = this.findById(id);
        Set<Diet> userDiets = u.getUserIsOnADiet();
        userDiets.add(d); 
//        LocalDate fromDate = LocalDate.now();
//        UserIsOnADiet userIsOnADiet = new UserIsOnADiet();
//        userIsOnADiet.setFromDate(fromDate);

// I want to do something like this, but I cannot save User with null value on fromDate,
//and cannot set fromDate before creating a tuple in the database.

        return this.userRepository.save(u);
    }

【问题讨论】:

    标签: java spring postgresql hibernate jpa


    【解决方案1】:

    您需要将连接表映射到一个附加实体,并将@ManyToMany 关联替换为两个双向@OneToMany 关联。

    The best way to map a many-to-many association with extra columns when using JPA and Hibernate

    对于简单的多对多数据库关系,您可以使用 @ManyToMany JPA 注释,因此隐藏连接表。

    但是,有时您在连接表中需要的外键列不止两个,为此,您需要将 @ManyToMany 关联替换为两个双向 @OneToMany 关联。与单向@OneToMany 不同,双向关系是映射一对多数据库关系的最佳方式,该关系需要在父端有一组子元素

    【讨论】:

      猜你喜欢
      • 2022-08-18
      • 2021-03-06
      • 2020-08-21
      • 2020-12-24
      • 2023-03-31
      • 1970-01-01
      • 2019-03-04
      • 2017-10-28
      • 2020-02-14
      相关资源
      最近更新 更多