我有一个简单的JPA存储库,如下所示:
public interface UserRepository extends JpaRepository
{
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()?