springboot整合mybatis
CREATE TABLE restaurant.`user` (
id int auto_increment NOT NULL COMMENT '主键',
name varchar(20) NULL COMMENT '姓名',
age int NULL COMMENT '年龄',
sex char(1) NULL COMMENT '性别 0 男 1 女',
create_time DATETIME NULL COMMENT '创建时间',
CONSTRAINT user_pk PRIMARY KEY (id)
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8
COLLATE=utf8_general_ci;
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>3.0.2version>
dependency>
项目基于springboot3.x
其他依赖包
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>com.mysqlgroupId>
<artifactId>mysql-connector-jartifactId>
<version>8.0.33version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>5.8.20version>
dependency>
配置application.yml文件
# 数据源配置
spring:
datasource:
driverClassName: com.mysql.cj.jdbc.Driver
# 数据库地址
url: jdbc:mysql://你的数据库地址:3306/restaurant?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: 你的数据库用户名
password: 你的数据库密码
jackson:
property-naming-strategy: SNAKE_CASE # 小驼峰规则配置
default-property-inclusion: non_null # 序列化非null的属性
mybatis:
type-aliases-package: com.ndky.**.domain
mapper-locations: classpath*:mapper/**/*Mapper.xml
server:
port: 8088
代码如下:
实体User类
package com.ndky.helloworld.domain;
import lombok.Data;
import java.time.LocalDateTime;
/**
* @author LikeYouDo
* @date 2023/10/22 10:42
*/
@Data//使用lomok简化实体类代码,这里不再展开
public class User {
private Integer id;
private String name;
private Integer age;
private String sex;
private LocalDateTime createTime;
}
Mapper接口
package com.ndky.helloworld.mapper;
/**
* @author LikeYouDo
* @date 2023/10/22 11:41
*/
//可以通过使用注解@Mapper
//或者在Application启动类中添加注解扫描mapper包的方式扫描Mapper
//这里使用第二种
public interface UserMapper {
}
在Application类中添加@MapperScan扫描包路径
package com.ndky.mybatisdemo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.ndky.mybatisdemo.mapper") // +++
public class MybatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisDemoApplication.class, args);
}
}
IUserService业务接口及其实现类
package com.ndky.mybatisdemo.service;
/**
* @author LikeYouDo
* @date 2023/10/22 11:47
*/
public interface IUserService {
}
package com.ndky.mybatisdemo.service.impl;
import com.ndky.mybatisdemo.service.IUserService;
import org.springframework.stereotype.Service;
/**
* @author LikeYouDo
* @date 2023/10/22 11:48
*/
@Service
public class UserServiceImpl implements IUserService {
}
mybatis的xml用法不再赘述,可以跳转学习
package com.ndky.mybatisdemo.controller;
import com.ndky.mybatisdemo.domain.User;
import com.ndky.mybatisdemo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @author LikeYouDo
* @date 2023/10/12 15:17
*/
@RestController
@RequestMapping("/hello")
public class MybatisController {
@Autowired
private IUserService userService;
/**
* 获取所有数据
*
* @return
*/
@GetMapping()
public String getUsers() {
return userService.getUsers();
}
/**
* 根据id查询数据
*
* @param id
* @return
*/
@GetMapping("/{id}")
public String getUserById(@PathVariable("id") Integer id) {
return userService.getUserById(id);
}
/**
* 添加一个新的数据
*
* @param user
* @return
*/
@PostMapping()
public String postHello(@RequestBody User user) {
return userService.insertUser(user);
}
/**
* 根据id修改name
*
* @param user
* @return
*/
@PutMapping()
public String updateUser(@RequestBody User user) {
return userService.updateUser(user);
}
/**
* 根据id删除数据
* @param id
* @return
*/
@DeleteMapping("/{id}")
public String deleteUserById(@PathVariable Integer id) {
return userService.deleteUserById(id);
}
}
package com.ndky.mybatisdemo.service;
import com.ndky.mybatisdemo.domain.User;
/**
* @author LikeYouDo
* @date 2023/10/22 11:47
*/
public interface IUserService {
String getUsers();
String getUserById(Integer id);
String insertUser(User user);
String updateUser(User user);
String deleteUserById(Integer id);
}
package com.ndky.mybatisdemo.service.impl;
import com.ndky.mybatisdemo.domain.User;
import com.ndky.mybatisdemo.mapper.UserMapper;
import com.ndky.mybatisdemo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author LikeYouDo
* @date 2023/10/22 11:48
*/
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public String getUsers() {
return userMapper.selectUsers();
}
@Override
public String getUserById(Integer id) {
User user = userMapper.selectUserById(id);
return user==null?"没有查询到该用户":user.toString();
}
@Override
public String insertUser(User user) {
return userMapper.insertUser(user);
}
@Override
public String updateUser(User user) {
return userMapper.updateUser(user);
}
@Override
public String deleteUserById(Integer id) {
return userMapper.deleteUserById(id);
}
}
package com.ndky.mybatisdemo.mapper;
import com.ndky.mybatisdemo.domain.User;
import org.apache.ibatis.annotations.Mapper;
/**
* @author LikeYouDo
* @date 2023/10/22 11:41
*/
@Mapper
public interface UserMapper {
String selectUsers();
String selectUserById(Integer id);
String insertUser(User user);
String updateUser(User user);
String deleteUserById(Integer id);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ndky.mybatisdemo.mapper.UserMapper">
<resultMap id="UserResult" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age" />
<result property="sex" column="sex" />
<result property="createTime" column="create_time" />
resultMap>
<insert id="insertUser" parameterType="user">
insert into user(name,age,sex,create_time) values(#{name},#{age},#{sex},#{createTime})
insert>
<update id="updateUser" parameterType="user">
update user set name=#{name},age=#{age},sex=#{sex},create_time=#{createTime} where id=#{id}
update>
<delete id="deleteUserById">
delete from user where id = #{id}
delete>
<select id="selectUsers" resultMap="UserResult">
select * from user
select>
<select id="selectUserById" parameterType="integer" resultMap="UserResult">
select * from user where id = #{id}
select>
mapper>
查询所有user
根据id查询user
添加一个user
检测是否添加成功
对于时间的LocalDateTime类因为格式问题jackson无法进行数据转换,需要进行相关序列化配置
package com.ndky.mybatisdemo.config;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
/**
* 日期序列化
*
* @author kou
*/
@Configuration
public class LocalDateTimeSerializerConfig {
@Bean(name = "mapperObject")
public ObjectMapper getObjectMapper() {
ObjectMapper om = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
// 序列化
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
// 反序列化
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
om.registerModule(javaTimeModule);
// 或略不识别的字段
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return om;
}
}
配置后,修改前
修改后(可以正常接受yyyy-MM-dd HH:mm:ss格式的参数了,但是返回值还是会带T需要前端进行处理)
以上就是对mybatis的简单使用,对mybatis使用熟悉后,可以进行进阶学习MP(MybatisPlus)或者MF(MybatisFlex)来提升开发效率