Spring JPA:更改不会在 OneToOne 关系中持续存在

Spring JPA: change doesn't persist in OneToOne relationship

我的论文使用 Spring Boot Starter Data JPA,但我有一个错误,我无法完全解决。

我的实体之间有以下关系:

餐厅

@NoArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "restaurants")
public class Restaurant {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    // ...

    @OneToMany(targetEntity = RestaurantTable.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name = "restaurant_table_fk", referencedColumnName = "id")
    private Set<RestaurantTable> restaurantTables;
    // ...
}

餐厅餐桌

@NoArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "restaurant_table")
public class RestaurantTable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id

    // ...

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "restaurant_table_id")
    private EndUser user;

    // ....

}

最终用户

@NoArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "end_users")
public class EndUser {
    public EndUser(String userId, String encryptedPassword) {
        this.userId = userId;
        this.encryptedPassword = encryptedPassword;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Long id;
    private String userId;
    private String encryptedPassword;
}

基本上:每个餐厅都可以有很多table,每个table都有一个对应的用户。

当我创建一个新的 table 时,我会自动为其创建一个新用户。

RestaurantTableService

// ...

@Override
public void add(RestaurantTable restaurantTable) {
    var restaurant = getRestaurant();

    restaurantTable.setUser(
            new EndUser(idGenerationService.get(), passwordEncoder.encode(passwordGenerationService.get()))
    );

    restaurant.addTable(restaurantTable);
    restaurantRepository.save(restaurant);
}

// ...

到目前为止这有效。问题是当我尝试更改 table 用户的密码时。我尝试了更多方法。

使用更新后的密码创建新用户并将其分配给 table

var newPassword = passwordGenerationService.get();
var user = restaurantTable.getUser();
var newUser = new EndUser(user.getUserId(), passwordEncoder.encode(newPassword));

restaurantTable.setUser(newUser);
restaurantTableService.update(restaurantTable);

更新现有用户

var newPassword = passwordGenerationService.get();
var user = restaurantTable.getUser();

user.setEncryptedPassword(passwordEncoder.encode(newPassword));

restaurantTable.setUser(user);
restaurantTableEntityService.update(restaurantTable);

restaurantTableEntityService.update(restaurantTable) 看起来像这样:

RestaurantTableService

@Override
public void update(RestaurantTable restaurantTable) {
    var restaurant = getRestaurant();
    restaurant.updateTable(restaurantTable);
    restaurantRepository.save(restaurant);
}

None 似乎有效。更改不会持续存在。我应该更改什么以使密码更改保持不变?

只需使用直接存储库直接持久化您想要的更改

var newPassword = passwordGenerationService.get();
var user = restaurantTable.getUser();
user.setEncryptedPassword(passwordEncoder.encode(newPassword));
endUserRepository.save(user);

您必须像这样将更改持久化到用户实体中:endUserRepository.save(user);