spring boot學習(五)之連線資料庫整合Mybatis
前言
在上一篇文章中記錄了 ofollow,noindex">spring boot整合jdbcTemplate ,這次記錄一下spring boot整合Mybatis,在實際專案中這種方式還是很常用的。和上一篇文章大同小異,發現spring boot整合mybatis比spring MVC整合要來得簡單得多呢。
正文
pom.xml引入依賴
<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> </dependency>
MyBatis-Spring-Boot-Starter
會自動將我們配置的 datasource
與 mapper.xml
檔案註冊到spring上下文,很智慧。
在 application.properties
配置檔案中配置資料來源
spring.datasource.url = jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 spring.datasource.username = root spring.datasource.password = 123456 spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
新增資料池依賴,這裡用的是阿里巴巴的資料池
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.19</version> </dependency>
在啟動類 Chapter1Application.java
中讀取資料來源配置資訊,Spring Boot會自動的用我們配置的這個DataSource。新增如下程式碼
@Autowired private Environment environment; public DataSource dataSource(destroyMethod ="close") { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(environment.getProperty("datasource.url")); dataSource.setUsername(environment.getProperty("datasource.username")); dataSource.setPassword(environment.getProperty("datasource.password")); dataSource.setDriverClassName(environment.getProperty("datasource.driver-class-name")); dataSource.setInitialSize(5);//初始化時建立物理連線的個數 dataSource.setMaxActive(20);//最大連線池數量 dataSource.setMinIdle(0);//最小連線池數量 dataSource.setMaxWait(50000);//獲取連線時最大等待時間,單位毫秒。 dataSource.setValidationQuery("SELECT 1");//用來檢測連線是否有效的sql return dataSource; }
下面就用我們配置的這個資料來源資訊,用JdbcTemplate來與資料庫進行資料互動
本地建立 spring
資料庫,再建立一張 user
表,表屬性如下,自行填幾條資料:

1.png
簡單的做了個查詢的例子:
-
建立實體檔案:
User.java
public class User { private int id; private String name; private int age; private String address; private String phone; //set and get }
-
controller
層:UserController.java
:
@RestController public class UserController { @Autowired private UserService userService; private Logger logger = LoggerFactory.getLogger(this.getClass()); @RequestMapping(value = "/queryUserList",method = RequestMethod.GET,produces="application/json;charset=UTF-8") @ResponseBody public String queryLearnList(HttpServletRequest request , HttpServletResponse response){ String name = request.getParameter("name"); String phone = request.getParameter("phone"); Map<String,Object> params = new HashMap<String,Object>(); params.put("name", name); params.put("phone", phone); List userList =userService.queryUserList(params); return JSONArray.fromObject(userList).toString(); }
-
service
層:介面UserService.java
和實現類UserServiceImpl.java
public interface UserService { List queryUserList(Map<String, Object> params); }
@Service public class UserServiceImpl implements UserService { @Autowired UserDao userDao; @Override public List queryUserList(Map<String,Object> params) { return userDao.queryUserList(params); } }
整合Mybatis
dao
層:這裡去掉了實現類,具體操作如下:
@Component @Mapper public interface UserDao { public List queryUserList(Map<String, Object> params); }
在 application.properies
中增加如下配置:
#指定bean所在包 mybatis.type-aliases-package=com.mlin.entiy #指定對映檔案 mybatis.mapperLocations=classpath:mapper/*.xml
新建 mapper
檔案目錄,存放在 src/main/resources
下面,在 src/main/resources/mapper
目錄下新建 UserDaoMapper.xml
檔案:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.mlin.dao.UserDao"> <resultMap id="resultMap" type="com.mlin.entiy.User"> <id column="id" property="id" jdbcType="BIGINT"/> <result column="name" property="name" jdbcType="VARCHAR"/> <result column="age" property="age" jdbcType="BIGINT"/> <result column="address" property="address" jdbcType="VARCHAR"/> <result column="phone" property="phone" jdbcType="VARCHAR"/> </resultMap> <sql id="sql_column" > id,name,age,address,phone </sql> <select id="queryUserList" resultMap="resultMap" parameterType="java.util.HashMap"> select <include refid="sql_column" /> from user <where> 1 = 1 <if test="name!= null and name !=''"> AND name like CONCAT(CONCAT('%',#{name,jdbcType=VARCHAR}),'%') </if> <if test="phone != null and phone !=''"> AND phone likeCONCAT(CONCAT('%',#{phone,jdbcType=VARCHAR}),'%') </if> </where> </select> </mapper>
通過指定 namespace
來與dao聯絡。
結果
啟動專案,在瀏覽器輸入: http://localhost:8080/queryUserList
,得到如下結果

1.png
總結
實踐中可能遇到如下問題:
報錯資訊
:啟動專案後瀏覽器訪問後臺一直報
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.mlin.dao.UserDao.queryUserList
這裡給出網路上的一下答案:
-
1. mapper的namespace路徑不正確
-
2.UserDao的方法在UserDaoMapper.xml中沒有
-
3. UserDao的方法返回值是List,而select元素沒有正確配置ResultMap,或者只配置ResultType
-
4. 如果你確認沒有以上問題,請任意修改下對應的xml檔案,比如刪除一個空行,再試試
上面的辦法都沒有解決我這裡的問題,後來才發現是application.properies
配置mybatis的路徑名寫錯了,可見這個名字也是不能隨便亂取的
改之前
#指定bean所在包 mybatis.bean=com.mlin.entiy #指定對映檔案 mybatis.mapper=classpath:mapper/*.xml
改之後:
#指定bean所在包 mybatis.type-aliases-package=com.mlin.entiy #指定對映檔案 mybatis.mapperLocations=classpath:mapper/*.xml
原創作者:夢凌小樣
作品連結: https://www.jianshu.com/p/7a804c7dee0f 【原創不易,轉載請註明出處,感謝理解】
一位愛生活,愛創作,愛分享,愛自己的90後女程式員一枚,記錄工作中的點點滴滴,一起學習,共同進步,期待能和優秀的您交上朋友