Hi fellow developers,
Probably you'll be able to answer this right off the top of your head, as this error occurs in response to a very routine webapp task: set a newly created user's company to the same company as that of the logged-on user who created him/her.
The USER table has a COMPANY_ID field to reflect the many-to-one relationship, so I expect Hibernate to create a new user with the same company ID as the user I'm logged in as. Instead, Hibernate/Tapestry outputs the following error...
Quote:
org.apache.tapestry5.runtime.ComponentEventException
detached entity passed to persist: com.example.harbour.entities.Company
Code snippet from 'pages/user/CreateUser.java'...
Code:
User user = new User(firstName, lastName, userName, email, authenticator.encryptPassword(password));
//Set the new user's company to the same as the creator's company
user.setCompany(authenticator.getLoggedUser().getCompany());
crudServiceDAO.create(user);
The User>>Company relationship, as defined in the User entity class...
Code:
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="COMPANY_ID")
private Company company;
...
@Override
public boolean equals(Object other){
if(this == other) return true;
if(!(other instanceof User)) return false;
final User user = (User)other;
if(!user.getUserName().equals(getUserName())) return false;
if(!user.getFirstName().equals(getFirstName())) return false;
if(!user.getLastName().equals(getLastName())) return false;
return true;
}
@Override
public int hashCode(){
int prime = 31;
int result = 1;
result = prime * result + ((userName == null) ? 0 : userName.hashCode());
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
return result;
}
The Company>>User relationship, as defined in the Company entity class...
Code:
@OneToMany(mappedBy="company", cascade=CascadeType.ALL)
private Collection<User> users = new ArrayList<User>();
...
@Override
public boolean equals(Object other){
if(this == other) return true;
if(!(other instanceof Company)) return false;
final Company company = (Company)other;
if(!company.getName().equals(getName())) return false;
if(!company.getEmail().equals(getEmail())) return false;
if(!company.getCreated().equals(getCreated())) return false;
return true;
}
@Override
public int hashCode(){
int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((created == null) ? 0 : created.hashCode());
return result;
}
I included the equals() and hashCode() methods in case they shine any light on the matter.
I'd really appreciate your help.
Thanks,
Chris.