You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@servicecomb.apache.org by GitBox <gi...@apache.org> on 2019/06/13 01:42:09 UTC

[GitHub] [servicecomb-pack] pengyu0929 edited a comment on issue #479: 向TxEvent表中插入时,为什么将surrogateId初始化为-1?

pengyu0929 edited a comment on issue #479: 向TxEvent表中插入时,为什么将surrogateId初始化为-1?
URL: https://github.com/apache/servicecomb-pack/issues/479#issuecomment-501515839
 
 
   @WillemJiang 是的,就是在执行save方法时,传进来的参数event中surrogateId=-1,这个值得设置实在上一步handle方法中通过调用TxEvent的构造函数初始化的,这就导致在使用jpa的SimpleJpaRepository的save方法时只会执行里边的merge方法。在save方法中会判断entity是否是新创建的(判断的条件是主键是否为null),因为此时entity的主键已经设置为-1了,所以只会执行merge方法(之后会将entity交给EntityManager管理)。
   第一种情况:TxEvent主键使用自增
   当surrogateId=-1时,我是用mysql没有问题,但是在使用oracle时会覆盖之前插入的记录,总之表中只会保存一条记录。
   关于这个现象,我的猜测是:
        在alpha接收到SagaStartEvent时,会将它插入数据库并且保存在EntityManager的缓存中,在之后进来的TxStartEvent(surrogateId=-1)执行merge(),merge()会在缓存和数据库中判断是否具有相同id的entity,只有满足一个,就会更新数据库和缓存。
   第二种情况:TxEvent主键使用序列(指定我创建的序列)
   当surrogateId=-1时,在使用oracle时只会保存第一次请求的SagaStartEvent,之后的TxStartEvent等等都没有插入,而且我发现在merge之后主键并没有回写,还是-1,这就导致保存在EntityManager缓存中的entity的主键为-1,下次在调用时merge时就会和EntityManager缓存中的entity主键一致,此时merge就会更新主键-1的记录,但是数据库没有,所以第一次插入的SagaStartEvent没有被覆盖(触发器使主键自增了)。
   对于这两种情况,我把在调用TxEvent构造函数的-1设置为null,这样就会执行persist()(直接插入,不会进行对比),在修改的过程中我发现,eclipseLink支持在主键策略为IDENTITY时,也支持oracle,条件是你必须在数据库中创建一个它的默认序列(SEQ_GEN_IDENTITY),当然也可以使用自定义的序列,只需要在后面加上@SequenceGenerator,不必修改strategy的值。这样就解决上面的情况。
   
   解决之后,我非常疑惑你们在new TxEvent时为什么要设置surrogateId=-1,而不是null。
   -1时就会调用merge方法进行对比,影响了性能,而且没必要啊。
   我现在就想知道你们为什么要用-1????
   
   
   关于EntityManager [https://blog.csdn.net/j080624/article/details/78751411](url)

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services