簡體   English   中英

Spring Data JPA ManyToOne 和 OneToMany - 無法找到具有 ID 的實體

[英]Spring Data JPA ManyToOne and OneToMany - Unable to find entity with ID

我有三個表 - roleuseruser_role 這應該是ManyToMany但由於我也想為user_role生成 id,我使用了OneToManyManyToOne

這是我僅具有相關字段的實體:

@Entity
public class Role {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Integer id;
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "role")
    private Set<UserRole> userRoles;
}

@Entity
public class User {
    @Id
    private String id;
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
    private Set<UserRole> userRoles;
}

@Entity
public class UserRole {
    @Id
    private String id;
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;
    @ManyToOne
    @JoinColumn(name = "role_id")
    private Role role;  
}

然后,這就是我創建它們的實例並保存到數據庫的方式:

// Retrieve from DB by ID
Role role = ...;

// ID String is generated from UUID
User user = new User();
user.id("abc");

// ID String is generated from UUID
UserRole userRole = new UserRole();
userRole.setId("xyz");

Set<UserRole> userRoles = Set.of(userRole);

role.setUserRoles(userRoles);
user.setUserRoles(userRoles);

userRole.setUser(user);
userRole.setRole(role);

userRepository.save(user);

無論我如何嘗試和搜索,我都發現很難解決的問題:

2020-09-27 23:41:58.917  WARN 21948 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find com.example.entity.UserRole with id xyz; nested exception is javax.persistence.EntityNotFoundException: Unable to find com.example.entity.UserRole with id xyz]

請幫我。 謝謝。

斯特恩說得很好。 您正在嘗試保存user實體,但您在任何地方都沒有任何級聯設置。 因此,當您調用userRepository.save(user)它顯然缺少角色實體。 在保存user之前保存依賴實體,或者更好的是,在 User 類中的userRoles字段上方添加級聯等。

正如其他地方提到的,您需要設置最低限度:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "user" , cascade = CascadeType.ALL)
private Set<UserRole> userRoles;

或最低:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "user" , cascade = 
        CascadeType.PERSIST)
private Set<UserRole> userRoles;

但是,如果您需要按User獲取UserRoles ,您還需要設置:

// for each UserRole in the list.
userRole.setUser(user);

在堅持之前,否則將不會填充列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM