springboot 整合Mybatis实战教程
但凡是搞Java开发的,现在应该基本上离不开使用springboot框架,使用框架的过程中肯定离不开操作数据库,目前国内主流的orm框架在Java生态圈中肯定首推Mybatis,虽然网上相关的整合教程还是非常多的,但是爹有娘有到最后还不如自己有,纸上谈兵谁都会,但是在作为一名编程人员,首先必须展示自己的代码,废话不多说,下面展示一个完整的整合案例,包括crud的完整操作,掌握明白应该可以应付公司的基本业务开发了,因此如果还打算在这个领域混,这个案例请必须掌握。
项目结构
src
com.spring.coding
- controller
- UserController.java
- service
- impl
UserServiceImpl.java
- UserService.java
- mapper
- UserMapper.java
- model
- User.java
resources
mybatis
- mapper
- UserMapper.xml
mybatis-config.xml
application.yml
maven依赖
<dependencies>
//web服务需要的包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
//springboot和Mybatis整合包
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
//MySQL驱动包
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
application.yml配置
server:
port: 8080
#MySQL相关配置
spring:
application:
name: mybatis-crud
datasource:
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/test?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&autoReconnect=true
driver-class-name: com.mysql.cj.jdbc.Driver
#mybatis相关配置
mybatis:
#Mybatis配置文件
config-location: classpath:mybatis/mybatis-config.xml
#接口映射文件配置
mapper-locations: classpath:mybatis/mapper/*.xml
#实体包映射配置
type-aliases-package: con.mybatis.springboot_mybatis.model
Mybatis 相关配置文件
1、mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>
</configuration>
2、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.spring.coding.mapper.UserMapper">
<resultMap id="UserBaseResultMap" type="com.spring.coding.model.User">
<id property="id" column="id" javaType="Integer"/>
<result property="userName" column="username"/>
<result property="password" column="password"/>
</resultMap>
<insert id="add" parameterType="com.spring.coding.model.User">
insert into user(username, password) values (#{userName}, #{password})
</insert>
<delete id="deleteByPrimary" parameterType="java.lang.Integer">
delete from user where id = #{id}
</delete>
<update id="updateByPrimaryKey" parameterType="com.spring.coding.model.User">
update user set username = #{userName}, password = #{password} where id = #{id}
</update>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="UserBaseResultMap">
select * from user where id = #{id}
</select>
<select id="selectByList" resultMap="UserBaseResultMap">
select * from user
</select>
</mapper>
UserMapper.java(dao接口层)
package com.spring.coding.mapper;
import com.spring.coding.model.User;
import java.util.List;
public interface UserMapper {
/**
* 添加接口
* @Param User user
* @return Int
*/
int add(User user);
/**
* 删除接口
* @Param Int id
* @return int
*/
int deleteByPrimary(Integer id);
/**
* 修改接口
* @Param User user
* @return int
*/
int updateByPrimaryKey(User user);
/**
* 单条查询接口
* @Param Integer id
* @return User
*/
User selectByPrimaryKey(Integer id);
/**
* 批量查询接口
* @Param User user
* @return List<User>
*/
List<User> selectByList();
}
User.java(model层)
package com.spring.coding.model;
public class User {
private Integer id;
private String userName;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User() {
}
public User(Integer id, String userName, String password) {
this.id = id;
this.userName = userName;
this.password = password;
}
}
UserService.java(Service层)
package com.spring.coding.service;
import com.spring.coding.model.User;
import java.util.List;
public interface UserService {
/**
* 添加接口
* @Param User user
* @return Int
*/
int add(User user);
/**
* 删除接口
* @Param Int id
* @return int
*/
int deleteByPrimary(Integer id);
/**
* 修改接口
* @Param User user
* @return int
*/
int updateByPrimaryKey(User user);
/**
* 单条查询接口
* @Param Integer id
* @return User
*/
User selectByPrimaryKey(Integer id);
/**
* 批量查询接口
* @Param User user
* @return List<User>
*/
List<User> selectByList();
}
UserServiceImpl.java(Service实现类)
package com.spring.coding.service.impl;
import com.spring.coding.mapper.UserMapper;
import com.spring.coding.model.User;
import com.spring.coding.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public int add(User user) {
return userMapper.add(user);
}
@Override
public int deleteByPrimary(Integer id) {
return userMapper.deleteByPrimary(id);
}
@Override
public int updateByPrimaryKey(User user) {
return userMapper.updateByPrimaryKey(user);
}
@Override
public User selectByPrimaryKey(Integer id) {
return userMapper.selectByPrimaryKey(id);
}
@Override
public List<User> selectByList() {
return userMapper.selectByList();
}
}
UserController.java(Controller层)
package com.spring.coding.controller;
import com.spring.coding.model.User;
import com.spring.coding.service.UserService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@RestController
@RequestMapping("/api")
public class UserController {
@Resource
private UserService userService;
/**
* 添加接口
* @Param User user
* @return String
*/
@PostMapping("/user/add")
public String addUser(@RequestBody User user) {
userService.add(user);
return "add";
}
/**
* 删除接口
* @Param Int id
* @return String
*/
@DeleteMapping("user/del/{id}")
public String delUser(@PathVariable("id") Integer id){
userService.deleteByPrimary(id);
return "delete";
}
/**
* 修改接口
* @Param User user
* @return int
*/
@PutMapping("/user/update")
public String updateUser(@RequestBody User user){
userService.updateByPrimaryKey(user);
return "update";
}
/**
* 单条查询接口
* @Param Integer id
* @return User
*/
@GetMapping("/user/{id}")
public String findUser(@PathVariable("id") Integer id) {
userService.selectByPrimaryKey(id);
return "select user one";
}
/**
* 批量查询接口
* @Param User user
* @return List<User>
*/
@GetMapping("/user/list")
public String findUserList() {
userService.selectByList();
return "select user list";
}
}
CodingApplication.java(主启动类)
package com.spring.coding;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.spring.coding.mapper")
public class CodingApplication {
public static void main(String[] args) {
SpringApplication.run(CodingApplication.class, args);
}
}
注意要点
- dao的名称需要与对应的mapper名称一致
- mapper的namespace对应dao的全路径
- dao 声明的方法mapper必须一致相同