SpringBoot(Spring、SpringMVC)集成Mybatis操作Mysql數據庫

1、由於使用的是Idea社區版,這裏從頭搞一下,我下載的Idea社區版壓縮包,解壓縮以後,直接打開就行了。

  點擊Configure -> Plugins插件。旗艦版Idea自帶有spring Initializr,社區版本是啥子都沒有默認安裝的,這裏安裝這個spring Assistant插件,在settings中plugins中搜索進行安裝。彈出Accept,點擊接受就行了,然後Restart IDE。

2、然後點擊Create New Project,創建我們的項目,如下所示:

由於我是新下載的社區版Idea,這裏我沒有使用他們默認的jdk11,我使用本地jdk1.8版本。

3、然後這些組織號,項目名稱,版本號,項目構建方式,語言,打包方式,語言版本,項目名稱,項目描述,包名稱,根據自己喜好去搞吧。

4、選擇項目所需要的依賴,這裏由於要連接Mysql數據庫,所以要將這些依賴都加進去的。

5、修改你的項目名稱和存儲的位置,保存即可。

6、設置字體大小,字小看着真是不舒服的。

7、Idea社區版,設置一下maven。可以安裝一下Maven Runner插件。

8、Idea社區版,集成tomcat,果然免費的,都是要自己手動搞的,有點浪費時間了。

安裝好插件以後,重啓Idea。在右上角Edit Configurations 配置環境變量,如下所示。

然後點擊configuration進行配置tomcat。看到上面那一行英文了嗎,Template,The values saved here will be used for new configurations of the same type,然後點擊Create configuration哦。

Tomcat添加成功以後,點擊Apply,點擊Ok即可了。

最後再配置一下Tomcat即可。

1)、Name : 項目名稱。
2)、Tomcat Server: tomcat的路徑。
3)、Deployment Directory: webapps的路徑。在main文件下創建一個新的目錄文件webapps。注意此處需要填寫的路徑是源碼裏webapps的路徑。
4)、custom context: 自定義上下文,這裏不自定義了。
5)、Context Path : 上下文路徑,這個會自動識別,一般不用修改。發佈的上下文,即訪問url的前面的根路徑(會自動識別,一般不需要修改)。
6)、Server Port : 服務器監聽端口 8080 (一般自行修改)。
7)、VM options : Java虛擬機參數設置(可不填)。

配置完成之後,點擊右上角的三角運行按鈕就能正常啓動tomcat了。

9、Maven依賴包,如下所示:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelVersion>4.0.0</modelVersion>
 5     <parent>
 6         <groupId>org.springframework.boot</groupId>
 7         <artifactId>spring-boot-starter-parent</artifactId>
 8         <version>2.2.5.RELEASE</version>
 9         <relativePath/> <!-- lookup parent from repository -->
10     </parent>
11     <groupId>com.bie</groupId>
12     <artifactId>demo</artifactId>
13     <version>0.0.1-SNAPSHOT</version>
14     <name>demo</name>
15     <description>Demo project for Spring Boot</description>
16 
17     <properties>
18         <java.version>1.8</java.version>
19     </properties>
20 
21     <dependencies>
22         <dependency>
23             <groupId>org.springframework.boot</groupId>
24             <artifactId>spring-boot-starter-data-jdbc</artifactId>
25         </dependency>
26         <dependency>
27             <groupId>org.springframework.boot</groupId>
28             <artifactId>spring-boot-starter-jdbc</artifactId>
29         </dependency>
30         <dependency>
31             <groupId>org.springframework.boot</groupId>
32             <artifactId>spring-boot-starter-web</artifactId>
33         </dependency>
34         <dependency>
35             <groupId>org.mybatis.spring.boot</groupId>
36             <artifactId>mybatis-spring-boot-starter</artifactId>
37             <version>2.1.1</version>
38         </dependency>
39 
40         <dependency>
41             <groupId>mysql</groupId>
42             <artifactId>mysql-connector-java</artifactId>
43             <scope>runtime</scope>
44         </dependency>
45         <dependency>
46             <groupId>org.projectlombok</groupId>
47             <artifactId>lombok</artifactId>
48             <optional>true</optional>
49         </dependency>
50         <dependency>
51             <groupId>org.springframework.boot</groupId>
52             <artifactId>spring-boot-starter-test</artifactId>
53             <scope>test</scope>
54             <exclusions>
55                 <exclusion>
56                     <groupId>org.junit.vintage</groupId>
57                     <artifactId>junit-vintage-engine</artifactId>
58                 </exclusion>
59             </exclusions>
60         </dependency>
61     </dependencies>
62 
63     <build>
64         <plugins>
65             <plugin>
66                 <groupId>org.springframework.boot</groupId>
67                 <artifactId>spring-boot-maven-plugin</artifactId>
68             </plugin>
69         </plugins>
70     </build>
71 
72 </project>

