springboot+springMVC+mysql+mybatis微整合

一.項目構建

  1. 下載springboot項目
    springboot網頁構建
  2. 添加mybatis逆向工程需要的依賴(jar包和插件):
<dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
<!-- mybatis generator 自動生成代碼插件 -->
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.2</version>
				<configuration>
					<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
					<!--允許覆蓋生成的文件-->
					<overwrite>true</overwrite>
					<!--允許移動生成的文件-->
					<verbose>true</verbose>
				</configuration>
			</plugin>

  1. 完善項目目錄

二.mybatis逆向工程

  1. 在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>
    <!-- 數據庫連接的jar包路徑(oracle同理) -->
    <classPathEntry location="C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\8.0.15\mysql-connector-java-8.0.15.jar" />
    <context id="mysqlTables" targetRuntime="MyBatis3">
        <!-- 生成的pojo,將implements Serializable-->
        <!--  <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>  -->
        <commentGenerator>
            <!-- 是否去除自動生成的註釋 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

        <!-- 數據庫鏈接URL、用戶名、密碼 (這裏寫死了mysql,其實Oracle也可以)-->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test?serverTimezone=GMT&amp;nullCatalogMeansCurrent=true&amp;characterEncoding=UTF-8"
                        userId="root"
                        password="123456">
        </jdbcConnection>

        <!--
           默認false,把JDBC DECIMAL 和 NUMERIC 類型解析爲 Integer
            true,把JDBC DECIMAL 和 NUMERIC 類型解析爲java.math.BigDecimal
        -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="true" />
        </javaTypeResolver>

        <!--
        生成model模型,對應的包路徑,以及文件存放路徑(targetProject),targetProject可以指定具體的路徑
        -->
        <javaModelGenerator targetPackage="com.example.demo.entity" targetProject="src/main/java">
            <!-- enableSubPackages:是否讓schema(數據庫名)作爲包的後綴 -->
            <!--<property name="enableSubPackages" value="true"/>-->
            <!-- 從數據庫返回的值被清理前後的空格  -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!--對應的mapper.xml文件  -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <!--<property name="enableSubPackages" value="true"/>-->
        </sqlMapGenerator>

        <!-- 對應的Mapper接口類文件 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.demo.dao" targetProject="src/main/java">
            <!--<property name="enableSubPackages" value="true"/>-->
        </javaClientGenerator>


        <!-- 列出要生成代碼的所有表,這裏配置的是不生成Example文件 -->
        <table schema="test" tableName="student" domainObjectName="Student"
               enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false" >
            <property name="useActualColumnNames" value="false"/>
        </table>
    </context>
</generatorConfiguration>

注意:

connectionURL=“jdbc:mysql://localhost:3306/test?serverTimezone=GMT&nullCatalogMeansCurrent=true&characterEncoding=UTF-8”

  1. serverTimezone屬性:不加這個屬性的話,需要修改mysql配置文件,把數據庫時區改爲中國時區,否則會報錯
  2. nullCatalogMeansCurrent屬性:用於識別主鍵,老版本mysql的jar包中默認屬性爲true,不需要加,但新版本需要加上,要不然生成的xml文件沒有主鍵.參考!MyBatis Generator踩坑與自救,如果按他上面的配置,表名前會有庫名加兩個點,項目進行中會因識別不了表名而報錯
  3. 配置中路徑和參數是我的路徑和參數,靈活修改
  1. 運行generatorConfig.xml文件(本案例使用maven命令運行)
mybatis-generator:generate -e



3. 運行後項目目錄結構:

三. 配置application.properties文件

spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

mybatis.type-aliases-package=com.example.demo.entity
mybatis.mapper-locations=classpath:mapper/*.xml

注意:

mysql-connector-java的jar包版本太高,驅動類名稱:com.mysql.cj.jdbc.Driver,老版本的驅動類不推薦使用了,在逆向工程的配置文件中也是這樣

四. 編寫業務層代碼合控制層代碼

  1. 業務層接口
public interface StudentService {
    Student getStudent(Long id);
}
  1. 業務層實現
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public Student getStudent(Long id) {
        return studentMapper.selectByPrimaryKey(id);
    }
}

注意:

這裏使用idea的時候,注入一個接口,studentMapper會標紅,不會影響程序運行,因爲mybatis使用動態代理生成了代理類,注入的其實是一個代理類,把error級別改爲warning即可.或者每個mapper接口都加上@Component,不過比較麻煩

  1. 控制層
@RestController
public class StudentController {
    @Autowired
    private StudentService studentService;

    @RequestMapping("/")
    public String findStudent() {
        return studentService.getStudent(1L).toString();
    }
}
  1. 實體類Student重寫toString方法
@Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
  1. 啓動類DemoApplication加mapper路徑掃描
@SpringBootApplication
@MapperScan("com.example.demo.dao")
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}

五. 數據庫表

六. 運行項目

直接運行啓動類main方法,瀏覽器輸入地址:http://localhost:8080/
結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章