实体类PasswordTicket代表一个重置口令的请求:
@Entity
@Table(name="T_PWDT")
public class PasswordTicket {
private String id;
private User user;
private String ticket;
private long createdDate;
@Id
@Column(nullable=false, updatable=false, length=32)
@GeneratedValue(generator="system-uuid")
@GenericGenerator(name="system-uuid", strategy="uuid")
public String getId() { return id; }
protected void setId(String id) { this.id = id; }
@ManyToOne
@JoinColumn(nullable=false, updatable=false)
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
@Column(nullable=false, updatable=false, length=32)
public String getTicket() { return ticket; }
public void setTicket(String ticket) { this.ticket = ticket; }
@Column(nullable=false, updatable=false)
public long getCreatedDate() { return createdDate; }
public void setCreatedDate(long createdDate) { this.createdDate = createdDate; }
}
UserDao接口定义了对用户的相关操作:
public interface UserDao {
User queryForSignOn(String username);
User queryUser(String username);
void createUser(User user);
void updateUser(User user);
boolean updateEmailValidation(String username, int ticket);
String createPasswordTicket(User user);
boolean updatePassword(String username, String oldPassword, String newPassword);
boolean queryResetPassword(User user, String ticket);
boolean updateResetPassword(User user, String ticket, String password);
void updateLock(User user, long lockTime);
void updateUnlock(User user);
}
UserDaoImpl是其实现类:
public class UserDaoImpl implements UserDao {
public User queryForSignOn(String username) {
User user = queryUser(username);
if(user.getLocked())
throw new LockException(user.getLockDate());
return user;
}
public User queryUser(String username) {
return (User) HibernateUtil.query(User.class, username);
}
public void createUser(User user) {
user.setEmailValidation((int)(Math.random() * 1000000) + 0xf);
HibernateUtil.createEntity(user);
}
// 其余方法略
...
}
由于将Hibernate事务绑定在Thread上,因此,实际的客户端调用DAO组件时,还必须加入事务代码:
Transaction tx = HibernateUtil.getCurrentSession().beginTransaction();
try {
dao.xxx();
tx.commit();
}
catch(Exception e) {
tx.rollback();
throw e;
}