一、 数据库
先创建一个first 数据库,
再创建一个student表,表中有姓名name,学号number,
性别sex,年龄age,所属班级class,电话tel。
二、 整合
使用maven项目管理。
加入mybatis和mysql依赖,整合Springboot和mybatis 。
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>8.0.15</scope>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
在Resource文件下创建的application.yml中配置连接数据库四大要素 。
spring:
datasource:
url: jdbc:mysql://localhost:3306/first?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
创建mapper controller
service entity 四个package。
然后使用mybatis逆向工程创建
entity实体类 mapper接口 mapper.xml文件 。
配置逆向工程generator。
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
然后在build的plugin配置generator。
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<configuration>
<!-- mybatis用于生成代码的配置文件 -->
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
在Resource下创建的generator.xml文件中配置你所想要生成的代码存放路径以及指定生成代码所需的数据库表(可以指定多个)。
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="false"/>
</commentGenerator>
<!--连接数据库四大要素-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/first"
userId="root" password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!--targetPackage填写生成代码所在的包名,targetProject为目标工程-->
<javaModelGenerator targetPackage="com.manage.stu.entity" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.manage.stu.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.manage.stu.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 指定数据库表 -->
<table tableName="student"
domainObjectName="student"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
</context>
如图双击生成代码即可完成Springboot整合Mybatis。