在上一节中我们简单的使用了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
Spring Boot从入门到精通-mybatis多数据源
您的关注是我最大的动力