Java Code Examples for org.apache.ibatis.session.SqlSession#rollback()

The following examples show how to use org.apache.ibatis.session.SqlSession#rollback() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestBasicAble.java    From tk-mybatis with MIT License 6 votes vote down vote up
/**
 * 新增
 */
@Test
public void testInsert() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        UserInfoAbleMapper mapper = sqlSession.getMapper(UserInfoAbleMapper.class);
        UserInfoAble userInfo = new UserInfoAble();
        userInfo.setUsername("abel533");
        userInfo.setPassword("123456");
        userInfo.setUsertype("2");
        userInfo.setEmail("[email protected]");//insert=false

        Assert.assertEquals(1, mapper.insert(userInfo));

        Assert.assertNotNull(userInfo.getId());
        Assert.assertEquals(6, (int) userInfo.getId());

        userInfo = mapper.selectByPrimaryKey(userInfo.getId());
        //email没有插入
        Assert.assertNull(userInfo.getEmail());
    } finally {
        sqlSession.rollback();
        sqlSession.close();
    }
}
 
Example 2
Source File: TestDeleteByExample.java    From Mapper with MIT License 6 votes vote down vote up
@Test
public void testDeleteByExample3() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
        CountryExample example = new CountryExample();
        example.createCriteria().andCountrynameLike("A%");
        example.or().andIdGreaterThan(100);
        example.setDistinct(true);
        int count = mapper.deleteByExample(example);
        //查询总数
        Assert.assertEquals(true, count > 83);
    } finally {
        sqlSession.rollback();
        sqlSession.close();
    }
}
 
Example 3
Source File: TestUpdateByExample.java    From tk-mybatis with MIT License 6 votes vote down vote up
@Test
public void testUpdateByExample2() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
        Country country = new Country();
        country.setCountryname("天朝");
        country.setId(1000);


        CountryExample example = new CountryExample();
        example.createCriteria().andIdEqualTo(35);
        int count = mapper.updateByExample(country, example);
        Assert.assertEquals(1, count);

        example = new CountryExample();
        example.createCriteria().andCountrycodeIsNull();
        count = mapper.selectCountByExample(example);
        Assert.assertEquals(1, count);
    } finally {
        sqlSession.rollback();
        sqlSession.close();
    }
}
 
Example 4
Source File: TestUpdateByExample.java    From Mapper with MIT License 6 votes vote down vote up
@Test
public void testUpdateByExample2() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
        Country country = new Country();
        country.setCountryname("天朝");
        country.setId(1000);


        CountryExample example = new CountryExample();
        example.createCriteria().andIdEqualTo(35);
        int count = mapper.updateByExample(country, example);
        Assert.assertEquals(1, count);

        example = new CountryExample();
        example.createCriteria().andCountrycodeIsNull();
        count = mapper.selectCountByExample(example);
        Assert.assertEquals(1, count);
    } finally {
        sqlSession.rollback();
        sqlSession.close();
    }
}
 
Example 5
Source File: BindingTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInsertAuthorWithSelectKeyAndDynamicParams() {
  SqlSession session = sqlSessionFactory.openSession();
  try {
    BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class);
    Author author = new Author(-1, "cbegin", "******", "[email protected]", "N/A", Section.NEWS);
    int rows = mapper.insertAuthorDynamic(author);
    assertEquals(1, rows);
    assertFalse(-1 == author.getId()); // id must be autogenerated
    Author author2 = mapper.selectAuthor(author.getId());
    assertNotNull(author2);
    assertEquals(author.getEmail(), author2.getEmail());
    session.rollback();
  } finally {
    session.close();
  }
}
 
Example 6
Source File: TestBasicAble.java    From tk-mybatis with MIT License 6 votes vote down vote up
/**
 * 根据主键全更新
 */
@Test
public void testUpdateByPrimaryKey() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        UserInfoAbleMapper mapper = sqlSession.getMapper(UserInfoAbleMapper.class);
        UserInfoAble userInfo = mapper.selectByPrimaryKey(2);
        Assert.assertNotNull(userInfo);
        userInfo.setUsertype(null);
        userInfo.setEmail("[email protected]");
        userInfo.setAddress("这个地址不会更新进去");//update=false
        //不会更新username
        Assert.assertEquals(1, mapper.updateByPrimaryKey(userInfo));

        userInfo = mapper.selectByPrimaryKey(userInfo);
        Assert.assertNull(userInfo.getUsertype());
        Assert.assertNotEquals("这个地址不会更新进去", userInfo.getAddress());
        Assert.assertEquals("[email protected]", userInfo.getEmail());
    } finally {
        sqlSession.rollback();
        sqlSession.close();
    }
}
 
