如何在Mule插入大量记录期间发生错误时回滚数据库更改?

时间:2017-02-14 13:56:50

标签: mysql database mule mule-studio anypoint-studio

我有以下json文件

[
    {
         "id": 1,
         "name": "Ramesh",
         "designation": "SE",
         "salary": 25000.00
    },
    {
         "id": 2,
         "name": "Anjali",
         "designation": "SE",
         "salary": 20000.00
    },
    {
         "id": 2,
         "name": "Harrish",
         "designation": "PM",
         "salary": 120000.00
    },
    {
         "id": 4,
         "name": "Rahul",
         "designation": "TA",
         "salary": 150000.00
    }
]

这里我要插入所有记录或不插入任何记录。表示所有四条记录都将被插入到员工数据库中,或者上面都没有。但是在这里你可以看到第三条记录有重复的id 2,因为第二条记录的id保持相同的id,当我运行下面的mule应用程序MySQLIntegrityConstraintViolationException时会发生错误但是前两条记录被插入到DB中错误出现在3号记录中。但是我想要的是防止插入记录或回滚更改,如果所有记录都没有插入到DB中(意味着任何错误介于其间)。

下面是我的mule xml配置文件,用于将json数据插入到DB中:

<sub-flow name="insert-fulltime-employee-details-subflow">
        <dw:transform-message metadata:id="35bfe913-8de7-4b3c-9ba9-98f375a2873e" doc:name="Transform Message">
            <dw:input-payload mimeType="application/json"/>
            <dw:set-payload><![CDATA[%dw 1.0
%output application/java
---
payload map ((payload01 , indexOfPayload01) -> {
    id: payload01.id,
    name: payload01.name,
    designation: payload01.designation,
    salary: payload01.salary
})]]></dw:set-payload>
        </dw:transform-message>
        <foreach doc:name="For Each">
            <db:insert config-ref="MySQL_Configuration" doc:name="Database-Insert">
                <db:parameterized-query><![CDATA[insert into fulltime_employee values (#[payload.id], #[payload.name], #[payload.designation], #[payload.salary])]]></db:parameterized-query>
            </db:insert>
        </foreach>
        <set-payload value="{&quot;message&quot;: &quot;All data successfully inserted into database&quot;}" mimeType="application/json" doc:name="Set Payload"/>
</sub-flow>

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

将必须回滚的块包装在“事务范围”中。如下所示,

<transactional action="ALWAYS_BEGIN" doc:name="Transactional">
<db:insert config-ref="MySQL_Configuration" doc:name="Database-Insert">
                <db:parameterized-query><![CDATA[insert into fulltime_employee values (#[payload.id], #[payload.name], #[payload.designation], #[payload.salary])]]></db:parameterized-query>
            </db:insert>
</transactional>