SpringBoot整合Mybatis注解实战 -- 插入数据
程序员文章站
2022-08-10 19:03:52
1.数据库数据表的创建(1)首先,在本地数据库中创建一个新数据库,再此命名为test_mybatis_1;创建一个数据表user,创建脚本如下:/* user表创建脚本 */CREATE TABLE `user` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(128) DEFAULT NULL COMMENT '名称', `phone` varchar(16) DEFAULT NULL CO...
1.数据库数据表的创建
(1)首先,在本地数据库中创建一个新数据库,再此命名为test_mybatis_1;创建一个数据表user,创建脚本如下:
/* user表创建脚本 */
CREATE TABLE `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL COMMENT '名称',
`phone` varchar(16) DEFAULT NULL COMMENT '用户手机号',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`age` int(4) DEFAULT NULL COMMENT '年龄',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
(2)插入一些数据:
2.创建springboot项目,编写配置文件
(1)pom.xml(导入依赖)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.11.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.hlx</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot</name>
<description>Test project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 引入第三方数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
(2)配置文件application.properties
#mybatis.type-aliases-package=net.xdclass.base_project.domain
#可以自动识别
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test_mybatis_1?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
#如果不使用默认的数据源 (com.zaxxer.hikari.HikariDataSource)
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
(3)启动类添加mapper扫描
package com.hlx.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.hlx.springboot.mapper")
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
3.编写需要使用到的工具类
(1)响应结果类:JsonData.java
package com.hlx.springboot.domain;
import java.io.Serializable;
/**
* 功能描述:响应结果类
*/
public class JsonData implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer code; // 状态码 0 表示成功,1表示处理中,-1表示失败
private Object data; // 数据
private String msg;// 描述
public JsonData() {
}
public JsonData(Integer code, Object data, String msg) {
this.code = code;
this.data = data;
this.msg = msg;
}
// 成功,传入数据
public static JsonData buildSuccess() {
return new JsonData(0, null, null);
}
// 成功,传入数据
public static JsonData buildSuccess(Object data) {
return new JsonData(0, data, null);
}
// 失败,传入描述信息
public static JsonData buildError(String msg) {
return new JsonData(-1, null, msg);
}
// 失败,传入描述信息,状态码
public static JsonData buildError(String msg, Integer code) {
return new JsonData(code, null, msg);
}
// 成功,传入数据,及描述信息
public static JsonData buildSuccess(Object data, String msg) {
return new JsonData(0, data, msg);
}
// 成功,传入数据,及状态码
public static JsonData buildSuccess(Object data, int code) {
return new JsonData(code, data, null);
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return "JsonData [code=" + code + ", data=" + data + ", msg=" + msg
+ "]";
}
}
(2)Json工具类:JsonUtils.java
package com.hlx.springboot.utils;
import java.io.IOException;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtils {
private static ObjectMapper objectMapper = new ObjectMapper();
//对象转字符串
public static <T> String obj2String(T obj) {
if (obj == null) {
return null;
}
try {
return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//字符串转对象
public static <T> T string2Obj(String str, Class<T> clazz) {
if (StringUtils.isEmpty(str) || clazz == null) {
return null;
}
try {
return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
4.编写用户实体类(domain/User.java)
package com.hlx.springboot.domain;
import java.util.Date;
public class User {
private int id;
private String name;
private String phone;
private int age;
private Date createTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
5.编写访问数据库的接口(mapper/UserMapper.java)
package com.hlx.springboot.mapper;
import com.hlx.springboot.domain.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* 访问数据库的接口
*/
public interface UserMapper {
@Insert("INSERT INTO user(name,phone,create_time,age) VALUES(#{name}, #{phone}, #{createTime},#{age})")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
// keyProperty java对象的属性;keyColumn表示数据库的字段
int insert(User user);
}
6.编写service层接口及其实现类
(1)service/UserService.java
package com.hlx.springboot.service;
import com.hlx.springboot.domain.User;
public interface UserService {
public int add(User user);
}
(2)service/impl/UserServiceImpl.java
package com.hlx.springboot.service.impl;
import com.hlx.springboot.domain.User;
import com.hlx.springboot.mapper.UserMapper;
import com.hlx.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public int add(User user) {
userMapper.insert(user);
int id = user.getId();
return id;
}
}
7.编写Controller层(controller/UserController.java)
package com.hlx.springboot.controller;
import com.hlx.springboot.domain.JsonData;
import com.hlx.springboot.domain.User;
import com.hlx.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("add")
public Object add(String msg) {
User user = new User();
user.setAge(18);
user.setCreateTime(new Date());
user.setName("Rose");
user.setPhone("10010004");
int id = userService.add(user);
return JsonData.buildSuccess(id);
}
}
8.运行程序,访问http://localhost:8080/user/add,结果如下。
9.此时访问数据库查看数据,发现数据已经成功插入。
本文地址:https://blog.csdn.net/m0_38056893/article/details/110130213
上一篇: c# 动态构建LINQ查询表达式
推荐阅读
-
SpringBoot系列-整合Mybatis(注解方式)
-
SpringBoot+Mybatis+Durid整合多数据源的三种方式,第一种
-
SpringBoot整合Mybatis注解实战 -- 插入数据
-
SpringBoot整合MyBatis获得插入数据后获取主键,返回值总是1
-
springboot整合mybatis采用druid连接池对mysql,hive双数据源整合并打包
-
springboot多数据源配置mybatis采用druid连接池对mysql,hive双数据源整合
-
springboot 整合mybatis和druid数据源连接池
-
SpringBoot+Mybatis+Durid整合多数据源的三种方式,第三种(注解切换)
-
springboot+druid+mybatisplus使用注解整合连接多个数据库
-
第二十章、SpringBoot2.x整合Mybatis3.x注解配置(SpringBoot2.x)