线程和休眠会话的问题

时间:2012-10-17 14:43:26

标签: java multithreading spring hibernate repository

我正在使用hibernate 3和spring。 当我启动一个线程时发生了一个异常:

org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions

我不知道如何分离实体或关闭此体系结构的会话。 我很感激一些帮助。

CommunicationService.sendCommunications()代码:

public void sendCommunications(HibernateMessageToSendRepository messageToSendRepository)  {
    Long messageId = new Long(41); //this is only for test. the idea is get a list of id and generate a thread group.
    MessageSender sender = SmsSender(messageId, messageToSendRepository);
    sender.start();
}

调用sendCommunications代码:

ApplicationContext appCont = new ClassPathXmlApplicationContext("appContext.xml");      
ServiceLocator serviceLocator = ServiceLocator.getInstance();
HibernateMessageToSendRepository messageToSendRepository = (HibernateMessageToSendRepository) appCont.getBean("messageToSendRepository");

CommunicationService communication = serviceLocator.getCommunicationService();
communication.sendCommunications(messageToSendRepository);

SmsSender(从MessageSender(线程)扩展)代码:

public class SmsSender extends MessageSender {

    public SmsSender(Long messageToSendId, HibernateMessageToSendRepository messageToSendRepository) {
        super(messageToSendRepository);
        MessageToSend messageToSendNew = this.messageToSendRepository.getById(messageToSendId);     
        this.messageToSend = messageToSendNew;
    }

    public void run() {
        try {
            MessageToSendSms messageToSendSms = (MessageToSendSms) this.messageToSend;
            Iterator<CustomerByMessage> itCbmsgs = messageToSendSms.getCustomerByMessage().iterator();          
            while (itCbmsgs.hasNext()) {                
                CustomerByMessage cbm = (CustomerByMessage) itCbmsgs.next();                        

                //sms sending
                this.getGateway().sendSMS(cbm.getBody(), cbm.getCellphone());                       
                cbm.setStatus(CustomerByMessageStatus.SENT_OK);
                cbm.setSendingDate(Calendar.getInstance().getTime());               
            }           

            messageToSendSms.getMessage().setStatus(messageToSendStatus.ALL_MESSAGES_SENT);
            this.messageToSendRepository.update(messageToSendSms);      
        } catch (Exception e) {         
            this.log.error("Error en sms sender " + e.getMessage());
        }

    }
}

MessageToSendRepository代码:

public void update(MessageToSend messageToSend) {
    try {
        this.getSession().update(messageToSend);
    } catch (HibernateException e) {
        this.log.error(e.getMessage(), e);
        throw e;
    }
}

1 个答案:

答案 0 :(得分:0)

您需要在检索messageToSendNew之后,但在与其他线程共享之前分离Session.close()。您可以通过在休眠会话中调用merge()来分离对象。

请注意,您必须急切地填充所需的所有字段。

如果您需要使用新会话重新连接,可以使用{{1}}方法。