非Spring环境使用Mybatis Plus
-
理论上Mirai Console也是可以使用的。IService那些由于适配了spring的事务,所以无spring环境用会有点困难。个人建议对于Iservice提供的快捷方法 如:saveOrUpdate 还是通过手写xml实现吧。
传送门:
Mybatis Plus Generator(3.5.1以下版本)
Mybatis Plus Generator(3.5.1及以上版本 ) 目标楼层末尾
pon.xml<dependencies> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.31</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.4.3</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-extension</artifactId> <version>3.4.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>4.0.3</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-core</artifactId> <version>5.7.17</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.16</version> <scope>compile</scope> </dependency> </dependencies>
新建一个SqlSessionConfig
public class SqlSessionConfig { public static SqlSession session = init(); private static SqlSession init() { SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); MybatisConfiguration configuration = new MybatisConfiguration(); initConfiguration(configuration); configuration.addInterceptor(initInterceptor()); //扫描DAO/Mapper所在包 configuration.addMappers("org.test.mybatis.entity.dao"); //配置日志实现 configuration.setLogImpl(Slf4jImpl.class); //构建mybatis-plus需要的globalconfig GlobalConfig globalConfig = new GlobalConfig(); //此参数会自动生成实现baseMapper的基础方法映射 globalConfig.setSqlInjector(new DefaultSqlInjector()); //设置id生成器 globalConfig.setIdentifierGenerator(new DefaultIdentifierGenerator()); //设置超类mapper globalConfig.setSuperMapperClass(BaseMapper.class); // 这里可以配置逻辑删除 globalConfig.setDbConfig(initDBConfig()); //给configuration注入GlobalConfig里面的配置 GlobalConfigUtils.setGlobalConfig(configuration, globalConfig); //设置数据源 Environment environment = new Environment("1", new JdbcTransactionFactory(), initDataSource()); configuration.setEnvironment(environment); // 设置xxxDAO.xml所在的目录 // registryMapperXml(configuration, "dao"); //构建sqlSessionFactory SqlSessionFactory sqlSessionFactory = builder.build(configuration); return sqlSessionFactory.openSession(true); } private static void initConfiguration(MybatisConfiguration configuration) { configuration.setMapUnderscoreToCamelCase(true); configuration.setUseGeneratedKeys(true); } private static DataSource initDataSource() { HikariDataSource dataSource = new HikariDataSource(); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/back_up?useSSL=false&autoReconnect=true&serverTimezone=GMT%2B8&rewriteBatchedStatements=true"); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); dataSource.setUsername("root"); dataSource.setPassword("123456"); // 数据源设置,请按照当前DB参数设置 dataSource.setIdleTimeout(60000); dataSource.setAutoCommit(true); dataSource.setMaximumPoolSize(5); dataSource.setMinimumIdle(1); dataSource.setMaxLifetime(60000 * 10); dataSource.setConnectionTestQuery("SELECT 1"); return dataSource; } private static Interceptor initInterceptor() { //创建mybatis-plus插件对象 MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); //构建分页插件 PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(); paginationInnerInterceptor.setDbType(DbType.MYSQL); paginationInnerInterceptor.setOverflow(true); paginationInnerInterceptor.setMaxLimit(500L); interceptor.addInnerInterceptor(paginationInnerInterceptor); return interceptor; } private static GlobalConfig.DbConfig initDBConfig() { GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig(); // 逻辑删除字段 dbConfig.setLogicDeleteField("enable"); dbConfig.setLogicDeleteValue("0"); dbConfig.setLogicNotDeleteValue("1"); return dbConfig; } private static void registryMapperXml(MybatisConfiguration configuration, String classPath) throws IOException { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); Enumeration<URL> mapper = contextClassLoader.getResources(classPath); while (mapper.hasMoreElements()) { URL url = mapper.nextElement(); if (url.getProtocol().equals("file")) { String path = url.getPath(); File file = new File(path); File[] files = file.listFiles(); for (File f : files) { FileInputStream in = new FileInputStream(f); XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(in, configuration, f.getPath(), configuration.getSqlFragments()); xmlMapperBuilder.parse(); in.close(); } } else { JarURLConnection urlConnection = (JarURLConnection) url.openConnection(); JarFile jarFile = urlConnection.getJarFile(); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); if (jarEntry.getName().endsWith(".xml")) { InputStream in = jarFile.getInputStream(jarEntry); XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(in, configuration, jarEntry.getName(), configuration.getSqlFragments()); xmlMapperBuilder.parse(); in.close(); } } } } } }
用法:
SqlSession session = SqlSessionConfig.session; TImageDao tImageDao = session.getMapper(TImageDao.class); List<TImage> tImages = tImageDao.selectList(null); log.info("******{}", tImages);
-
旧版Mybatis Plus Generator
// 需要构建一个 代码自动生成器 对象 AutoGenerator mpg = new AutoGenerator(); // 配置策略 // 1、全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("Author"); gc.setOpen(false); // 是否覆盖 gc.setFileOverride(false); // 去Service的I前缀 gc.setServiceName("%sService"); gc.setMapperName("%sDao"); gc.setIdType(IdType.ASSIGN_ID); gc.setDateType(DateType.ONLY_DATE); // Swagger 2 API Doc相关注解,Knife4j亦可使用 // gc.setSwagger2(true); mpg.setGlobalConfig(gc); //2、设置数据源 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/back_up?useSSL=false"); // 驱动包 dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); // 数据库类型 dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); //3、包的配置 PackageConfig pc = new PackageConfig(); pc.setModuleName("test"); pc.setParent("org.test"); pc.setEntity("entity"); pc.setMapper("dao"); pc.setService("service"); pc.setController("controller"); mpg.setPackageInfo(pc); //4、策略配置 StrategyConfig strategy = new StrategyConfig(); // 设置要映射的表名 strategy.setInclude( "t_image", "t_plain_text" ); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); // 自动lombok; strategy.setEntityLombokModel(true); // 逻辑删除 strategy.setLogicDeleteFieldName("enable"); // 自动填充配置 TableFill gmtCreate = new TableFill("create_time", FieldFill.INSERT); TableFill gmtModified = new TableFill("update_time", FieldFill.INSERT_UPDATE); ArrayList<TableFill> tableFills = new ArrayList<>(); tableFills.add(gmtCreate); tableFills.add(gmtModified); strategy.setTableFillList(tableFills); // 乐观锁 // strategy.setVersionFieldName("version"); // Restful 风格 strategy.setRestControllerStyle(true); strategy.setControllerMappingHyphenStyle(true); mpg.setStrategy(strategy); mpg.execute();