10、你可以使用application.properties文件,也可以使用application.yml文件。我這裏使用application.properties文件,創建了兩個properties文件application.properties、application-dev.properties。或者你可以根據壞境多創建幾個配置文件的。嗯,好吧,社區版配置文件提示都沒有,毛線啊,難搞哦!

  在項目中配置多套環境的配置方法。因爲現在一個項目有好多環境,開發環境,測試環境,生產環境,每個環境的參數不同,所以我們就可以把每個環境的參數配置到properties文件中,這樣再想用哪個環境的時候只需要在主配置文件中將用的配置文件寫上就行。在Spring Boot中多環境配置文件名需要滿足application-{profile}.properties的格式,其中{profile}對應你的環境標識,比如:
  application-dev.properties:開發環境。
  application-test.properties:測試環境。
  application-prod.properties:生產環境。
  至於哪個具體的配置文件會被加載,需要在application.properties文件中通過spring.profiles.active屬性來設置,其值對應{profile}值。

application.properties配置文件,如下所示:

1 spring.profiles.active=dev

application-dev.properties配置文件,如下所示:

 1 server.port=8080
 2 server.address=127.0.0.1
 3 # mysql的驅動連接
 4 spring.datasource.username=root
 5 spring.datasource.password=123456
 6 spring.datasource.url=jdbc:mysql://localhost:3306/gov_policy?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
 7 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
 8 # mybatis
 9 mybatis.mapper-locations=classpath:mapping/*Mapper.xml
10 mybatis.type-aliases-package=com.bie.demo.po
11 # 後臺打印sql語句
12 mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

10、創建包,開始碼代碼。resources下創建mapping文件夾,用於配置sql語句,也可以用註解的方式直接寫在mapper文件裏。看個人喜好了這裏。

實體類CustomerInfo ,如下所示:

 1 package com.bie.demo.po;
 2 
 3 import lombok.AllArgsConstructor;
 4 import lombok.Data;
 5 import lombok.NoArgsConstructor;
 6 import lombok.ToString;
 7 
 8 /**
 9  *
10  */
11 @Data
12 @ToString
13 @AllArgsConstructor
14 @NoArgsConstructor
15 public class CustomerInfo {
16 
17     private int id;
18     private String account;
19     private String cname;
20     private String sex;
21     private String password;
22     private String identity;
23     private String telephone;
24     private String address;
25     private String birthday;
26     private String identification;
27 
28 }

數據交互層CustomerInfoMapper接口,如下所示:

 1 package com.bie.demo.mapper;
 2 
 3 import com.bie.demo.po.CustomerInfo;
 4 import org.springframework.stereotype.Repository;
 5 
 6 @Repository
 7 public interface CustomerInfoMapper {
 8 
 9     /**
10      * 根據政策ID查詢
11      *
12      * @param id
13      * @return
14      */
15     public CustomerInfo selectCustomerInfoById(int id);
16 }

業務邏輯層接口,和實現類,如下所示:

 1 package com.bie.demo.service;
 2 
 3 import com.bie.demo.po.CustomerInfo;
 4 
 5 /**
 6  *
 7  */
 8 public interface CustomerInfoService {
 9 
10     /**
11      * 根據政策ID查詢
12      *
13      * @param id
14      * @return
15      */
16     public CustomerInfo selectCustomerInfoById(int id);
17 }
 1 package com.bie.demo.service.impl;
 2 
 3 import com.bie.demo.mapper.CustomerInfoMapper;
 4 import com.bie.demo.po.CustomerInfo;
 5 import com.bie.demo.service.CustomerInfoService;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.stereotype.Service;
 8 
 9 /**
10  *
11  */
12 @Service
13 public class CustomerInfoServiceImpl implements CustomerInfoService {
14 
15     @Autowired
16     private CustomerInfoMapper customerInfoMapper;
17 
18     @Override
19     public CustomerInfo selectCustomerInfoById(int id) {
20         if (id > 0) {
21             CustomerInfo customerInfo = customerInfoMapper.selectCustomerInfoById(id);
22             if (customerInfo != null) {
23                 return customerInfo;
24             }
25         }
26         return null;
27     }
28 }