Example 7
Source File: TestLogicDelete.java    From Mapper with MIT License 6 votes vote down vote up
@Test
public void testUpdateByExample() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        TbUserLogicDeleteMapper logicDeleteMapper = sqlSession.getMapper(TbUserLogicDeleteMapper.class);

        // username为test的有两条  一条标记为已删除
        Example example = new Example(TbUserLogicDelete.class);
        example.createCriteria().andEqualTo("username", "test");

        TbUserLogicDelete tbUserLogicDelete = new TbUserLogicDelete();
        tbUserLogicDelete.setUsername("123");
        logicDeleteMapper.updateByExample(tbUserLogicDelete, example);

        example.clear();
        example.createCriteria().andEqualTo("username", "123");
        List<TbUserLogicDelete> list = logicDeleteMapper.selectByExample(example);
        Assert.assertEquals(1, list.size());

        Assert.assertNull(list.get(0).getPassword());
    } finally {
        sqlSession.rollback();
        sqlSession.close();
    }
}
 
Example 8
Source File: TestDeleteByExample.java    From Mapper with MIT License 6 votes vote down vote up
@Test
public void testDeleteByExample2() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
        Example example = new Example(Country.class);
        example.createCriteria().andLike("countryname", "A%");
        example.or().andGreaterThan("id", 100);
        example.setDistinct(true);
        int count = mapper.deleteByExample(example);
        //查询总数
        Assert.assertEquals(true, count > 83);
    } finally {
        sqlSession.rollback();
        sqlSession.close();
    }
}
 
Example 9
Source File: TestLogicDelete.java    From Mapper with MIT License 6 votes vote down vote up
@Test
public void testInsert() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        TbUserLogicDeleteMapper logicDeleteMapper = sqlSession.getMapper(TbUserLogicDeleteMapper.class);

        TbUserLogicDelete tbUserLogicDelete = new TbUserLogicDelete();
        tbUserLogicDelete.setUsername("test111");
        logicDeleteMapper.insert(tbUserLogicDelete);

        TbUserMapper mapper = sqlSession.getMapper(TbUserMapper.class);
        TbUser tbUser = new TbUser();
        tbUser.setUsername("test222");
        mapper.insert(tbUser);

        Assert.assertEquals(1, mapper.selectCount(tbUser));

        TbUserLogicDelete tbUserLogicDelete1 = new TbUserLogicDelete();
        tbUserLogicDelete1.setUsername("test222");
        Assert.assertEquals(0, logicDeleteMapper.selectCount(tbUserLogicDelete1));

    } finally {
        sqlSession.rollback();
        sqlSession.close();
    }
}
 
Example 10
Source File: ComponentTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInsertNestedPasswordFieldOfComplexType() throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    //Create User
    User user = new User();
    user.setId(500000L);
    user.setPassword(new EncryptedString("secret"));
    user.setUsername("johnny" + Calendar.getInstance().getTimeInMillis());//random
    user.setAdministrator(true);

    sqlSession.insert("User.insert", user);

    //Retrieve User
    user = (User) sqlSession.selectOne("User.find", user.getId());

    assertNotNull(user.getId());

    sqlSession.rollback();
  } finally {
    sqlSession.close();
  }
}
 
Example 11
Source File: TestBasic.java    From Mapper with MIT License 6 votes vote down vote up
/**
 * 根据主键全更新
 */
@Test
public void testUpdateByPrimaryKey() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
        UserInfo userInfo = mapper.selectByPrimaryKey(2);
        Assert.assertNotNull(userInfo);
        userInfo.setUsertype(null);
        userInfo.setEmail("[email protected]");
        //不会更新username
        Assert.assertEquals(1, mapper.updateByPrimaryKey(userInfo));

        userInfo = mapper.selectByPrimaryKey(userInfo);
        Assert.assertNull(userInfo.getUsertype());
        Assert.assertEquals("[email protected]", userInfo.getEmail());
    } finally {
        sqlSession.rollback();
        sqlSession.close();
    }
}
 
Example 12
Source File: TestJDBC.java    From tk-mybatis with MIT License 5 votes vote down vote up
public void testJDBC() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        CountryJDBCMapper mapper = sqlSession.getMapper(CountryJDBCMapper.class);
        CountryJDBC country = new CountryJDBC();
        country.setId(1);
        country.setCountrycode("CN");
        country.setCountryname("China");
        Assert.assertEquals(1, mapper.insert(country));
        Assert.assertNotNull(country.getId());
    } finally {
        sqlSession.rollback();
        sqlSession.close();
    }
}
 
