如何将Hibernate实体对象传递给另一个保存到数据库的方法?

时间:2016-08-10 09:12:03

标签: java hibernate

我有一个访问实体并使用新数据更新它的EJB,并将其发送到JMS队列,然后由一个MDB使用,该MDB应该实现将该实体保存/保存到数据库的代码。这是从数据库访问实体的EJB:

AccountAccessBean.java

@Stateless(mappedName = "AccountAccessBean")
@TransactionManagement(value=TransactionManagementType.CONTAINER)
@LocalBean
public class AccountAccessBean {

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void resigterAccountEvent() {

        Calendar calendar = Calendar.getInstance();
        Date now = calendar.getTime();

        Configuration configuration = new Configuration().configure();
        ServiceRegistry registry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties())
                .build();
        SessionFactory sessionFactory = configuration
                .addAnnotatedClass(Account.class)
                .addAnnotatedClass(Accountaccesslog.class)
                .buildSessionFactory(registry);
        Session session = sessionFactory.openSession();     
        Transaction transaction = session.beginTransaction();

        Account accountEntity = (Account) session.get(Account.class, new Integer(1));
        accountEntity.setAccessCount(accountEntity.getAccessCount() + 1);

        Accountaccesslog accountAccessLogEntity = new Accountaccesslog();
        accountAccessLogEntity.setAccessDateTime(new Timestamp(now.getTime()));
        accountEntity.addAccountaccesslog(accountAccessLogEntity);
        session.save(accountAccessLogEntity);

        transaction.commit();
        session.close();

        EntityEnqueueBean enqueueObject = new EntityEnqueueBean();
        enqueueObject.enqueueEntity(accountEntity);
    }
}

目前,此Bean更新实体并自行将更改提交到数据库。我想移动'提交'接收JMS消息的以下MDB的代码的一部分:

AccountPersistenceMDB.java

@MessageDriven(
    activationConfig = { @ActivationConfigProperty(
            propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
            @ActivationConfigProperty( propertyName = "destination", 
            propertyValue ="java:/jms/queue/AccountAccessQueue")
    })
public class AccountPersitenceMDB implements MessageListener {

    public void onMessage(Message message) {
        ObjectMessage objectMessage = null;
        objectMessage = (ObjectMessage) message;
        try {
            Account accountEntity = (Account) objectMessage.getObject();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

我不确定如何实现这一点。我是否还需要将会话或事务对象与accountEntity对象一起传递?非常感谢任何帮助或指导。

1 个答案:

答案 0 :(得分:0)

您有两项操作

  1. 访问权限并发送JMS消息
  2. 使用JMS消息并提交到数据库
  3. 您的交易不能也不应该围绕这两项操作

    JMS消息可以

    1. 如果消费者的消费速度不够快,请排队等候
    2. 由多个消费者消费
    3. 重播
    4. 在与发布商不同的计算机上使用
    5. 有关将JMS使用和数据库提交组合为单个事务的更多信息,请参阅here