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组件时,还必须加入事务代码:
public class UserDaoImplTest extends DatabaseFixture {
private UserDao userDao = new UserDaoImpl();
private UserDao proxy = (UserDao)createProxy(userDao);
@Test
public void testQueryUser() {
User user = newUser("test");
proxy.createUser(user);
User t = proxy.queryUser("test");
assertEquals(user.getEmail(), t.getEmail());
}
}
注意到UserDaoImplTest持有两个UserDao引用,userDao是普通的UserDaoImpl对象,而proxy则是将userDao进行了事务封装的对象。