现在我要对2个表进行插入,先插入了第一张表,用第一张表执行的结果对第二个表进行插入,可以第一个成功了,但是第二个失败了,怎么处理?
现在的我想做的是2张表要么一起插入成功,要么第一张插入成功了,第二个失败了,就把第一个回滚
看你用的是什么ORM,不过原理都是是类似的,你可以手动参与,
sqlSession = sqlSessionFactory.openSession(); //开始
id = lightControlMapper.insert(lightControl);
LightResult lr = new LightResult();
lr.setLightID(Integer.valueOf(entityID));
lr.setResult("updating");
lr.setCreateTime(new Timestamp(System.currentTimeMillis()));
lr.setControlType("setAutoMode");
lr.setData(lighting_status);
lr.setLightControlID(lightControl.getId());
lightResultMapper.insert(lr);
Destination destination = new ActiveMQQueue(mk_light_control);
jmsTemplate.convertAndSend(destination, String.valueOf(id));
sqlSession.commit(); //结束
这里我用的是mybatis的手动控制,你看下,我也是先插第一张表,再通过第一张表自动生成的ID,来插入第二张表,如果第一张表失败了,事务就会回滚
hibernate也应该是类似 的,我已经很久没用了
try{
事务开始
逻辑代码
事务提交
}catch{
事务回滚
}
可以在业务层进行事务控制---@Transaction
你可以把这两个步骤写在同一个service方法里,然后controller调用service,某个步骤失败后抛出RuntimeException便会回滚,前提是你需要在spring里配置好事务
嗯 ,错了
<aop:config>
<aop:pointcut expression="execution(* com.login.serviceImpl.WXServiceImpl..*.*(..))" id="pointcut2"/>
<aop:pointcut expression="execution(* com.login.serviceImpl.LoginServiceImpl..*.*(..))" id="pointcut"/>
<aop:advisor advice-ref="trAdvice" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="trAdvice" pointcut-ref="pointcut2"/>
</aop:config>
我配置的是service实现类,可以写成service接口,上面说错了,是service实现类或service接口起名用insert开头匹配insert*,实现公用一个事务,达到错误回滚
在ServiceImpl层你执行的那个方法外面也就是@override下面加上@Transactional
是ssm项目吗?,spring的配置里有
<tx:advice id="trAdvice" transaction-manager="transactionManager">
<!-- propagation事务的传播行为
isolation 事物的隔离级别
-->
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="do*" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
方法起名字以insert 开头,公用一个事务,把两个insert语句放到dao的同一个方法里
在dao接口加@Transaction