hi,
I'm migrating a small webapp to hibernate annotations and am currently facing a strange problem.
I have following User model object (as test code):
Code:
@Entity
@Table(name = "TLUSER")
public class User extends AbstractEntity { //AbstractEntity just contains some abstract methods
private Long id;
[b] @Version[/b]
private Long version;
private String name;
private Set<Role> roles;
@Transient
private String type;
@Override
public boolean equals(Object otherObject) {
return otherObject instanceof User && StringUtils.equals(((User) otherObject).getName(), getName());
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "USER_ID")
public Long getId() {
return id;
}
@Column(length = 64, nullable = false)
public String getName() {
return name;
}
@OneToMany(mappedBy = "user")
@JoinColumn(name = "USER_ID", nullable = false)
public Set<Role> getRoles() {
return roles;
}
public String getType() {
return type;
}
public Long getVersion() {
return version;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(getName()).toHashCode();
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public void setType(String type) {
this.type = type;
}
public void setVersion(Long version) {
this.version = version;
}
}
This is the simple controller:
Code:
@Controller
@RequestMapping(value = "/userEdit.htm")
public class UserEditController {
@Autowired
private UserService userService;
@RequestMapping(method = RequestMethod.GET)
public void setupForm(@RequestParam(value = "userID") Long userID, ModelMap model) {
User u = userService.getUser(userID);
model.addAttribute("user", u);
}
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@RequestParam(value = "userID") Long userID,
@ModelAttribute(value = "user") User u,
BindingResult result,
SessionStatus status) {
userService.updateUser(u);
return "redirect:users.htm";
}
}
The way the code is above it works fine; when I edit an existing user this user is then updated when userService.updateUser is called (this in the end calls a saveOrUpdate on the session).
If however in User.class move the @Version annotation from the field version to the getter like this:
Code:
@Version
public Long getVersion() {
return version;
}
then after the same edit action it will create a new User (each time).
If someone could enlighten me why the location of the annotation matters that would be great!
Side-question: what is the best place to place the annotations in general: fields or getters?
many thanks,
Stijn