SpringBootl連線資料庫MyBatis方式實現
阿新 • • 發佈:2018-12-07
SpringBoot中利用MyBatis的方式連線資料庫是十分簡單、可操作性也非常強,層次十分清晰,解耦性很高,利用的是面向介面程式設計。
首先,你需要依次建立相關的包:
–pojo
–service
–controller
–mapper
然後再resourse下建立一個XXXMapper.xml檔案。
所有的不走和程式碼如下:
第一步:配置先關資訊
#設定jdbc相關配置
spring:
datasource:
url: jdbc:mysql://10.1.1.3:3306/liangtest
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
max-idle: 10
max-wait: 10000
min-idle: 5
initial-size: 5
#設定執行埠
server:
port: 8081
session:
timeout: 10
#設定字元編碼集
tomcat:
uri-encoding: utf-8
#配置相關MyBatis資訊
mybatis:
mapper-locations: classpath:mappers/*.xml
type-aliases-package: com.lgp.SpringBoot.bean
第二步:
<?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.demofor.mybatis.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.demofor.mybatis.pojo.User">
<id column="id" property="id" javaType="INTEGER" />
<result column="name" property="name" javaType="String"/>
<result column="age" property="age" javaType="INTEGER"/>
</resultMap>
<select id="getUserList" resultMap="BaseResultMap" parameterType="com.demofor.mybatis.pojo.User">
select * from user
</select>
</mapper>
第三步:
package com.demofor.mybatis.controller;
import com.demofor.mybatis.pojo.User;
import com.demofor.mybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* Created by rcc on 2017/12/11.
*/
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/getUserList")
public List<User> getUserList(){
List<User> userList = userService.getUserList();
return userList;
}
}
以上省略相關介面和實現類的步驟,是十分簡單的,只是簡單地呼叫相關的方法,和具體的實現,重要的是瞭解mapper.xml中的相關知識。