Spring JPA – 持久化嵌套对象

我有一个简单的JPA存储库,如下所示:

public interface UserRepository extends JpaRepository<User, String>
{
    User findByName(String name);
}

还有两个具有OneToOne映射的类,如下所示:

@Entity
public class User
{
    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    protected String uuid;

    @Column(nullable = false, unique = true)
    private String name;

    @Column(nullable = false)
    private String email;

    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user")
    private PlayerCharacter playerCharacter;

    //...
}

.

@Entity
public class PlayerCharacter
{
    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    protected String uuid;

    @OneToOne(optional = true)
    private User user;

    @Column(nullable = false)
    private String characterName;

    //...
}

现在,我知道我可以轻松地编辑和持久化这样的用户实例:

User user = userRepository.findByName("Alice");
PlayerCharacter character = user.getPlayerCharacter();
character.setCharacterName("ConanTheBarbarian");
userRepository.save(user);

但是如何在我没有指向User实例的指针的上下文中持久保存PlayerCharacter实例,f.:

public void changePlayerCharacterName(PlayerCharacter character, String name){
    character.setCharacterName(name);
    // How to correctly persist the 'character' instance here?
}

我可以只调用userRepository.save(character);?

我是否需要自动装配另一个存储库(PlayerCharacterRepository)并在其上调用.save()?

最佳答案 首先,您不会使用UserRepository,而是使用PlayerCharacterRepository.

但即便如此,JPA的基金会原则是它会自动使对托管实体的更改持续存在.所以你不需要调用save().您只需获取托管玩家角色(使用find(),或通过关联导航或使用查询),并更改其名称.这就是你所需要的.

点赞