package cn.itcast.test;

import cn.itcast.dao.CustomerDao;
import cn.itcast.dao.LinkManDao;
import cn.itcast.domain.Customer;
import cn.itcast.domain.LinkMan;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class OneToManyTest {

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private LinkManDao linkManDao;

    /**
     * 保存一个客户，存入一个联系人
     */
    @Test
    @Transactional
    @Rollback(value = false)//设置不自动回滚
    public void testAdd(){
        //创建一个客户，创建一个联系人
        Customer customer = new Customer();
        customer.setCustName("张三");
        LinkMan linkMan = new LinkMan();
        linkMan.setLkmName("张张三");

        /**
         * 配置了客户到联系人之间的关系
         *      从客户的角度上，发送两条insert语句，发送一条更新的数据(更新外检)
         */
        customer.getLinkMans().add(linkMan);

        customerDao.save(customer);
        linkManDao.save(linkMan);
    }
    @Test
    @Transactional
    @Rollback(value = false)//设置不自动回滚
    public void testAdd1(){
        //创建一个客户，创建一个联系人
        Customer customer = new Customer();
        customer.setCustName("张三");
        LinkMan linkMan = new LinkMan();
        linkMan.setLkmName("张张三");

        /**
         * 配置了联系人到客户之间的关系
         *      发送了两条Insert语句
         */
        linkMan.setCustomer(customer);
        customerDao.save(customer);
        linkManDao.save(linkMan);
    }

    @Test
    @Transactional
    @Rollback(value = false)//设置不自动回滚
    public void testAdd2(){
        //创建一个客户，创建一个联系人
        Customer customer = new Customer();
        customer.setCustName("张三");
        LinkMan linkMan = new LinkMan();
        linkMan.setLkmName("张张三");

        /**
         * 在一的一放弃维护权
         */
        linkMan.setCustomer(customer);
        customer.getLinkMans().add(linkMan);

        customerDao.save(customer);
        linkManDao.save(linkMan);
    }

    /**
     * 级联添加
     */
    @Test
    @Transactional
    @Rollback(value = false)
    public void testCascadeAdd(){
        //创建一个客户，创建一个联系人
        Customer customer = new Customer();
        customer.setCustName("张三");
        LinkMan linkMan = new LinkMan();
        linkMan.setLkmName("张张三");

        linkMan.setCustomer(customer);
        customer.getLinkMans().add(linkMan);

        customerDao.save(customer);

    }

    /**
     * 级联删除
     */
    @Test
    @Transactional
    @Rollback(value = false)
    public void testCascadeRemove(){
        Customer customer = customerDao.findOne(1l);
        customerDao.delete(customer);
    }

}
