package com.xjrsoft.xjrsoftboot;


import cn.hutool.db.Entity;
import cn.hutool.db.Session;
import com.xjrsoft.XjrSoftApplication;
import com.xjrsoft.common.utils.DatasourceUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * dynamic datasource 多数据源 事务测试
 *
 * @Author: tzx
 * @Date: 2022/10/20 10:25
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = XjrSoftApplication.class)
public class DynamicDatasourceTest {

    @Test
    public void testMultiTask() throws SQLException {

        DataSource datasourceMaster = DatasourceUtil.getDatasourceMaster();

        DataSource dataSourceSlave = DatasourceUtil.getDataSource("1");

        Session masterSession = Session.create(datasourceMaster);
        masterSession.beginTransaction();
        Entity masterEntity = Entity.create("xjr_user").set("id", 123124L).set("name", "事务测试").set("department_id",1123123L).set("delete_mark",1).set("enabled_mark",1);
        masterSession.insert(masterEntity);

        Session slaveSession = Session.create(dataSourceSlave);
        slaveSession.beginTransaction();
        Entity slaveEntityEntity = Entity.create("xjr_user").set("id", 123124L).set("name", "事务测试").set("delete_mark",1).set("enabled_mark",1);
        slaveSession.insert(slaveEntityEntity);

        try {
            masterSession.commit();
            slaveSession.commit();
        }
        catch(Exception e) {
            masterSession.rollback();
            slaveSession.rollback();
        }


//        Db masterDb = DbUtil.use(datasourceMaster);
//
//
//        Entity masterEntity = Entity.create("xjr_user").set("id", 123124L).set("name", "事务测试").set("department_id",1123123L).set("delete_mark",1).set("enabled_mark",1);
//        masterDb.insert(masterEntity);
//
//
//        Db slaveDb = DbUtil.use(dataSourceSlave);
//
//        Entity slaveEntity = Entity.create("xjr_user").set("id", 123124L).set("name", "事务测试").set("delete_mark",1).set("enabled_mark",1);
//        slaveDb.insert(slaveEntity);

        throw new SQLException("报错");

    }
}