控制層CustomerInfoController,如下所示:

 1 package com.bie.demo.controller;
 2 
 3 import com.bie.demo.po.CustomerInfo;
 4 import com.bie.demo.service.CustomerInfoService;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RequestParam;
 9 import org.springframework.web.bind.annotation.ResponseBody;
10 
11 /**
12  *
13  */
14 @Controller
15 @RequestMapping(value = "/customerInfo")
16 public class CustomerInfoController {
17 
18     @Autowired
19     private CustomerInfoService customerInfoService;
20 
21     @RequestMapping(value = "/selectCustomerInfoById")
22     @ResponseBody
23     public CustomerInfo selectCustomerInfoById(@RequestParam(value = "id") int id) {
24         CustomerInfo customerInfo = customerInfoService.selectCustomerInfoById(id);
25         if (customerInfo != null) {
26             return customerInfo;
27         }
28         return null;
29     }
30 
31 
32 }

實體類和數據表映射配置文件CustomerInfoMapper.xml,如下所示:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 3         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4 <mapper namespace="com.bie.demo.mapper.CustomerInfoMapper">
 5 
 6     <resultMap id="BaseResultMap" type="com.bie.demo.po.CustomerInfo">
 7         <result column="id" jdbcType="INTEGER" property="id"/>
 8 
 9         <result column="account" jdbcType="VARCHAR" property="account"/>
10         <result column="cname" jdbcType="VARCHAR" property="cname"/>
11         <result column="sex" jdbcType="VARCHAR" property="sex"/>
12         <result column="password" jdbcType="VARCHAR" property="password"/>
13         <result column="telephone" jdbcType="VARCHAR" property="telephone"/>
14         <result column="address" jdbcType="VARCHAR" property="address"/>
15         <result column="birthday" jdbcType="VARCHAR" property="birthday"/>
16         <result column="identification" jdbcType="VARCHAR" property="identification"/>
17     </resultMap>
18 
19     <select id="selectCustomerInfoById" resultMap="BaseResultMap">
20         select
21         *
22         from
23             customer_info
24         where
25             id = #{id}
26     </select>
27 
28 </mapper>

SpringBoot項目啓動類,如下所示:

切記,一定要配置,需要掃描的mapper文件路徑,不然報錯哦,之前貼過,這裏略過,@MapperScan("com.bie.demo.mapper")。

 1 package com.bie.demo;
 2 
 3 import org.mybatis.spring.annotation.MapperScan;
 4 import org.springframework.boot.SpringApplication;
 5 import org.springframework.boot.autoconfigure.SpringBootApplication;
 6 
 7 @MapperScan("com.bie.demo.mapper")
 8 @SpringBootApplication
 9 public class DemoApplication {
10 
11     public static void main(String[] args) {
12         SpringApplication.run(DemoApplication.class, args);
13     }
14 
15 }

11、項目結構圖,如下所示:

12、啓動項目,測試如下所示:

13、數據表結構,如下所示:

14、如何使用Mybatis的sql語句註解版呢,如下所示:

application-dev.properties配置文件,修改爲如下所示:

 1 server.port=8080
 2 server.address=127.0.0.1
 3 # mysql的驅動連接
 4 spring.datasource.username=root
 5 spring.datasource.password=123456
 6 spring.datasource.url=jdbc:mysql://localhost:3306/biehl?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
 7 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
 8 # mybatis
 9 # mybatis.mapper-locations=classpath:mapping/*Mapper.xml
10 # mybatis依賴
11 mybatis.type-aliases-package=com.bie.demo.mapper
12 # 後臺打印sql語句
13 mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

數據交互層,CustomerInfoMapper,修改爲如下所示:

 1 package com.bie.demo.mapper;
 2 
 3 import com.bie.demo.po.CustomerInfo;
 4 import org.apache.ibatis.annotations.Select;
 5 import org.springframework.stereotype.Repository;
 6 
 7 @Repository
 8 public interface CustomerInfoMapper {
 9 
10     /**
11      * 根據政策ID查詢
12      *
13      * @param id
14      * @return
15      */
16     @Select("SELECT * FROM customer_info WHERE id = #{id}")
17     public CustomerInfo selectCustomerInfoById(int id);
18 }

此時,將resources目錄下面的mapping目錄刪除即可。通過測試,表示是可行的。

 

作者:別先生

博客園:https://www.cnblogs.com/biehongli/

如果您想及時得到個人撰寫文章以及著作的消息推送,可以掃描上方二維碼,關注個人公衆號哦。

 

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