Example 13
Source File: TestLogicDelete.java    From Mapper with MIT License 5 votes vote down vote up
@Test
public void testExistsWithPrimaryKey() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        TbUserLogicDeleteMapper logicDeleteMapper = sqlSession.getMapper(TbUserLogicDeleteMapper.class);
        Assert.assertFalse(logicDeleteMapper.existsWithPrimaryKey(9));

        TbUserMapper mapper = sqlSession.getMapper(TbUserMapper.class);
        Assert.assertTrue(mapper.existsWithPrimaryKey(9));
    } finally {
        sqlSession.rollback();
        sqlSession.close();
    }
}
 
Example 14
Source File: TestDeleteByExample.java    From Mapper with MIT License 5 votes vote down vote up
@Test
public void testDeleteByExample() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
        Example example = new Example(Country.class);
        example.createCriteria().andGreaterThan("id", 100);
        int count = mapper.deleteByExample(example);
        //查询总数
        Assert.assertEquals(83, count);
    } finally {
        sqlSession.rollback();
        sqlSession.close();
    }
}
 
Example 15
Source File: ChatAction.java    From anychat with MIT License 5 votes vote down vote up
public static List<Chat> getGroupChatList(String toTypeId, int start, int pageSize) {
	if (StringUtil.stringIsNull(toTypeId)) {
		return null;
	}
	List<Chat> chatList = null;
	SqlSession sqlSession = null;
	try {
		sqlSession = MybatisManager.getSqlSession();
		ChatMapper chatMapper = sqlSession.getMapper(ChatMapper.class);
		ChatCriteria chatCriteria = new ChatCriteria();
		ChatCriteria.Criteria criteria = chatCriteria.createCriteria();
		criteria.andToTypeEqualTo((byte) ChatConfig.TO_TYPE_GROUP);

		criteria.andToTypeIdEqualTo(toTypeId);

		criteria.andChatStateEqualTo((byte) ChatConfig.CHAT_STATE_EXIST);
		chatCriteria.setLimitStart(start);
		chatCriteria.setPageSize(pageSize);
		chatCriteria.setOrderByClause("chat_create_time asc");

		chatList = chatMapper.selectByExample(chatCriteria);
		return chatList;
	} catch (Exception e) {
		if (sqlSession != null) {
			sqlSession.rollback();
		}
		MybatisManager.log.error("获取聊天异常", e);
		return null;
	} finally {
		if (sqlSession != null) {
			sqlSession.close();
		}
	}
}
 
Example 16
Source File: TestJDBC.java    From Mapper with MIT License 5 votes vote down vote up
public void testJDBC2() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        CountryJDBCMapper mapper = sqlSession.getMapper(CountryJDBCMapper.class);
        CountryJDBC country = new CountryJDBC();
        country.setId(1);
        country.setCountrycode("CN");
        country.setCountryname("China");
        Assert.assertEquals(1, mapper.insertSelective(country));
        Assert.assertNotNull(country.getId());
    } finally {
        sqlSession.rollback();
        sqlSession.close();
    }
}
 
Example 17
Source File: TestBasic.java    From Mapper with MIT License 5 votes vote down vote up
/**
 * 新增
 */
@Test
public void testInsert() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername("abel533");
        userInfo.setPassword("123456");
        userInfo.setUsertype("2");
        userInfo.setEmail("[email protected]");
        Collection collection = sqlSession.getConfiguration().getMappedStatements();
        for (Object o : collection) {
            if(o instanceof MappedStatement){
                MappedStatement ms = (MappedStatement) o;
                if (ms.getId().contains("UserInfoMapper.insert")) {
                    System.out.println(ms.getId());
                }
            }
        }

        Assert.assertEquals(1, mapper.insert(userInfo));

        Assert.assertNotNull(userInfo.getId());
        Assert.assertTrue((int) userInfo.getId() >= 6);

        Assert.assertEquals(1,mapper.deleteByPrimaryKey(userInfo));
    } finally {
        sqlSession.rollback();
        sqlSession.close();
    }
}
 
Example 18
Source File: SysUserMapperTest.java    From mybatis-action with Apache License 2.0 5 votes vote down vote up
@Test
public void testInsertUseGeneratedKeys() {
    SqlSession sqlSession = getSqlSession();

    try {
        SysUserMapper sysUserMapper = sqlSession.getMapper(SysUserMapper.class);

        SysUser sysUser = new SysUser();
        sysUser.setUserName("test1");
        sysUser.setUserPassword("123456");
        sysUser.setUserEmail("[email protected]");
        sysUser.setUserInfo("test info");
        // 正常情况下应该读入一张图片保存到byte数组中
        sysUser.setHeadImg(new byte[]{1, 2, 3});
        sysUser.setCreateTime(new Date());

        // 这里的返回值result是执行的SQL影响的行数
        int result = sysUserMapper.insertUseGeneratedKeys(sysUser);
        // 只插入1条数据
        Assert.assertEquals(1, result);
        // 因为id回写,所以id不为null
        Assert.assertNotNull(sysUser.getId());
    } finally {
        sqlSession.rollback();
        sqlSession.close();
    }
}
 
