Question

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?

Était-ce utile?

La solution

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.

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top