创建SpringBoot工程并集成Mybatis的方法
今天我们在springboot上集成mybatis。首先创建一个maven项目。
添加依赖
<!--springboot依赖--> <dependency> <groupId>org.springframework.boot<groupI> <artifactId>springbootstarter<artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--测试--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--集成Mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter<artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency>
在src/main/resources/目录下新建一个application.properties配置文件,里面写数据源的配置
spring.datasource.name=test spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test spring.datasource.username=root spring.datasource.password=root
配置文件有两种写法,我们还可以写成yml文件形式,在src/main/resources/目录下新建一个application.yml文件(两种方式选其中一种就可以了)
spring: datasource: url: jdbc:mysql://127.0.0.1:3306/test username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver
在本地数据库中创建test数据库,并新建一个表t_user
CREATE DATABASE test; CREATE TABLE `t_user` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(225) NOT NULL, `password` varchar(225) NOT NULL, `phone` varchar(225) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8
这里我们使用mybatis-generator插件,自动生成实体类,mapper,以及mapper.xml文件
在pom中添加build依赖(放在层次外面)
<build> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <excludes> <exclude>generator/**</exclude> </excludes> </resource> </resources> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.4-SNAPSHOT</version> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.39</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.4-SNAPSHOT</version> </dependency> </dependencies> <configuration> <overwrite>true</overwrite> <configurationFile>src/main/resources/generator/generatorConfig.xml</configurationFile> </configuration> </plugin> </plugins> </build>
在src/main/resources/下面新建一个目录generator,在此目录下新建一个generatorConfig.xml文件(注意根据自己的目录,调整路径)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--数据库链接地址账号密码--> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/test" userId="root" password="root"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!--生成Model类存放位置--> <javaModelGenerator targetPackage="com.lw.study.dao.domain" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!--生成映射文件存放位置--> <sqlMapGenerator targetPackage="sqlmap" targetProject="src/main/resources/"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!--生成Dao类存放位置--> <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码 type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.lw.study.dao.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!--生成对应表及类名--> <!--<table schema="loandb" tableName="T_AUDIT_JOB" domainObjectName="AuditJob">--> <!--<property name="useActualColumnNames" value="true"/>--> <!--<generatedKey column="Id" sqlStatement="MySql" identity="true"/>--> <!--</table>--> <table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>
然后运行generator配置文件。
在点击左上角的➕,选择maven
Working derectory选择自己的项目路径。然后apply,在右上角运行就可以了,就会在指定的目录下生成三个文件(实体类,mapper类,和mapper.xml文件)
最后在src/main/java/com/lw/study/目录下新建一个mybatisConfig目录,里面新建两个配置类。
MybatisConfig.java
@Configuration @EnableTransactionManagement public class MyBatisConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource(){ return new org.apache.tomcat.jdbc.pool.DataSource(); } @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactoryBean() throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource()); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/sqlmap/*.xml")); return sqlSessionFactoryBean.getObject(); } }
MyBatisMapperScannerConfig.java
@Configuration @AutoConfigureAfter(MyBatisConfig.class) public class MyBatisMapperScannerConfig { @Bean public MapperScannerConfigurer mapperScannerConfigurer() { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); mapperScannerConfigurer.setBasePackage("com.study.dao.mapper"); return mapperScannerConfigurer; } }
创建一个springboot的启动类,Application.java
@SpringBootApplication(scanBasePackages = {"com.lw.study.*"}) @MapperScan("com.lw.study.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
好了,到这里我们在springboot中通过generator插件的方式集成mybatis就完成了。大家可以自己写一个测试类,使用mapper中的方法看能否在数据库中查到数据。
总结
以上所述是小编给大家介绍的创建SpringBoot工程并集成Mybatis的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!