'Avoid an entity to be saved
I've got two entities as follows:
@Entity
public class UserType implements Serializable {
@Id
@Column(name = "id")
private Integer id;
@Column(name = "description")
private String description;
@OneToMany(mappedBy = "userType")
private List<User> users;
}
@Entity
public class User implements Serializable {
@Id
@Column(name = "id")
private Integer id;
@ManyToOne
@JoinColumn(name = "user_type")
private UserType userType;
}
I don't want any new UserType to be created, this entity will have the same values the whole life of the project, but I still want it to exist as an entity so new Users only can be created if they are referencing an actual existing UserType.
With my current configuration, when I save a User that already exists (aka updating) pointing to a UserType that doesn't exist, the exception I recieve is EntityNotFoundException which seems ok, indicating me that this User can't be updated referencing a non existing UserType. But, whenever I try to create a new User pointing to a UserType that doesn't exist, the exception is TransientPropertyValueException, which indicates me that Hibernate is in some way expecting this UserType to be saved.
That's how it's saved:
public interface UserRepository extends JpaRepository<User, Integer>{
}
public class UserService {
private final UserRepository userRepository;
public User update(User user, UserType userType, Integer id) {
user.setId(id); //I'm updating an already existing entity.
user.setUserType(userType);//value of userType id does not exists in database.
user.getUserType().setUsers(List.of(user));
userRepository.save(user); //this throws EntityNotFoundException
}
public User create(User user, UserType userType) {
user.setUserType(userType); //value of userType id does not exists in database.
user.getUserType().setUsers(List.of(user));
userRepository.save(user); //this throws TransientPropertyValueException
}
}
Is this correct? Is there some way to avoid this behavior and to make it consistent so everytime I save User, no matter if I'm updating or inserting I receive the same exception?
Solution 1:[1]
I think userType has to be queried and set it to User, if you don't want to create unnecessary UserTypes with cascade all.
I assume that userType is selected from combobox or similar ui component, so you need to get that UserType from database and set it to user entity which will be created.
Pseudocode :
UserType userType = userTypeRepository.findById(userType.getId());
user.setUserType(userType);
userRepository.save(user);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
