문제

I have bean

@Entity
@Table(name = "Users")
public class User {

@Id
@GeneratedValue
@Column(name = "userId")
private Integer userId;

@Column(name = "username")
private String username;

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "parentId")
@Fetch(value = FetchMode.SUBSELECT)
private List<User> childs;

@Column(name = "password")
private String password;

@Column(name = "email")
private String email;

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "userId")
@Fetch(value = FetchMode.SUBSELECT)
private List<Role> roles;

and an object loaded by hibernate, but before saving all changes to database I need to get current password from database. I am trying to do this

if (user.getPassword() == null) { user.setPassword(userDao.getUserById(user.getUserId()).getPassword());}

but I am getting DuplicateKeyException.

So, how can I do this? Or, can I save all fields except password?

도움이 되었습니까?

해결책

You could retrieve the data from the database with Hibernate, copy the values from your (detached) bean (coming from your presentation or business layer) into this JPA bean (the one returned by Hibernate), then let Hibernate update the database (at the end of the transaction), or explicitely if you want.

다른 팁

You could use the annotation @Column(updatable=false) to exclude the field from database update

you can use Hibernatecallback methods @PrePersist. which does some action before persist there you can write yor fetch password into local transient variable logic.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top