Example 19
Source File: ChatAction.java    From anychat with MIT License 4 votes vote down vote up
public static Chat createChat(String chatContent, int toType, String toTypeId, String fromUserId) {
	if (StringUtil.stringIsNull(chatContent) || StringUtil.stringIsNull(toTypeId) || StringUtil.stringIsNull(fromUserId)) {
		return null;
	}
	if (toType != ChatConfig.TO_TYPE_USER && toType != ChatConfig.TO_TYPE_GROUP) {
		return null;
	}
	Chat chat = new Chat();
	Date date = new Date();
	chat.setChatId(IdUtil.getUuid());
	chat.setChatCreateTime(date);
	chat.setChatContent(chatContent);
	chat.setFromUserId(fromUserId);
	chat.setToType((byte) toType);
	chat.setToTypeId(toTypeId);
	chat.setChatState((byte) ChatConfig.CHAT_STATE_EXIST);
	chat.setChatType((byte) ChatConfig.CHAT_TYPE_SEND);

	SqlSession sqlSession = null;
	try {
		sqlSession = MybatisManager.getSqlSession();
		ChatMapper chatMapper = sqlSession.getMapper(ChatMapper.class);
		int result = chatMapper.insert(chat);
		if (result == 0) {
			MybatisManager.log.warn("创建聊天内容失败");
			return null;
		}
		sqlSession.commit();
		return chat;
	} catch (Exception e) {
		if (sqlSession != null) {
			sqlSession.rollback();
		}
		MybatisManager.log.error("创建聊天内容异常", e);
		return null;
	} finally {
		if (sqlSession != null) {
			sqlSession.close();
		}
	}
}
 
Example 20
Source File: SchedulerActor.java    From Nickle-Scheduler with Apache License 2.0 4 votes vote down vote up
private void cycleSchedule(String msg) {
    log.info("开始扫描待调度任务");
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        NickleSchedulerTriggerMapper schedulerTriggerMapper = sqlSession.getMapper(NickleSchedulerTriggerMapper.class);
        NickleSchedulerLockMapper schedulerLockMapper = sqlSession.getMapper(NickleSchedulerLockMapper.class);
        //获取锁防止多个schduler同时获取到相同的任务
        schedulerLockMapper.lock(LOCK_NAME);
        //查询需要执行的任务
        QueryWrapper<NickleSchedulerTrigger> queryWrapper = new QueryWrapper<>();
        /**
         * 一次性获取到下一次待调度的trigger,按需要调度时间降序,获取条件(满足一条即可):
         * 1、触发器状态为STAND_BY且时间在当前时间+调度时间内
         * 2、触发器状态为ACQUIRED但更新时间小于一次性获取的时间+容错时间(为了防止调度器修改完状态后down机)
         */
        log.info("autocommit:{}", sqlSession.getConnection().getAutoCommit());
        queryWrapper.lambda()
                .and(qw -> qw.le(NickleSchedulerTrigger::getTriggerNextTime, System.currentTimeMillis())
                        .eq(NickleSchedulerTrigger::getTriggerStatus, STAND_BY))
                .or(qw1 -> qw1.and(qw2 -> qw2.eq(NickleSchedulerTrigger::getTriggerStatus, ACQUIRED)
                        .le(NickleSchedulerTrigger::getTriggerUpdateTime, System.currentTimeMillis() - (SCHEDULE_TIME + MISTAKE_TIME))))
                .orderByDesc(NickleSchedulerTrigger::getTriggerNextTime);
        //分页取
        Page<NickleSchedulerTrigger> triggerPage = new Page<>(1, SCHEDULE_TRIGGER_NUM);
        List<NickleSchedulerTrigger> nickleSchedulerTriggers = schedulerTriggerMapper.selectPage(triggerPage, queryWrapper).getRecords();
        log.info("需要调度的触发器:{}", nickleSchedulerTriggers);
        if (ObjectUtils.isEmpty(nickleSchedulerTriggers)) {
            log.info("结束扫描待调度任务,无调度触发器");
            nextSchedule();
            return;
        }
        //修改trigger状态后释放锁
        modifyTriggerStatus(nickleSchedulerTriggers, sqlSession);
        //添加任务
        addRunJob(nickleSchedulerTriggers);
        //触发器不为空继续调度
        getSelf().tell(SCHEDULE, getSelf());
    } catch (Exception e) {
        sqlSession.rollback();
        e.printStackTrace();
        log.error("调度发生错误:{}", e.getMessage());
    } finally {
        sqlSession.close();
    }
    log.info("结束扫描待调度任务");
    nextSchedule();
}