hi all,
I have a problem with transaction in hibernate because there is an impossibility of making a rollback.
I explain me : i have created a user class with hibernate annotations and i have made a test class in order to add user to my MySQL database.
The probleme is that when an user is already in my database, i would like the transaction be 'canceled', that is to say, the database return to its initial stat before inserting.
Code of user class :
Code:
@Entity
@Table(name = "USERS")
public class User {
@Id
@GeneratedValue
@Column(name = "USER_ID")
private Long id;
@Column(name = "LOGIN", nullable = false, unique = true)
private String login;
@Column(name = "PASS", nullable = false)
private String pass;
@ManyToMany(targetEntity = com.calenco.users.Role.class, cascade = {
CascadeType.PERSIST, CascadeType.MERGE })
@JoinTable(name = "USER_ROLE", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
private Collection<Role> roles = new ArrayList<Role>();
@Column(name = "MAIL", nullable = false)
private String mail;
/**
* Creates a new instance of Users
*/
public User() {
}
public User(String login, String pass, String mail, Collection<Role> role) {
super();
this.login = login;
this.pass = pass;
this.roles = role;
this.mail = mail;
}
public Long getId() {
return id;
}
@SuppressWarnings("unused")
private void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public String getPass() {
return pass;
}
public void setLogin(String login) {
this.login = login;
}
public String getMail() {
return mail;
}
public Collection<Role> getRoles() {
return roles;
}
public void setMail(String mail) {
this.mail = mail;
}
public void setPass(String pass) {
this.pass = pass;
}
public void setRoles(Collection<Role> roles) {
this.roles = roles;
}
public void addRole(Role role) {
roles.add(role);
}
}
Code of test class :
Code:
public void addUser(User user) throws UserExistsException {
if (userExists(user)) {
throw new UserExistsException("Users already exists");
} else {
Session session = HibernateUtils.getSession();
Transaction transact = session.beginTransaction();
session.save(user);
System.out.println("User added : " + user.getLogin());
transact.commit();
session.close();
}
}
public boolean addUsers(List<User> users) throws UserExistsException {
Session session = HibernateUtils.getSession();
Transaction transact = null;
boolean retVal = true;
try {
transact = session.beginTransaction();
for (int i = 0; i < users.size(); i++) {
System.out.println("Trying to add user " + i);
addUser(users.get(i));
}
transact.commit();
} catch (UserExistsException e) {
if (transact != null)
transact.rollback();
retVal = false;
throw e;
} finally {
session.close();
}
return retVal;
}
I would like to know why my transaction doesn't execute a rollback.
If there is another method to do this, i would be happy to know it.
Thanks in advance for answers.