public static boolean deleteUserGroupById(String userGroupId) { SqlSession sqlSession = null; try { sqlSession = MybatisManager.getSqlSession(); UserGroupMapper userGroupMapper = sqlSession.getMapper(UserGroupMapper.class); int result = userGroupMapper.deleteByPrimaryKey(userGroupId); if (result == 0) { MybatisManager.log.warn("删除用户组异常"); return false; } sqlSession.commit(); } catch (Exception e) { if (sqlSession != null) { sqlSession.rollback(); } MybatisManager.log.error("删除用户组异常", e); return false; } finally { if (sqlSession != null) { sqlSession.close(); } } return true; }
/** * 测试 selectOneByExample */ @Test public void testSelectOneByExample() throws IOException, XMLParserException, InvalidConfigurationException, InterruptedException, SQLException { MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/SelectOneByExamplePlugin/mybatis-generator.xml"); tool.generate(new AbstractShellCallback() { @Override public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper"))); ObjectUtil TbExample = new ObjectUtil(loader, packagz + ".TbExample"); ObjectUtil criteria = new ObjectUtil(TbExample.invoke("createCriteria")); criteria.invoke("andIdEqualTo", 1l); // sql String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "selectOneByExample", TbExample.getObject()); Assert.assertEquals(sql, "select id, field1, field2 from tb WHERE ( id = '1' ) limit 1"); Object result = tbMapper.invoke("selectOneByExample", TbExample.getObject()); ObjectUtil Tb = new ObjectUtil(result); Assert.assertEquals(Tb.get("id"), 1l); Assert.assertEquals(Tb.get("field1"), "fd1"); Assert.assertNull(Tb.get("field2")); } }); }
@Override public Channel getChannel(int id) { try (SqlSession sqlSession = dbManager.getSqlSession()) { ChannelMapper mapper = sqlSession.getMapper(ChannelMapper.class); ChannelEntity channelEntity = mapper.selectByPrimaryKey(id); if (channelEntity == null) { return null; } Channel channel = DozerMapperUtil.map(channelEntity, Channel.class); channel.setLink("/channel/".concat(channel.getSlug())); channel.setColor("#".concat(Integer.toHexString(channel.getMainColor()))); return channel; } }
/** * 主要测试删除 */ // @Test public void testDelete() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { UserInfoMapMapper mapper = sqlSession.getMapper(UserInfoMapMapper.class); //查询总数 Assert.assertEquals(5, mapper.selectCount(new UserInfoMap())); //查询100 UserInfoMap userInfoMap = mapper.selectByPrimaryKey(1); //根据主键删除 Assert.assertEquals(1, mapper.deleteByPrimaryKey(1)); //查询总数 Assert.assertEquals(4, mapper.selectCount(new UserInfoMap())); //插入 Assert.assertEquals(1, mapper.insert(userInfoMap)); } finally { sqlSession.close(); } }
@Override public PropertyBean getNewProperty() { SqlSession sqlSession = MybatisSqlSession.getSqlSession(); PropertyBean propertyBean = new PropertyBean(); try { PropertyDao propertyDao = sqlSession.getMapper(PropertyDao.class); propertyBean = propertyDao.getNewProperty(); } catch (Exception e) { // e.printStackTrace(); // logger.error(e.getStackTrace()); } finally { sqlSession.close(); } return propertyBean; }
/** * 根据主键全更新 */ // @Test public void testUpdateByPrimaryKey() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { UserInfoMapMapper mapper = sqlSession.getMapper(UserInfoMapMapper.class); UserInfoMap userInfoMap = mapper.selectByPrimaryKey(2); Assert.assertNotNull(userInfoMap); userInfoMap.setUserType(null); userInfoMap.setRealName("liuzh"); //不会更新user_type Assert.assertEquals(1, mapper.updateByPrimaryKey(userInfoMap)); userInfoMap = mapper.selectByPrimaryKey(userInfoMap); Assert.assertNull(userInfoMap.getUserType()); Assert.assertEquals("liuzh",userInfoMap.getRealName()); } finally { sqlSession.close(); } }
/** * 继承类可以使用,但多出来的属性无效 */ @Test public void testDynamicSelectNotFoundKeyProperties() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { CountryMapper mapper = sqlSession.getMapper(CountryMapper.class); //根据主键删除 Assert.assertEquals(183, mapper.select(new Key()).size()); Key key = new Key(); key.setCountrycode("CN"); key.setCountrytel("+86"); Assert.assertEquals(1, mapper.select(key).size()); } finally { sqlSession.close(); } }
@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(); } }
private CMSEvent getRelease(CMSEventRecord record) { CMSEvent event; try (SqlSession session = sqlsf.openSession()) { DJMapper djMapper = session.getMapper(DJMapper.class); CmsRelease release = djMapper.getReleaseById(record.getSourcePk()); if (release != null) { long rfcCount = djMapper.countCiRfcByReleaseId(release.getReleaseId()); release.setCiRfcCount(rfcCount); } event = new CMSEvent(); event.setEventId(record.getEventId()); event.addHeaders("source", "release"); event.addHeaders("clazzName", "Release"); event.addHeaders("action", record.getEventType()); event.addHeaders("sourceId", String.valueOf(record.getSourcePk())); event.setPayload(release); } return event; }
/** * 测试关联生成的方法和常量 */ @Test public void testOtherMethods() throws IOException, XMLParserException, InvalidConfigurationException, InterruptedException, SQLException { MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/LogicalDeletePlugin/mybatis-generator.xml"); tool.generate(new AbstractShellCallback() { @Override public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception{ ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper"))); ObjectUtil tbExample = new ObjectUtil(loader, packagz + ".TbExample"); ObjectUtil criteria = new ObjectUtil(tbExample.invoke("createCriteria")); criteria.invoke("andDeleted", true); criteria.invoke("andIdEqualTo", 3l); // 验证sql String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "selectByExample", tbExample.getObject()); Assert.assertEquals(sql, "select id, del_flag, and_logical_deleted, ts_1, ts_3, ts_4 from tb WHERE ( del_flag = '1' and id = '3' )"); // 验证执行 Object result = tbMapper.invoke("selectByExample", tbExample.getObject()); Assert.assertEquals(((List)result).size(), 1); } }); }
/** * 主要测试删除 */ @Test public void testDynamicDelete() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { UserLoginMapper mapper = sqlSession.getMapper(UserLoginMapper.class); //查询总数 Assert.assertEquals(10, mapper.selectCount(new UserLogin())); UserLogin userLogin = new UserLogin(); userLogin.setUsername("test1"); List<UserLogin> userLoginList = mapper.select(userLogin); //批量删除 Assert.assertEquals(userLoginList.size(), mapper.delete(userLogin)); //循环插入 for (int i = 0; i < userLoginList.size(); i++) { Assert.assertEquals(1, mapper.insert(userLoginList.get(i))); Assert.assertEquals(i + 1, (int) userLoginList.get(i).getLogid()); } //查询总数 Assert.assertEquals(10, mapper.selectCount(new UserLogin())); } finally { sqlSession.close(); } }
/** * 根据查询条件进行查询 */ @Test public void testDynamicSelect() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { CountryTMapper mapper = sqlSession.getMapper(CountryTMapper.class); CountryT country = new CountryT(); country.setId(174); country.setCountrycode("US"); List<CountryT> countryList = mapper.select(country); Assert.assertEquals(1, countryList.size()); Assert.assertEquals(true, countryList.get(0).getId() == 174); Assert.assertNotNull(countryList.get(0).getCountryname()); Assert.assertNull(countryList.get(0).getCountrycode()); } finally { sqlSession.close(); } }
/** * 循环标签 测试 */ public static void main(String[] args) { // 加载配置文件 InputStream in = CircularLabelsTest.class.getClassLoader().getResourceAsStream("mysql-config.xml"); MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder(); SqlSessionFactory sessionFactory = mf.build(in); SqlSession session = sessionFactory.openSession(); UserMapper userMapper = session.getMapper(UserMapper.class); Page<User> page = new Page<>(1, 6); List<User> users = userMapper.forSelect(page, Arrays.asList("1", "2", "3")); System.out.println(users.toString()); System.out.println(page); User user = new User(); user.setId(1L); User users1 = userMapper.selectOne(user); System.out.println(users1); TestMapper mapper = session.getMapper(TestMapper.class); Test test = new Test(); test.setCreateTime(new Date()); test.setType("11111"); mapper.insert(test); session.rollback(); }
/** * <p> * 事务测试 * </p> */ public static void main(String[] args) { /* * 加载配置文件 */ InputStream in = TransactionalTest.class.getClassLoader().getResourceAsStream("mysql-config.xml"); MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder(); SqlSessionFactory sessionFactory = mf.build(in); SqlSession sqlSession = sessionFactory.openSession(); /** * 插入 */ UserMapper userMapper = sqlSession.getMapper(UserMapper.class); int rlt = userMapper.insert(new User(IdWorker.getId(), "1", 1, 1)); System.err.println("--------- insertInjector --------- " + rlt); //session.commit(); sqlSession.rollback(); sqlSession.close(); }
/** * 查询不存在的结果 */ @Test public void testDynamicSelectZero() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { CountryMapper mapper = sqlSession.getMapper(CountryMapper.class); Country country = new Country(); country.setCountrycode("CN"); country.setCountryname("天朝");//实际上是 China Country result = mapper.selectOne(country); Assert.assertNull(result); } finally { sqlSession.close(); } }
/** * 通用selected方法查询 * 反射方式执行mybatis Mapper接口的代理实现对象的方法, * * @param method ISelectDao中定义的方法名 * @param params ISelectDao方法中的参数 * @return * @throws InvocationTargetException * @throws IllegalAccessException * @throws NoSuchMethodException */ @Override public List<Map<String, String>> commonSelect(String method, HashMap<String, String> params) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { SqlSession sqlSession = factory.openSession(); ISelectDao mapper = sqlSession.getMapper(ISelectDao.class); Method m = mapper.getClass().getMethod(method, new Class[]{Map.class}); Object result = m.invoke(mapper, params); /*此处强转获取类型 mybatis的interface中的的select查询返回值都必须是List mybatis的mapper.xml中的的select查询返回值都必须是Map Mybatis会自动根据返回值是多条纪录还是单条纪录,来返回值*/ return (List<Map<String, String>>) result; }
public static Token getTokenById(String tokenId) { if (StringUtil.stringIsNull(tokenId)) { return null; } SqlSession sqlSession = null; try { sqlSession = MybatisManager.getSqlSession(); TokenMapper tokenMapper = sqlSession.getMapper(TokenMapper.class); Token token = tokenMapper.selectByPrimaryKey(tokenId); return token; } catch (Exception e) { if (sqlSession != null) { sqlSession.rollback(); } MybatisManager.log.error("获取token异常", e); return null; } finally { if (sqlSession != null) { sqlSession.close(); } } }
/** * 主要测试删除 */ @Test public void testDelete() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class); //查询总数 Assert.assertEquals(5, mapper.selectCount(new UserInfo())); //查询100 UserInfo userInfo = mapper.selectByPrimaryKey(1); //根据主键删除 Assert.assertEquals(1, mapper.deleteByPrimaryKey(1)); //查询总数 Assert.assertEquals(4, mapper.selectCount(new UserInfo())); //插入 Assert.assertEquals(1, mapper.insert(userInfo)); } finally { sqlSession.rollback(); sqlSession.close(); } }
/** * 查询不存在的结果 */ @Test public void testDynamicSelectZero() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { CountryMapper mapper = sqlSession.getMapper(CountryMapper.class); Country country = new Country(); country.setCountrycode("CN"); country.setCountryname("天朝");//实际上是 China List<Country> countryList = mapper.select(country); Assert.assertEquals(0, countryList.size()); } finally { sqlSession.close(); } }
public static List<User> getUserList(String userGroupId, boolean isRecursion, boolean isUserGroupIsNull, int userState, int userSex, int userRole, String userGroupTopId, String userName, String userCreateTimeGreaterThan, String userCreateTimeLessThan, String userUpdateTimeGreaterThan, String userUpdateTimeLessThan) { SqlSession sqlSession = null; List<User> userListAll = new ArrayList<>(); try { sqlSession = MybatisManager.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); UserGroupMapper userGroupMapper = sqlSession.getMapper(UserGroupMapper.class); getUserListRecursion(userListAll, userGroupId, userState, userSex, userRole, userGroupMapper, userMapper, isRecursion, userGroupTopId, isUserGroupIsNull, userName, userCreateTimeGreaterThan, userCreateTimeLessThan, userUpdateTimeGreaterThan, userUpdateTimeLessThan); return userListAll; } catch (Exception e) { if (sqlSession != null) { sqlSession.rollback(); } MybatisManager.log.error("获取用户列表异常", e); return null; } finally { if (sqlSession != null) { sqlSession.close(); } } }
/** * 查询全部 */ @Test public void testDynamicSelectPage() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { CountryMapper mapper = sqlSession.getMapper(CountryMapper.class); Country country = new Country(); country.setCountrycode("US"); List<Country> countryList = mapper.selectPage(country, 0, 10); //查询总数 Assert.assertEquals(1, countryList.size()); countryList = mapper.selectPage(null, 100, 10); //查询总数 Assert.assertEquals(10, countryList.size()); } finally { sqlSession.close(); } }
@Override public boolean deleteUsermeta(UsermetaEntity usermetaEntity) { try (SqlSession sqlSession = dbManager.getSqlSession()){ UserMetaMapper mapper = sqlSession.getMapper(UserMetaMapper.class); UsermetaEntityExample entityExample = UsermetaEntityExample.builder().oredCriteria(new ArrayList<>()).build(); entityExample.or().andMetaKeyEqualTo(usermetaEntity.getMetaKey()).andUidEqualTo(usermetaEntity.getUid()).andMetaValueEqualTo(usermetaEntity.getMetaValue()); int result = mapper.deleteByExample(entityExample); sqlSession.commit(); return result > 0; } }
@Override public int selectPraiseByUseridAndPraiseUserid(Map praiseMap) throws Exception { SqlSession os = sqlSessionFactory.openSession(); int is_praise = os.selectOne("selectPraiseByUseridAndPraiseUserid", praiseMap); os.close(); return is_praise; }
private boolean metaExist(long userId, String key, String value) { try (SqlSession sqlSession = dbManager.getSqlSession()) { UserMetaMapper mapper = sqlSession.getMapper(UserMetaMapper.class); UsermetaEntityExample usermetaEntityExample = UsermetaEntityExample.builder().oredCriteria(new ArrayList<>()).build(); usermetaEntityExample.or().andMetaKeyEqualTo(key).andUidEqualTo(userId).andMetaValueEqualTo(value); return mapper.countByExample(usermetaEntityExample) > 0; } }
@Override protected HealthCheck.Result check() throws Exception { try (SqlSession session = sessionFactory.openSession(); CallableStatement callableStatement = session.getConnection().prepareCall(validationQuery)) { callableStatement.execute(); } return Result.healthy(); }
/** * 测试andIf方法 */ @Test public void testAndIf() throws IOException, XMLParserException, InvalidConfigurationException, InterruptedException, SQLException { MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/ExampleEnhancedPlugin/mybatis-generator.xml"); tool.generate(new AbstractShellCallback() { @Override public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) { try { ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper"))); // 1. andIf true ObjectUtil tbExample = new ObjectUtil(loader, packagz + ".TbExample"); ObjectUtil tbExampleCriteria = new ObjectUtil(tbExample.invoke("createCriteria")); // 代理实现接口 Object criteriaAdd = Proxy.newProxyInstance(loader, new Class[]{ loader.loadClass(packagz + ".TbExample$Criteria$ICriteriaAdd") }, new TestInvocationHandler()); Method method = tbExampleCriteria.getMethods("andIf").get(0); method.invoke(tbExampleCriteria.getObject(), true, criteriaAdd); String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "selectByExample", tbExample.getObject()); Assert.assertEquals(sql, "select id, field1 from tb WHERE ( id = '5' )"); // 2. andIf false ObjectUtil tbExample1 = new ObjectUtil(loader, packagz + ".TbExample"); ObjectUtil tbExampleCriteria1 = new ObjectUtil(tbExample1.invoke("createCriteria")); method = tbExampleCriteria1.getMethods("andIf").get(0); method.invoke(tbExampleCriteria1.getObject(), false, criteriaAdd); sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "selectByExample", tbExample1.getObject()); Assert.assertEquals(sql, "select id, field1 from tb"); } catch (Exception e) { e.printStackTrace(); Assert.assertTrue(false); } } }); }
@Override public int deleteCollect(Map collectid) throws Exception { SqlSession os = sqlSessionFactory.openSession(); int i = os.delete("deleteCollect",collectid); os.close(); return i; }
@Override public TaskMonitorService getTaskMonitorService() { SqlSession session = this.sessionManager; TaskMonitorServiceImpl taskMonitorServiceImpl = new TaskMonitorServiceImpl(this, session.getMapper(TaskMonitorMapper.class)); return taskMonitorServiceImpl; }
public User GetUser() { SqlSessionFactory mySqlSessionFactory = MyBatisHelper.getSqlSessionFactory(); SqlSession session = mySqlSessionFactory.openSession(); try { UserMapper userMapper = session.getMapper(UserMapper.class); User user = userMapper.getUser(1); return user; } finally { session.close(); } }
@Override public void addTask(TaskBean taskBean) { SqlSession sqlSession = MybatisSqlSession.getSqlSession(); try { TaskDao taskDao = sqlSession.getMapper(TaskDao.class); taskDao.addTask(taskBean); sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); logger.error(e.getStackTrace()); } finally { sqlSession.close(); } }
/** * 查询 */ // @Test public void testSelect() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { UserInfoMapMapper mapper = sqlSession.getMapper(UserInfoMapMapper.class); UserInfoMap userInfoMap = new UserInfoMap(); userInfoMap.setUserType("1"); List<UserInfoMap> UserInfoMaps = mapper.select(userInfoMap); Assert.assertEquals(3, UserInfoMaps.size()); } finally { sqlSession.close(); } }
@Override public UserEntity getUserEntity(long id) { try (SqlSession sqlSession = dbManager.getSqlSession()) { UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.selectByPrimaryKey(id); } }
/** * 查询全部 */ @Test public void testDynamicSelectPage() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { CountryMapper mapper = sqlSession.getMapper(CountryMapper.class); List<Country> countryList = mapper.selectAll(); //查询总数 Assert.assertEquals(183, countryList.size()); } finally { sqlSession.close(); } }
@SuppressWarnings("unchecked") public <T> T getMapper(Class<T> type, SqlSession sqlSession) { final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type); if (mapperProxyFactory == null) { throw new BindingException("Type " + type + " is not known to the MybatisPlusMapperRegistry."); } try { return mapperProxyFactory.newInstance(sqlSession); } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } }
/** * 根据查询条件进行查询 */ @Test public void testDynamicSelect() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { CountryMapper mapper = sqlSession.getMapper(CountryMapper.class); Country country = new Country(); country.setCountrycode("CN"); Assert.assertEquals(1, mapper.selectCount(country)); } finally { sqlSession.close(); } }
/** * 查询 */ @Test public void testSelect() { SqlSession sqlSession = MybatisHelper.getSqlSession(); try { UserLoginMapper mapper = sqlSession.getMapper(UserLoginMapper.class); UserLogin userLogin = new UserLogin(); userLogin.setUsername("test1"); List<UserLogin> userLogins = mapper.select(userLogin); Assert.assertEquals(5, userLogins.size()); } finally { sqlSession.close(); } }
/** * 测试insertSelective增强 */ @Test public void testInsertSelective() throws IOException, XMLParserException, InvalidConfigurationException, InterruptedException, SQLException { MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/SelectiveEnhancedPlugin/mybatis-generator.xml"); tool.generate(new AbstractShellCallback() { @Override public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper"))); ObjectUtil tb = new ObjectUtil(loader, packagz + ".Tb"); tb.set("incF3", 10l); tb.set("tsIncF2", 5l); // selective ObjectUtil TbColumnField1 = new ObjectUtil(loader, packagz + ".Tb$Column#field1"); ObjectUtil TbColumnTsIncF2 = new ObjectUtil(loader, packagz + ".Tb$Column#tsIncF2"); Object columns = Array.newInstance(TbColumnField1.getCls(), 2); Array.set(columns, 0, TbColumnField1.getObject()); Array.set(columns, 1, TbColumnTsIncF2.getObject()); tb.invoke("selective", columns); // sql String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "insertSelective", tb.getObject()); Assert.assertEquals(sql, "insert into tb ( field_1, inc_f2 ) values ( 'null', 5 )"); Object result = tbMapper.invoke("insertSelective", tb.getObject()); Assert.assertEquals(result, 1); } }); }