写一个新的dao。没有Hibernate Session绑定到线程

时间:2012-09-12 15:42:03

标签: java sql hibernate transactional

所以我有这样的课程

BaseDao

public interface BaseDao<T> {

    T save(T entity);  
}

userDAO的

public interface UserDao extends BaseDao<User> {

    User getUserByUserName(String name);

}

GenericDao 公共抽象类GenericDao实现了BaseDao {

@Autowired
protected SessionFactory sessionFactory;

private Class<?> getEntityClass() {
    return ((Class) ((ParameterizedType) getClass().getGenericSuperclass())
            .getActualTypeArguments()[0]);
}

public T save(T entity) {
    Integer id = (Integer) sessionFactory.getCurrentSession().save(entity);
    return (T) sessionFactory.getCurrentSession().get(getEntityClass(), id);
}

}

在UserDAOImpl

@Repository
public class PgUserDaoImpl extends GenericDao<User> implements UserDao {

    public User getUserByUserName(String name) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(
                User.class);
        criteria.add(Restrictions.eq("name", name));

        return (User) criteria.uniqueResult();
    }

}

GenericService

public class GenericService<T extends GenericDao<E>, E> {

    protected T dao;

    public GenericService(T dao) {
        setDao(dao);
    }

    @Transactional
    public E save(E entity) {
        return dao.save(entity);
    }
}

UserServiceImpl

@Service("userServiceImpl")
public class UserServiceImpl extends GenericService<PgUserDaoImpl, User>
        implements UserService {

    @Autowired
    public UserServiceImpl(PgUserDaoImpl dao) {
        super(dao);
    }

    @Autowired
    private UserAssebmler assebmler;

    @Transactional
    @Override
    public UserDetails loadUserByUsername(String name)
            throws UsernameNotFoundException {
        .....
    }

}

所以我编写测试控制器以保存用户,但我总是得到Exception org.hibernate.HibernateException:没有Hibernate Session绑定到线程,配置不允许在这里创建非事务性的

控制器 @

Controller
@RequestMapping(value = "/test")
public class TestController {

    @Autowired
    private UserServiceImpl userService;

    @RequestMapping(value = "save", method = RequestMethod.GET)
    public String test() {

        User user = new User();

        user.setName("admin");
        user.setPassword("21232f297a57a5a743894a0e4a801fc3");
        user.setRole(UserRole.ADMIN);

        userService.save(user);

        return "home";
    }

}

有人知道解决这个问题吗?谢谢:))

1 个答案:

答案 0 :(得分:0)

我通过从HibernateDaoSupport类扩展GenericDao类来解决我的问题。