java中的事务(二)

package com.leqi.manage.service;

import com.leqi.manage.model.Customer;
import com.dakun.jianzhong.utils.AbstractService;
import com.leqi.manage.mapper.CustomerMapper;
import com.leqi.manage.model.CustomerNature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

/**
 * Created by liuqiulan on Fri Jun 08 17:29:27 CST 2018.
 * @author liuqiulan
 */
@Service
@Transactional(rollbackFor = Exception.class) //每一个方法都是一个事务
public class CustomerService extends AbstractService<Customer> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private CustomerNatureService customerNatureService;

    /**
     * 编辑客户信息
     */
    public Customer saveOrUpdate(Customer customer) {//但是包裹在这个方法里了,就包装成一个事务了,任意错误发生都会回滚每一个原子事务
        //客户信息更新
        this.update(customer);//原子事务
        //中间表信息更新
        //客户性质ids
        String[] ids = customer.getCompanyNatures().split(",");
        CustomerNature customerNature = new CustomerNature();
        customerNature.setCustomerId(customer.getId());
        customerNatureService.deletObj(customerNature);//原子事务
        for (String id : ids) {
            customerNature.setNature(Byte.valueOf(id));
            customerNatureService.save(customerNature);//原子事务
            customerNature.setId(null);
        }
        return customer;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34638435/article/details/80692158