在上一節中我們簡單的使用了spring的JdbcTemplate來進行數據庫操作,但是在實際的項目中使用mybatis來連接數據庫是更好的選擇。接下來我們將在項目中集成mybatis。
- 首先在pom.xml中加入mybatis的依賴
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
- 然後在pom.xml中的build節點下的plugins節點新增一個自動生成代碼插件
<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>
- 接下來在application.yml中新增以下配置,yml文件對格式有要求,冒號後面必須空格,否則會識別不了。有關於yml的具體配置之後會詳細講解。
## 該配置節點爲獨立的節點,有很多同學容易將這個配置放在spring的節點下,導致配置無法被識別
mybatis:
mapper-locations: classpath:mapping/*.xml #注意:一定要對應mapper映射xml文件的所在路徑
type-aliases-package: com.example.demo.model # 注意:對應實體類的路徑
#pagehelper分頁插件
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
- 在項目路徑下新建model文件夾,在其中新建user.java實體類。
package com.example.demo.model;
public class User {
private Integer userId;
private String userName;
private String password;
private String phone;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
}
- 項目路徑下新建mapper文件夾,新建UserMapper.java
package com.example.demo.mapper;
import com.example.demo.model.User;
import java.util.List;
public interface UserMapper {
int deleteByPrimaryKey(Integer userId);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer userId);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
//這個方式我自己加的
List<User> selectAllUser();
}
- 在resources路徑下新建mapping文件夾,新建UserMapper.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.example.demo.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.example.demo.model.User" >
<id column="user_id" property="userId" jdbcType="INTEGER" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="phone" property="phone" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
user_id, user_name, password, phone
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from t_user
where user_id = #{userId,jdbcType=INTEGER}
</select>
<!-- 這個方法是我自己加的 -->
<select id="selectAllUser" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_user
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from t_user
where user_id = #{userId,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.example.demo.model.User" >
insert into t_user (user_id, user_name, password,
phone)
values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{phone,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.example.demo.model.User" >
insert into t_user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="userId != null" >
user_id,
</if>
<if test="userName != null" >
user_name,
</if>
<if test="password != null" >
password,
</if>
<if test="phone != null" >
phone,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="userId != null" >
#{userId,jdbcType=INTEGER},
</if>
<if test="userName != null" >
#{userName,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
<if test="phone != null" >
#{phone,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.example.demo.model.User" >
update t_user
<set >
<if test="userName != null" >
user_name = #{userName,jdbcType=VARCHAR},
</if>
<if test="password != null" >
password = #{password,jdbcType=VARCHAR},
</if>
<if test="phone != null" >
phone = #{phone,jdbcType=VARCHAR},
</if>
</set>
where user_id = #{userId,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.example.demo.model.User" >
update t_user
set user_name = #{userName,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
phone = #{phone,jdbcType=VARCHAR}
where user_id = #{userId,jdbcType=INTEGER}
</update>
</mapper>
完成之後項目結構如圖:
- 在service中新增方法testMapper方法並自動注入mapper
package com.example.demo.service;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class DemoService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private UserMapper userMapper;
public List<Map<String, Object>> test () {
return jdbcTemplate.queryForList("select * from user");
}
public List<User> testMapper () {
return userMapper.selectAllUser();
}
}
- 在controller中新增另一個接口,調用剛剛在service中新增的方法
@GetMapping("/testMapper")
public List<User> testMapper() {
return demoService.testMapper();
}
- 啓動項目,在瀏覽器中調用http://localhost:8080/testMapper,即可得到我們想要的結果。此處步驟較多,如果項目在啓動過程中報錯的話,請仔細檢查yml配置以及xml中的各項語法。
xml中namespace爲對應的mapper實體類,resultMap的type爲返回值對應的實體類,各個節點中的parameterType爲輸入參數對應的實體類,這些路徑都要正確。
以上就是Spring Boot簡單的整合mybatis,後期會對這個整合做進一步的深入探究。
現在我們已經有了兩個可以和數據庫交流的接口了,在下一節通過Spring Boot與swagger整合來開發一個我們自己的接口文檔。Spring Boot從入門到精通-集成swagger