也许这个问题已被分别提出,但我无法找到解决方法。我是Spring的新手,并尝试使用注释将Spring与ssh
集成在一个简单的项目中。每当我单击用户表单保存到DB时,它都会抛出此异常:
HTTP状态500 - 请求处理失败;嵌套异常是org.hibernate.HibernateException:如果没有活动事务,saveOrUpdate无效
我做错了什么?我的代码如下:
User.java
Hibernate 4
UsDAOImpl.java
@Entity
@Table(name="SpringUsers")
public class User implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "userId")
private int id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "email")
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
用户servlet.xml中
@Repository
public class UserDAOImpl implements UserDAO{
@Autowired
private SessionFactory sessionFactory;
public UserDAOImpl(){}
public UserDAOImpl( SessionFactory sessionFactory){
this.sessionFactory= sessionFactory;
}
@Override
@Transactional
public List<User> list() {
List<User> listUser = sessionFactory.getCurrentSession()
.createCriteria(User.class).list();
return listUser;
}
@Override
@Transactional
public void saveOrUpdate(User user) {
sessionFactory.getCurrentSession().saveOrUpdate(user);
}
@Override
@Transactional
public void delete(int id) {
User userToDelete = new User();
userToDelete.setId(id);
sessionFactory.getCurrentSession().delete(userToDelete);
}
@Override
@Transactional
public User get(int i) {
String hql = "from User where id=" + i;
Query query = sessionFactory.getCurrentSession().createQuery(hql);
List<User> listUser = (List<User>) query.list();
if (listUser != null && !listUser.isEmpty()) {
return listUser.get(0);
}
return null;
}
}
答案 0 :(得分:0)
取消注释此行,它应该有效:
<tx:annotation-driven />