HibernateException:非法尝试将集合与两个打开的会话相关联

时间:2015-05-04 11:28:03

标签: hibernate session orm sql-delete

这是我的表格:

Orders.java

@Entity
public class Orders implements Serializable {

@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private Date orderDate;
@ManyToOne(cascade = CascadeType.ALL)
private User user;

@OneToMany(mappedBy = "orders", cascade = CascadeType.ALL)
private Set<OrderItem> orderItems = new HashSet<OrderItem>();
//getter/setters

我要从Orders表中删除一条记录:

OrderServiceImple.java

@Transactional
public void deleteOrder(String oid) {
    Orders ordersToDelete = orderDao.findById(oid);
    System.out.println("orders To Delete: " + ordersToDelete); // retrieved correctly
    orderDao.delete(ordersToDelete); // exception is here
}

这是delete()中的oderDaoImpl

OrderDaoImpl.java

@Component
public class OrderDaoImpl implements OrderDao<Orders, Integer>, Serializable {

@Autowired
private SessionFactory sessionFactory;
private Session session;

public Session getSession() {
    session = sessionFactory.openSession();
    return session;
 }

public void delete(Orders entity) {
    getSession().delete(entity);
  }
}

我在sessionFactory.getCurrentSession().delete(entity)中尝试delete(),但得到了同样的错误。

例外:

04-May-2015 15:49:18.929 WARNING [http-apr-8080-exec-2] null.null #{myCardBean.deleteOrder()}: org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
 javax.faces.FacesException: #{myCardBean.deleteOrder()}: org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
    at 

com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
Caused by: org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
    at 
org.hibernate.collection.internal.AbstractPersistentCollection.setCurrentSession(AbstractPersistentCollection.java:633)

更新

public Orders findById(String id) {
    Orders foundOrders = (Orders) getSession().get(Orders.class, Integer.parseInt(id)); // should be Integer
    return foundOrders;
}

1 个答案:

答案 0 :(得分:2)

在两种方法中使用内置的currentsession() SessionFactory

findById(String id)delete(Orders entity)