开发者

Synchronization issue with JMS and JPA

I have a situation where I need to receive parts of a large file over JMS(grouped messages) and store it in DB.

The problem is that each message in group will be one row in TABLE A and there is @ManytoOne realtionship to TABLE B. Which means the for one group there will be only one entry in table B but many entries in table A.

My current logic is such that before inserting in table A, I'm checking for any entries(@Name开发者_高级运维dQuery, as the primary key would NOT be known to the MDB at that time), and if not found, creating a new one(creating the primary key of Table B here).

Since there are multiple instances of MDB receiving the messages in same group, the entries in table B are getting duplicated for same message group, since the transaction in MDB which first created entry for TABLE B is not not comiitted yet.

To be more clear:

Step 1: Receiving the message.

Step 2: Create the entitiy required for TABLE A. Check whether there's any entries with same group ID in table B(READ), if found, set the relationship and persist, if not, create a new entity for table B(WRITE) (with generated primary key by a service) set the relationship and persist.

The issue is, multiple instances of MDB creates entry for table B, since it not able to find the entry(created by the first MDB) during READ, hence WRITING new entries for same group ID.

Is there any way I can overcome this problem ? 1. I'm using eclipselink and Oracle , Container managed transaction and entity managers are injected using @PersistenceContext annotation.

Thanks


Not exactly sure what you are doing? Are you trying to prevent both transactions from creating a new A, or only a new B?

You can add a unique constraint on the A foreign key in the B table. This will ensure the second attempt to insert a B for the A will fail.

Another solution is to use a pessimistic lock on the A for the transaction, this will ensure the transaction do not conflict.

You could also use an optimistic lock by forcing the version of A to increment, this will cause the second attempt will fail. Actually since A has a ManyToOne to B, its version should increment, so you should get a lock error already.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